1 /****************************************************************************
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/contact-us.
17 ** GNU Free Documentation License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Free
19 ** Documentation License version 1.3 as published by the Free Software
20 ** Foundation and appearing in the file included in the packaging of
21 ** this file. Please review the following information to ensure
22 ** the GNU Free Documentation License version 1.3 requirements
23 ** will be met: http://www.gnu.org/copyleft/fdl.html.
26 ****************************************************************************/
29 \page gettingstartedqt.html
31 \title Getting Started Programming with Qt
32 \ingroup gettingStarted
34 Welcome to the world of Qt--the cross-platform GUI toolkit. In
35 this getting started guide, we teach basic Qt knowledge by
36 implementing a simple Notepad application. After reading this
37 guide, you should be ready to delve into our overviews and API
38 documentation, and find the information you need for the
39 application you are developing.
41 The code for this tutorial is available in \c
42 {examples/tutorials/gettingStarted/gsQt} under your Qt
43 installation. If you are using the Qt SDK, you will find it in
44 \c{Examples/4.7/tutorials/gettingStarted/gsQt} (change \c{4.7} if
45 you are using a later Qt version).
47 \section1 Hello Notepad
49 In this first example, we simply create and show a text edit in a
50 window frame on the desktop. This represents the simplest possible
51 Qt program that has a GUI.
58 1 #include <QApplication>
59 2 #include <QTextEdit>
61 4 int main(int argv, char **args)
63 6 QApplication app(argv, args);
72 Let us go through the code line by line. In the first two lines, we
73 include the header files for QApplication and QTextEdit, which are
74 the two classes that we need for this example. All Qt classes have
75 a header file named after them.
77 Line 6 creates a QApplication object. This object manages
78 application-wide resources and is necessary to run any Qt program
79 that has a GUI. It needs \c argv and \c args because Qt accepts a
80 few command line arguments.
82 Line 8 creates a QTextEdit object. A text edit is a visual element
83 in the GUI. In Qt, we call such elements widgets. Examples of
84 other widgets are scroll bars, labels, and radio buttons. A widget
85 can also be a container for other widgets; a dialog or a main
86 application window, for example.
88 Line 9 shows the text edit on the screen in its own window frame.
89 Since widgets also function as containers (for instance a
90 QMainWindow, which has toolbars, menus, a status bar, and a few
91 other widgets), it is possible to show a single widget in its own
92 window. Widgets are not visible by default; the function
93 \l{QWidget::}{show()} makes the widget visible.
95 Line 11 makes the QApplication enter its event loop. When a Qt
96 application is running, events are generated and sent to the
97 widgets of the application. Examples of events are mouse presses
98 and key strokes. When you type text in the text edit widget, it
99 receives key pressed events and responds by drawing the text
102 To run the application, open a command prompt, and enter the
103 directory in which you have the \c .cpp file of the program. The
104 following shell commands build the program.
112 This will leave an executable in the \c part1 directory (note that
113 on Windows, you may have to use \c nmake instead of \c make. Also,
114 the executable will be placed in part1\\debug or part1\\release
115 (these directories are created when you run \c make). \c qmake is
116 Qt's build tool, which takes a configuration file. \c qmake
117 generates this for us when given the \c{-project} argument. Given
118 the configuration file (suffixed .pro), \c qmake produces a \c
119 make file that will build the program for you. We will look into
120 writing our own \c .pro files later.
129 \o Widgets and Window Geometry
130 \o \l{Window and Dialog Widgets}
132 \o Events and event handling
133 \o \l{The Event System}
136 \section1 Adding a Quit Button
138 In a real application, you will normally need more than one
139 widget. We will now introduce a QPushButton beneath the text edit.
140 The button will exit the Notepad application when pushed (i.e.,
141 clicked on with the mouse).
145 Let us take a look at the code.
150 3 int main(int argv, char **args)
152 5 QApplication app(argv, args);
154 7 QTextEdit *textEdit = new QTextEdit;
155 8 QPushButton *quitButton = new QPushButton("&Quit");
157 10 QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));
159 12 QVBoxLayout *layout = new QVBoxLayout;
160 13 layout->addWidget(textEdit);
161 14 layout->addWidget(quitButton);
164 17 window.setLayout(layout);
168 21 return app.exec();
172 Line 1 includes QtGui, which contains all of Qt's GUI classes.
174 Line 10 uses Qt's Signals and Slots mechanism to make the
175 application exit when the \gui {Quit button} is pushed. A slot is
176 a function that can be invoked at runtime using its name (as a
177 literal string). A signal is a function that when called will
178 invoke slots registered with it; we call that to connect the slot
179 to the signal and to emit the signal.
181 \l{QApplication::}{quit()} is a slot of QApplication that exits
182 the application. \l{QPushButton::}{clicked()} is a signal that
183 QPushButton emits when it is pushed. The static
184 QObject::connect() function takes care of connecting the slot to
185 the signal. SIGNAL() and SLOT() are two macros that take the
186 function signatures of the signal and slot to connect. We also
187 need to give pointers to the objects that should send and receive
190 Line 12 creates a QVBoxLayout. As mentioned, widgets can contain
191 other widgets. It is possible to set the bounds (the location and
192 size) of child widgets directly, but it is usually easier to use a
193 layout. A layout manages the bounds of a widget's children.
194 QVBoxLayout, for instance, places the children in a vertical row.
196 Line 13 and 14 adds the text edit and button to the layout. In
197 line 17, we set the layout on a widget.
207 \o \l{Signals & Slots}
210 \o \l{Layout Management},
211 \l{Widgets and Layouts},
214 \o The widgets that come with Qt
215 \o \l{Qt Widget Gallery},
219 \section1 Subclassing QWidget
221 When the user wants to quit an application, you might want to
222 pop-up a dialog that asks whether he/she really wants to quit. In
223 this example, we subclass QWidget, and add a slot that we connect
224 to the \gui {Quit button}.
228 Let us look at the code:
231 5 class Notepad : public QWidget
242 16 QTextEdit *textEdit;
243 17 QPushButton *quitButton;
247 The \c Q_OBJECT macro must be first in the class definition, and
248 declares our class as a \c QObject (Naturally, it must also
249 inherit from QObject). A \l{QObject} adds several abilities to a
250 normal C++ class. Notably, the class name and slot names can be
251 queried at run-time. It is also possible to query a slot's
252 parameter types and invoke it.
254 Line 13 declares the slot \c quit(). This is easy using the \c
255 slots macro. The \c quit() slot can now be connected to signals.
256 We will do that later.
258 Instead of setting up the GUI and connecting the slot in the \c
259 main() function, we now use \c{Notepad}'s constructor.
262 20 Notepad::Notepad()
264 22 textEdit = new QTextEdit;
265 23 quitButton = new QPushButton(tr("Quit"));
267 25 connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));
269 27 QVBoxLayout *layout = new QVBoxLayout;
270 28 layout->addWidget(textEdit);
271 29 layout->addWidget(quitButton);
273 31 setLayout(layout);
275 33 setWindowTitle(tr("Notepad"));
279 As you saw in the class definition, we use pointers to our \l
280 {QObject}s (\c textEdit and \c quitButton). As a rule, you should
281 always allocate \l{QObject}s on the heap and never copy them.
283 We now use the function \l{QObject::}{tr()} around our user
284 visible strings. This function is necessary when you want to
285 provide your application in more than one language (e.g. English
286 and Chinese). We will not go into details here, but you can follow
287 the \c {Qt Linguist} link from the learn more table.
289 Here is the \c quit() slot:
292 75 void Notepad::quit()
294 77 QMessageBox messageBox;
295 78 messageBox.setWindowTitle(tr("Notepad"));
296 79 messageBox.setText(tr("Do you really want to quit?"));
297 80 messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
298 81 messageBox.setDefaultButton(QMessageBox::No);
299 82 if (messageBox.exec() == QMessageBox::Yes)
304 We use the QMessageBox class to display a dialog that asks the
305 user whether he/she really wants to quit.
314 \o tr() and internationalization
315 \o \l{Qt Linguist Manual},
316 \l{Writing Source Code for Translation},
317 \l{Hello tr() Example},
318 \l{Internationalization with Qt}
320 \o QObjects and the Qt Object model (This is essential to understand Qt)
323 \o qmake and the Qt build system
327 \section2 Creating a .pro file
329 For this example, we write our own \c .pro file instead of
330 using \c qmake's \c -project option.
333 1 HEADERS = notepad.h
334 2 SOURCES = notepad.cpp \
338 The following shell commands build the example.
345 \section1 Using a QMainWindow
347 Many applications will benefit from using a QMainWindow, which has
348 its own layout to which you can add a menu bar, dock widgets, tool
349 bars, and a status bar. QMainWindow has a center area that can be
350 occupied by any kind of widget. In our case, we will place our
355 Let us look at the new \c Notepad class definition.
360 4 class Notepad : public QMainWindow
373 17 QTextEdit *textEdit;
375 19 QAction *openAction;
376 20 QAction *saveAction;
377 21 QAction *exitAction;
383 We include two more slots that can save and open a document. We
384 will implement these in the next section.
386 Often, in a main window, the same slot should be invoked by
387 several widgets. Examples are menu items and buttons on a tool
388 bar. To make this easier, Qt provides QAction, which can be given
389 to several widgets, and be connected to a slot. For instance, both
390 QMenu and QToolBar can create menu items and tool buttons from the
391 same \l{QAction}s. We will see how this works shortly.
393 As before, we use the \c {Notepad}s constructor to set up the
397 25 Notepad::Notepad()
399 27 openAction = new QAction(tr("&Open"), this);
400 28 saveAction = new QAction(tr("&Save"), this);
401 29 exitAction = new QAction(tr("E&xit"), this);
403 31 connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
404 32 connect(saveAction, SIGNAL(triggered()), this, SLOT(save()));
405 33 connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
407 35 fileMenu = menuBar()->addMenu(tr("&File"));
408 36 fileMenu->addAction(openAction);
409 37 fileMenu->addAction(saveAction);
410 38 fileMenu->addSeparator();
411 39 fileMenu->addAction(exitAction);
413 41 textEdit = new QTextEdit;
414 42 setCentralWidget(textEdit);
416 44 setWindowTitle(tr("Notepad"));
420 \l{QAction}s are created with the text that should appear on the
421 widgets that we add them to (in our case, menu items). If we also
422 wanted to add them to a tool bar, we could have given
423 \l{QIcon}{icons} to the actions.
425 When a menu item is clicked now, the item will trigger the action,
426 and the respective slot will be invoked.
435 \o Main windows and main window classes
436 \o \l{Application Main Window},
437 \l{Main Window Examples}
444 \section1 Saving and Loading
446 In this example, we will implement the functionality of the \c
447 open() and \c save() slots that we added in the previous example.
451 We will start with the \c open() slot:
454 48 void Notepad::open()
456 50 QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
457 51 tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
459 53 if (fileName != "") {
460 54 QFile file(fileName);
461 55 if (!file.open(QIODevice::ReadOnly)) {
462 56 QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
465 59 QTextStream in(&file);
466 60 textEdit->setText(in.readAll());
472 The first step is asking the user for the name of the file to
473 open. Qt comes with QFileDialog, which is a dialog from which the
474 user can select a file. The image above shows the dialog on
475 Kubuntu. The static \l{QFileDialog::}{getOpenFileName()} function
476 displays a modal file dialog. It returns the file path of the file
477 selected, or an empty string if the user canceled the dialog.
479 If we have a file name, we try to open the file with
480 \l{QIODevice::}{open()}, which returns true if the file could be
481 opened. We will not go into error handling here, but you can follow
482 the links from the learn more section. If the file could not be
483 opened, we use QMessageBox to display a dialog with an error
484 message (see the QMessageBox class description for further
487 Actually reading in the data is trivial using the QTextStream
488 class, which wraps the QFile object. The
489 \l{QTextStream::}{readAll()} function returns the contents of the
490 file as a QString. The contents can then be displayed in the text
491 edit. We then \l{QIODevice::}{close()} the file to return the file
492 descriptor back to the operating system.
494 Now, let us move on to the the \c save() slot.
497 65 void Notepad::save()
499 67 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "",
500 68 tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
502 70 if (fileName != "") {
503 71 QFile file(fileName);
504 72 if (!file.open(QIODevice::WriteOnly)) {
507 75 QTextStream stream(&file);
508 76 stream << textEdit->toPlainText();
516 When we write the contents of the text edit to the file, we use
517 the QTextStream class again. QTextStream can also write
518 \l{QString}s to the file with the << operator.
527 \o Files and I/O devices
534 This may not be true for the first release.
535 The Qt documentation comes with three getting started guides. You
536 have come to the end of the first, which concerns itself with
537 basic Qt concepts. We also have guides covering intermediate and
538 advanced topics. They are found here: You may also have noticed that the learn more sections in
539 this guide frequently linked to them.
540 Basic Qt Architecture