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.
First we subclassKXmlGuiWindow 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.
#include<QApplication>#include<QCommandLineParser>#include<KAboutData>#include<KLocalizedString>#include"mainwindow.h"intmain(intargc,char*argv[]){usingnamespaceQt::Literals::StringLiterals;QApplicationapp(argc,argv);KLocalizedString::setApplicationDomain("mainwindow");KAboutDataaboutData(u"mainwindow"_s,i18n("Main Window"),u"1.0"_s,i18n("A simple text area"),KAboutLicense::GPL,i18n("(c) 2024"),i18n("Educational application..."),u"https://apps.kde.org/someappname/"_s,u"submit@bugs.kde.org"_s);aboutData.addAuthor(i18n("John Doe"),i18n("Tutorial learner"),u"john.doe@example.com"_s,u"https://john-doe.example.com"_s,u"johndoe"_s);KAboutData::setApplicationData(aboutData);QCommandLineParserparser;aboutData.setupCommandLine(&parser);parser.process(app);aboutData.processCommandLine(&parser);MainWindow*window=newMainWindow();window->show();returnapp.exec();}
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.