Creating the main window

This tutorial shows you the magic of an application's most important thing: the main window.

Summary

This tutorial carries on from our [Hello World project]({{< ref "hello_world.md" >}}) and will introduce the KXmlGuiWindowarrow-up-right class.

In the previous tutorial, the program caused a dialog box to pop up. Now we are going to take steps towards creating a functioning application with a more advanced window structure.

KXmlGuiWindow

KXmlGuiWindowarrow-up-right provides a full main window view with menubars, toolbars, a statusbar and a main area in the centre for a large widget. For example, the help menu is predefined. Most KDE applications will derive from this class as it provides an easy way to define menu and toolbar layouts through XML files (this technology is called KXmlGuiarrow-up-right). While we will not be using it in this tutorial, we will use it in the next.

In order to have a useful KXmlGuiWindowarrow-up-right, we must subclass it. So we create two files, mainwindow.cpp and mainwindow.h, which will contain our code.

mainwindow.h

First we subclassarrow-up-right KXmlGuiWindowarrow-up-right with class MainWindow : public KXmlGuiWindow, then we declare the constructorarrow-up-right with MainWindow(QWidget *parent = nullptr);.

Finally, we declare a pointer to the object that will make up the bulk of our program, turning it into a text editor. KTextEditarrow-up-right is a generic rich text editing widget with some niceties like cursor auto-hiding and spell checking.

mainwindow.cpp

First, of course, we have to include the header file containing the class declaration.

Inside the constructor of our subclassed KXmlGuiWindowarrow-up-right, we initialize our KTextEditarrow-up-right textArea. Because textArea derives from QWidgetarrow-up-right and our KXmlGuiWindowarrow-up-right MainWindow derives from QMainWindowarrow-up-right, we can call QMainWindow::setCentralWidget()arrow-up-right to make our textArea occupy the empty area in the central section of our window.

Finally, KXmlGuiWindow::setupGUI()arrow-up-right is called which does a lot of behind-the-scenes stuff and creates the default menus (Settings, Help).

Back to main.cpp

In order to actually run this window, we need to add a few lines in main.cpp:

We include our new header file mainwindow.h. This lets us create our new MainWindow object which we then display near the end of the main function (by default, new window objects are hidden).

CMake

The best way to build the program is to use CMake. We add mainwindow.cpp to the sources list, include the XmlGui and TextWidgets frameworks, and replace all helloworld text with mainwindow.

CMakeLists.txt

Running our application

You can repeat the same steps provided in the [KXmlGui Hello World]({{< ref "hello_world#kxmlgui-running" >}}) to build and install the application. You can then run the project with:

or

Last updated