Creating the Main Window
This tutorial carries on from our Hello World project 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 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
, we must subclass it. So we create two files,
mainwindow.h, which will contain our code.
First we subclass
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.
is a generic rich text editing widget with some niceties like cursor auto-hiding and spell checking.
First, of course, we have to include the header file containing the class declaration.
Inside the constructor of our subclassed
, we initialize our
textArea derives from
MainWindow derives from
, we can call
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:
Again, 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).
The best way to build the program is to use CMake. We add
mainwindow.cpp to the sources list, include the
TextWidgets frameworks, and replace all
helloworld text with
Running our application
For mature projects, the best way to compile, link and run KDE software is to set up a correct build environment. But for a simple tutorial like this, it's enough to just create a build directory and build from there. Like before:
cmake -B build/ cmake --build build/ ./build/mainwindow