How to create an application with Qt and C++

This tutorial is an introduction to Qt programming and will teach you how to create an application with Qt and C++. Full project and source code are provided.

Qt logo header

Qt

Qt is a cross-platform framework and a collection of tools for creating applications which can run on desktop, embedded and mobile operating systems.

If you need to create an application with a GUI in C++ you should definitely consider Qt for it.

A simple example application

This tutorial will guide you through the creation of a basic window with a menu bar, a menu and a status bar. The final result while look like this:

How to create an application with Qt and C++

Nothing too fancy, but these are the basic elements of most desktop applications and you can use this code as starting template for your projects.

When working with Qt, especially when developing cross-platform software, it’s recommended to use Qt Creator as IDE.  The main reason is that Qt Creator is the official Qt IDE and it offers full integration with the framework and all the other development tools. Using other IDEs is possible, but I don’t recommend it and for this tutorial I will use Qt Creator.

Creating a new Qt project

The first step is to create a new project in Qt Creator from one of the available templates:

Qt Creator new project

For a graphical application you want to select the Qt Widgets Application template.

The second step is selecting a name for your project and a location where to save it. For my project I decided to use “BasicApplication” for the name, but obviously you can use anything you want.

The third step is selecting the kit(s) for building your application.

Qt Creator kit selection

Qt Creator kits are groups of settings used for building and running projects for different platforms.

I am developing on Linux so I am going for the kit Desktop Qt 5.7.0 GCC 64bit, but you might see different kits if developing on/for different platforms.

The fourth step is defining the details of the initial main window class that will be generated by the template.

Qt Creator class information

You can leave everything as it is, but make sure to uncheck the Generate form field. The form file is used by the integrated visual interface editor Qt Designer. We won’t need it because we will be coding the GUI from scratch.

In the final step of the project creation you will get a summary of what defined in the previous steps.

Qt Creator project summary

Here it’s also possible to set a version control system to use for the project, but feel free to not set any for now.

Clicking on the button Finish will create the project and generate 3 C++ files (main.cpp, MainWindow.h and MainWindow.cpp) and a project file used by Qt Creator and qmake (the Qt building tool) to build the project.

The main

The main function initialises the application, then creates and opens the main window:

int main(int argc, char * argv[])
{
	QApplication a(argc, argv);

	MainWindow w;
	w.show();

	return a.exec();
}

The last line of code launches the Qt application and waits for it to return an exit code before terminating the program.

The main window class

The main window is defined in the header file MainWindow.h and it inherits from QMainWindow:

class MainWindow : public QMainWindow
{
	Q_OBJECT

It’s important to include the Q_OBJECT macro in all the classes that are inheriting from QObject.

In this simple example the constructor is the only public function:

public:
	MainWindow(QWidget * parent = nullptr);

Finally some private slots are declared:

private slots:
	void OnFileNew();
	void OnFileOpen();
	void OnFileSave();
};

Slots are handlers used to do something when an event happens. They will be explained in more detail later.

The main window implementation

All the MainWindow methods, including the slots, are implemented in MainWindow.cpp.

Most of the code will be placed in the constructor because it’s there where the elements of the window are created.

Window settings

We can start with some basic settings:

MainWindow::MainWindow(QWidget * parent) : QMainWindow(parent)
{
	setWindowTitle("Basic Application");

	setMinimumSize(800, 450);

The function setWindowTitle sets the title of the window, whereas setMinimumSize sets the minimum size allowed when resizing it.

Adding a menu bar

Most applications have a menu bar with menus. Creating one in Qt is pretty simple:

	QMenuBar * menuBar = new QMenuBar(this);
	setMenuBar(menuBar);

Once the menu bar is created you need to set it for the main window calling the setMenuBar function.

After creating and setting the menu bar it’s time to create a first menu:

QMenu * menu = menuBar->addMenu("&File");

The “&” before “File” will enable the keyboard shortcut ALT+F to open the menu.

Now that we have a menu we can populate it with entries, which are QAction objects:

	// New
	QAction * action = new QAction("&New", this);
	connect(action, &QAction::triggered, this, &MainWindow::OnFileNew);
	menu->addAction(action);

	// Open
	action = new QAction("&Open", this);
	connect(action, &QAction::triggered, this, &MainWindow::OnFileOpen);
	menu->addAction(action);

	// Save
	action = new QAction("&Save", this);
	connect(action, &QAction::triggered, this, &MainWindow::OnFileSave);
	menu->addAction(action);

As you can see creating an entry and adding it to a menu is pretty straightforward.

What’s more interesting is connecting menu entries to functions so that something happens when they are clicked. This is achieved using the Qt function connect which in its standard format takes 4 parameters:

  1. sender – the element generating an event
  2. signal – the event generated by the sender
  3. receiver – the element receiving the event
  4. slot – the handler to execute when an event is received

In the case of the first menu entry we have the following scenario

  1. sender : action (the menu entry)
  2. signal : &QAction::triggered (a menu entry has been clicked)
  3. receiver : this (the event is handled by the MainWindow)
  4. slot : &MainWindow::OnFileNew (when the menu entry is clicked this function is called)

When building a menu it’s also possible to add a horizontal line to to separate logic blocks. It only takes one line of code:

	menu->addSeparator();

The final entry of the File menu is going to be one to exit from the application:

	// Exit
	action = new QAction("&Exit", this);
	connect(action, &QAction::triggered, this, &MainWindow::close);
	menu->addAction(action);

This entry is connected to the function close defined in QMainWindow which, as expected, will close the window when the menu entry is clicked.

Adding a status bar

A status bar is useful to show messages to the user. Creating one is pretty simple:

	QStatusBar * statusBar = new QStatusBar(this);
	setStatusBar(statusBar);

As for the menu bar, it’s important to remember to set the active status bar calling the setStatusBar function.

Implementing the slots

In this simple example all the slot functions do is setting a message to show in the status bar like in the following code:

void MainWindow::OnFileNew()
{
	statusBar()->showMessage("File -> New");
}

Obviously this is just an example and a real application will do something more useful with them.

Adding content to the window

Once the basic elements of the window have been created it’s time to add some content.

This is done by calling the function setCentralWidget and passing it a QWidget which contains the graphic elements the application needs to show and handle.

I decided to not add any central widget in my code to keep this example as simple as possible, but obviously you’ll need to do that in your application.

Source code

The full source code of this tutorial is available on GitHub and released under the Unlicense license.

References

All the Qt widgets discussed in this tutorial are documented in detail in the Qt Widgets C++ Classes section of the Qt documentation.

To learn more about Qt Creator check out the online manual.

Conclusion

This was a simple tutorial to teach you how to create an application with Qt and C++. If you have any question about the code explained here feel free to leave a comment.

If you found it helpful please feel free to share it on social media using the share buttons below.

Subscribe

Don’t forget to subscribe to the blog newsletter to get notified of future posts.

You can also get updates following me on Google+, LinkedIn and Twitter.

Leave a Comment

Your email address will not be published. Required fields are marked *