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 KXmlGuiWindow 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
KXmlGuiWindow 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 KXmlGui). While we will not be using it in this tutorial, we will use it in the next.
In order to have a useful KXmlGuiWindow, we must subclass it. So we create two files, mainwindow.cpp
and mainwindow.h
, which will contain our code.
mainwindow.h
First we subclass KXmlGuiWindow with class MainWindow : public KXmlGuiWindow
, then we declare the constructor 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. KTextEdit
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 KXmlGuiWindow, we initialize our KTextEdit textArea
. Because textArea
derives from QWidget and our KXmlGuiWindow MainWindow
derives from QMainWindow, we can call QMainWindow::setCentralWidget() to make our textArea
occupy the empty area in the central section of our window.
Finally, KXmlGuiWindow::setupGUI() 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