summaryrefslogtreecommitdiffstats
path: root/doc/src/getting-started/gettingstartedqt.qdoc
blob: 07f75f5bbaac93e6ddcd413e63a417ecd824a5c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Free Documentation License Usage
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of
** this file.  Please review the following information to ensure
** the GNU Free Documentation License version 1.3 requirements
** will be met: http://www.gnu.org/copyleft/fdl.html.
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
    \page gettingstartedqt.html

    \title Getting Started Programming with Qt Widgets

    In this topic, we teach basic Qt knowledge by implementing a simple Notepad
    application using C++ and the \l{Qt Widgets} module. We use the
    Qt Creator IDE and Qt Designer to generate some code, but you could also write all the
    code yourself.

    After reading this topic, you are ready to refer to our overviews and API
    documentation, to find the information you need for the application you are
    developing.

    In this topic, we first use Qt Creator to create a project with the
    necessary files. Then we use Qt Designer to modify the user interface files
    to show a text edit and a push button in a window on the desktop.
    This represents a simple Qt application that has a GUI. Finally, we add
    user interaction to the application by creating actions for opening and
    saving files.

    \image gs1.png "Notepad application"

    You can find the final Notepad source files in the qtdoc repository in the
    snippets/widgets-tutorial/notepad directory. You can either fetch
    the Qt 5 sources from Qt Project or install them as part of Qt 5.

    \section1 Creating the Notepad Project

    Setting up a new project in Qt Creator is aided by a wizard that guides you
    step-by-step through the project creation process. The wizard prompts you
    to enter the settings needed for that particular type of project and creates
    the project for you.

    \image gs-project1.png "Qt Creator New File or Project dialog"

    To create the Notepad project, select \b File > \b{New File or Project} >
    \b Applications > \b {Qt Gui Application} > \b Choose, and follow the
    instructions of the wizard. In the \b {Class Information} dialog, type
    \b Notepad as the class name and select \b QMainWindow as the base class.

    \image gs-project2.png "Class Information Dialog"

    The \b {Qt Gui Application} wizard creates a project that contains a main
    source file and a set of files that specify a user interface (Notepad
    widget):

    \list
        \li notepad.pro - the project file.
        \li main.cpp - the main source file for the application.
        \li notepad.cpp - the source file of the notepad class of the Notepad
            widget.
        \li notepad.h - the header file of the notepad class for the Notepad
            widget.
        \li notepad.ui - the UI form for the Notepad widget.
    \endlist

    The .cpp, .h, and .ui files come with the necessary boiler plate code for
    you to be able to build and run the project. The .pro file is complete.
    We will take a closer look at the file contents in the following sections.

    \b{Learn More}

    \table
        \header
            \li About
            \li Here
        \row
            \li Using Qt Creator
            \li \l{Qt Creator Manual}{Qt Creator}
        \row
            \li Creating other kind of applications with Qt Creator
            \li \l{Tutorials for Creator}{Qt Creator Tutorials}
    \endtable


    \section1 Main Source File

    The wizard generates the following code in the main.cpp file:

    \snippet snippets/widgets-tutorial/notepad/main.cpp all

    Let us go through the code line by line. On the first two lines, we include
    the header files for the Notepad widget and QApplication. All Qt classes
    have a header file named after them.

    Line 4 defines the main function that is the entry point for all C and C++
    based applications.

    Line 6 creates a QApplication object. This object manages
    application-wide resources and is necessary to run any Qt program
    that uses Qt Widgets. It constructs an application object with \c argc command
    line arguments run in \c argv. (For GUI applications that do not use Qt Widgets, you can use
    QGuiApplication instead.)

    Line 7 creates the Notepad object. This is the object for which the wizard
    created the class and the UI file. The user interface contains visual
    elements that are called \c widgets in Qt. Examples of widgets are text
    edits, scroll bars, labels, and radio buttons. A widget can also be a
    container for other widgets; a dialog or a main application window, for
    example.

    Line 8 shows the Notepad widget on the screen in its own window.
    Since widgets also function as containers (for instance a
    QMainWindow, which has toolbars, menus, a status bar, and a few
    other widgets), it is possible to show a single widget in its own
    window. Widgets are not visible by default; the function
    \l{QWidget::}{show()} makes the widget visible.

    Line 10 makes the QApplication enter its event loop. When a Qt
    application is running, events are generated and sent to the
    widgets of the application. Examples of events are mouse presses
    and key strokes.

    \b{Learn More}

    \table
        \header
            \li About
            \li Here
        \row
            \li Widgets and Window Geometry
            \li \l{Window and Dialog Widgets}
        \row
            \li Events and event handling
            \li \l{The Event System}
    \endtable

    \section1 Designing a UI

    The wizard generates a user interface definition in XML format, notepad.ui.
    When you open the notepad.ui file in Qt Creator, it automatically opens
    in the integrated Qt Designer.

    When you build the application, Qt Creator launches the Qt
    \l{User Interface Compiler (uic)} that reads the .ui file and creates a
    corresponding C++ header file, ui_notepad.h.

    \section2 Using Qt Designer

    The wizard creates an application that uses a QMainWindow. It has its own
    layout to which you can add a menu bar, dock widgets, tool bars, and a
    status bar. The center area can be occupied by any kind of widget. The
    wizard places the Notepad widget there.

    Let us use Qt Designer to add a QTextEdit object and a QPushButton object to
    the main window. When you type text in the text edit widget, it receives key
    pressed events and responds by drawing the text typed. The button will exit
    the Notepad application when pushed (that is, clicked with the mouse).

    To add widgets in Qt Designer:

    \list 1
        \li In the Qt Creator \b Editor mode, double-click the notepad.ui file
            in the \b Projects view to launch the file in the integrated Qt
            Designer.
        \li Drag and drop the following widgets to the form:
            \list
                \li Text Edit (QTextEdit)
                \li Push Button (QPushButton)
            \endlist
        \li Double-click the \b {Push Button} widget and enter the text \b Quit.
        \li In the \b Properties pane, change the value of \b objectName to
            \b quitButton.
        \li Press \b {Ctrl+A} (or \b {Cmd+A}) to select the widgets and click
            \b {Lay out Vertically} (or press \b {Ctrl+L}) to apply a vertical
            layout (QVBoxLayout).
        \li Press \b {Ctrl+S} (or \b {Cmd+S}) to save your changes.
    \endlist

    The UI now looks as follows in Qt Designer:

    \image gs2.png

    You can view the generated XML file in the code editor:

    \quotefromfile snippets/widgets-tutorial/notepad/notepad.ui

    \printuntil QMenuBar
    \dots

    Line 1 contains the XML declaration, which specifies the XML version and
    character encoding used in the document.

    Line 2 creates an \c ui element that defines a Notepad widget.

    Line 26 creates a QVBoxLayout widget that contains a QTextEdit
    and QPushButton widget. As mentioned, widgets can contain
    other widgets. It is possible to set the bounds (the location and
    size) of child widgets directly, but it is usually easier to use a
    layout. A layout manages the bounds of a widget's children.
    QVBoxLayout, for instance, places the children in a vertical row.

    The UI file is used together with the header and source file of the Notepad
    class. We will look at the rest of the UI file in the later sections.

    \section2 Notepad Header File

    The wizard generated a header file for the Notepad class that has the
    necessary #includes, a constructor, a destructor, and the Ui object. The
    file looks as follows:

    \snippet snippets/gs/notepad1.h all

    Line 4 includes QMainWindow that provides a main application window.

    Line 6 declares the Notepad class in the Ui namespace, which is the
    standard namespace for the UI classes generated from .ui files by the
    \c uic tool.

    Line 10 contains the \c Q_OBJECT macro. It must come first in the class
    definition, and declares our class as a QObject. Naturally, it must also
    inherit from QObject. A QObject adds several abilities to a normal C++
    class. Notably, the class name and slot names can be
    queried at run-time. It is also possible to query a slot's
    parameter types and invoke it.

    Line 15 declares a constructor that has a default argument called \c parent.
    The value 0 indicates that the widget has no parent (it is a top-level
    widget).

    Line 16 declares a virtual destructor to free the resources that were
    acquired by the object during its life-cycle. According to the C++
    naming convention, destructors have the same name as the class they are
    associated with, prefixed with a tilde (~). In QObject, destructors are
    virtual to ensure that the destructors of derived classes are invoked
    properly when an object is deleted through a pointer-to-base-class.

    Line 19 declares a member variable which is a pointer to the Notepad UI
    class. A member variable is associated with a specific class, and accessible
    for all its methods.

    \section2 Notepad Source File

    The source file that the wizard generated for the Notepad class looks as
    follows:

    \snippet snippets/gs/notepad1.cpp all

    The first two lines include the Notepad class header file that was generated
    by the wizard and the UI header file that was generated by the \c uic tool.

    Line 4 defines the \c {Notepad} constructor and sets up the UI file.

    Line 5 calls the QMainWindow constructor, which is the base class for the
    Notepad class.

    Line 6 creates the UI class instance and assigns it to the \c ui member.

    Line 8 sets up the UI.

    Line 11 destructs the \c ui.

    \section2 Project File

    The wizard generates the following project file, \c {notepad.pro}, for us:

    \quotefile snippets/widgets-tutorial/notepad/notepad.pro

    The project file specifies the application name and the \c qmake template to
    use for generating the project, as well as the source, header, and UI files
    included in the project.

    You could also use \c qmake's \c -project option to generate the \.pro file. Although,
    in that case, you have to remember to add the line \c{QT += widgets} to the generated
    file in order to link against the Qt Widgets Module.

    \b{Learn More}

    \table
        \header
            \li About
            \li Here
        \row
            \li Using Qt Designer
            \li \l{Qt Designer Manual}
        \row
            \li Layouts
            \li \l{Layout Management},
               \l{Widgets and Layouts},
               \l{Layout Examples}
        \row
            \li The widgets that come with Qt
            \li \l{Qt Widget Gallery}
        \row
            \li Main windows and main window classes
            \li \l{Application Main Window},
               \l{Main Window Examples}
        \row
            \li QObjects and the Qt Object model (This is essential to
                understand Qt)
            \li \l{Object Model}
        \row
            \li qmake and the Qt build system
            \li \l{qmake Manual}
    \endtable

    \section1 Adding User Interaction

    We now have a user interface, but it does not really do anything useful, as
    it only contains a text edit and a push button, as well as some standard
    functions for quitting, minimizing and maximizing the application. To make
    the application useful, we will add user interaction to it. First, we will
    add functionality to the push button. Second, we will add functions for
    loading a file to the text edit and for saving the contents of the text edit
    as a file.

    \section2 Adding Push Buttons

    Most desktop operating systems have standard ways of enabling users to quit
    applications. However, in this example we use this basic function to
    illustrate how you can add user interaction to applications. To do this, we
    add a slot that we connect to the \b {Quit button}.

    To exit the application when the \b Quit button is pushed, you use the Qt
    signals and slots mechanism. A signal is emitted when a particular event
    occurs and a slot is a function that is called in response to a particular
    signal. Qt widgets have predefined signals and slots that you can use
    directly from Qt Designer.

    To use Qt Designer to add a slot for the quit function, right-click the
    \b Quit button to open a context-menu and then select \b {Go to slot} >
    \b {clicked()}.

    A private slot, \c{on_quitButton_clicked()}, is added to the Notepad widget
    class header file, notepad.h and a private function,
    \c{Notepad::on_quitButton_clicked()}, is added to the Notepad widget class
    source file, notepad.cpp. We just need to write the code to execute the quit
    function in the source file.

    Let us look at the modified code in the header file, notepad.h:

    \snippet snippets/gs/notepad2.h all

    Line 14 uses Qt's signals and slots mechanism to make the
    application exit when the \b {Quit button} is pushed. Qt Designer uses
    QMetaObject \l{designer-using-a-ui-file.html#automatic-connections}
    {auto-connection facilities} to connect the button's clicked() signal to a
    slot in the Notepad class. The \c uic tool automatically generates code in
    the dialog's \c{setupUi()} function to do this, so Qt Designer only needs to
    declare and implement a slot with a name that follows a standard convention.

    The corresponding code in the source file, notepad.cpp, looks as follows:

    \snippet snippets/gs/notepad2.cpp all

    The code defines the private function that is executed when QPushButton
    emits the \l{QPushButton::}{clicked()} signal.

    We now complement the code to have the \l{QApplication::}{quit()} slot of
    QApplication exit Notepad:

    \snippet snippets/widgets-tutorial/notepad/notepad.cpp 1

    \b{Learn More}

    \table
        \header
            \li About
            \li Here
         \row
            \li Signals and slots
            \li \l{Signals & Slots}
    \endtable

    \section2 Adding Menu Items

    Often, in a main window, the same slot should be invoked by
    several widgets. Examples are menu items and buttons on a tool
    bar. To make this easier, Qt provides QAction, which can be given
    to several widgets, and be connected to a slot. For instance, both
    QMenu and QToolBar can create menu items and tool buttons from the
    same \l{QAction}.

    To learn how to use actions with signals and slots, we add menu items to
    open and save a document and connect them to slots.

    As before, we use Qt Designer to add the widgets to the user interface.
    The wizard creates an application with a QMenu widget, with the text
    \b {Type Here} as a placeholder for menu and menu item names. Double-click
    the text to enter names for the \b File menu and \b Open and \b Save menu
    items. Qt Designer automatically generates the appropriate actions.

    \image gs3.png

    To connect the actions to slots, right-click an action and select
    \b {Go to slot} > \b triggered().

    \l{QAction} instances are created with the text that should appear on the
    widgets that we add them to (in our case, menu items). If we also
    wanted to add the actions to a tool bar, we could have specified
    \l{QIcon}{icons} for them.

    The modified code in notepad.ui now looks as follows:

    \quotefromfile snippets/widgets-tutorial/notepad/notepad.ui

    \skipto QMenuBar
    \printto layoutdefault

    Qt Designer adds the private slots \c{on_actionOpen_triggered()} and
    \c{on_actionSave_triggered()} to notepad.h and the private functions
    \c{Notepad::on_actionOpen_triggered()} and
    \c{Notepad::on_actionSave_triggered()} to notepad.cpp.

    In the following sections, we complement the code to load and save files.
    When a menu item is clicked, the item triggers the action, and the
    respective slot is invoked.

    \section2 Opening Files

    In this section, we implement the functionality of the
    \c{on_actionOpen_triggered()} slot. The first step is asking the user for
    the name of the file to open. Qt comes with QFileDialog, which is a dialog
    from which the user can select a file. The appearance of the dialog depends
    on the desktop platform that you run the application on. The following
    image shows the dialog on Mac OS:

    \image gs4.png

    We complement the code generated by Qt Designer in notepad.cpp, as follows:

    \snippet snippets/widgets-tutorial/notepad/notepad.cpp 2

    The static \l{QFileDialog::}{getOpenFileName()} function
    displays a modal file dialog. It returns the file path of the file
    selected, or an empty string if the user canceled the dialog.

    If we have a file name, we try to open the file with
    \l{QIODevice::}{open()}, which returns true if the file could be
    opened. We will not go into error handling here, but you can follow
    the links from the learn more section. If the file could not be
    opened, we use QMessageBox to display a dialog with an error
    message (see the QMessageBox class description for further
    details).

    Actually reading in the data is trivial using the QTextStream
    class, which wraps the QFile object. The
    \l{QTextStream::}{readAll()} function returns the contents of the
    file as a QString. The contents can then be displayed in the text
    edit. We then \l{QIODevice::}{close()} the file to return the file
    descriptor back to the operating system.

    We now use the function \l{QObject::}{tr()} around our user
    visible strings. This function is necessary when you want to
    provide your application in more than one language (for example, English
    and Chinese). We will not go into details here, but you can follow
    the \c {Qt Linguist} link from the learn more table.

    To use QFileDialog, QFile, QMessageBox, and QTextStream, add the following
    includes to notepad.cpp:

    \snippet snippets/widgets-tutorial/notepad/notepad.cpp 0

    \section2 Saving Files

    Now, let us move on to the \c{on_actionSave_triggered()} slot, which
    also uses QFileDialog to create a dialog in which the user can save a
    file with the specified name in the specified location.

    \image gs5.png

    We complement the code generated by Qt Designer in notepad.cpp, as follows:

    \snippet snippets/widgets-tutorial/notepad/notepad.cpp 3

    When we write the contents of the text edit to the file, we use
    the QTextStream class again. QTextStream can also write
    \l{QString}s to the file with the << operator.

    \b{Learn More}

    \table
        \header
            \li About
            \li Here
        \row
            \li MDI applications
            \li QMdiArea,
               \l{MDI Example}
        \row
            \li Files and I/O devices
            \li QFile, QIODevice
        \row
            \li tr() and internationalization
            \li \l{Qt Linguist Manual},
               \l{Writing Source Code for Translation},
               \l{Internationalization with Qt}
    \endtable

    \section1 Building and Running Notepad

    Now that you have all the necessary files, select \b Build >
    \b {Build Project Notepad} to build and run the application. Qt Creator
    uses \c qmake and \c make to create an executable in the directory
    specified in the build settings of the project and runs it.

    \section2 Building and Running from the Command Line

    To build the application from the command line, switch to the
    directory in which you have the \c .cpp file of the application and add the
    project file (suffixed .pro) described earlier. The following shell commands
    then build the application:

    \code
        qmake
        make (or nmake on Windows)
    \endcode

    The commands create an executable in the project directory. The \c qmake tool reads the
    project file and produces a \c Makefile with instructions on how to build the application.
    The \c make tool (or the \c nmake tool) then reads the \c Makefile and produces the executable
    binary.
*/