Getting Started Programming with Qt Widgets▲
In this topic, we teach basic Qt knowledge by implementing a simple Notepad application using C++ and the Qt Widgets module. The application is a small text editor which allows you to create a text file, save it, print it, or reopen and edit it again. You can also set the font to be used.
You can find the final Notepad source files in the qtdoc repository in the tutorials/notepad directory. You can either fetch the Qt 5 sources from Qt Project or install them as part of Qt 5. The application is also available in the example list of Qt Creator's Welcome mode.
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.
To create the Notepad project, select File > New File or Project > Applications > Qt Widgets Application > Choose, and follow the instructions of the wizard. In the Class Information dialog, type Notepad as the class name and select QMainWindow as the base class.
The Qt Widgets Application wizard creates a project that contains a main source file and a set of files that specify a user interface (Notepad widget):
-
notepad.pro - the project file.
-
main.cpp - the main source file for the application.
-
notepad.cpp - the source file of the notepad class of the Notepad widget.
-
notepad.h - the header file of the notepad class for the Notepad widget.
-
notepad.ui - the UI form for the Notepad widget.
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.
Learn More
About |
Here |
---|---|
Using Qt Creator |
|
Creating other kind of applications with Qt Creator |
Main Source File▲
The wizard generates the following code in the main.cpp file:
#include
"notepad.h"
#include <QApplication>
int
main(int
argc, char
*
argv[])
{
QApplication EditorApp(argc, argv);
Notepad Editor;
Editor.show();
return
EditorApp.exec();
}
We will go through the code line by line. The following lines include the header files for the Notepad widget and QApplication. All Qt classes have a header file named after them.
#include
"notepad.h"
#include <QApplication>
The following line defines the main function that is the entry point for all C and C++ based applications:
int
main(int
argc, char
*
argv[])
The following line 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 argc command line arguments run in argv. (For GUI applications that do not use Qt Widgets, you can use QGuiApplication instead.)