Export translations SettingsGroupCategory:PhononContribute/List of KDE ModulesDevelopmentDevelopment/FAQs/General FAQDevelopment/FAQs/Technical FAQDevelopment/KDevelop-PG-Qt IntroductionDevelopment/ToolsDevelopment/TutorialsDevelopment/Tutorials/CommandLineArgumentsDevelopment/Tutorials/Common Programming MistakesDevelopment/Tutorials/First programDevelopment/Tutorials/First program/KDE4Development/Tutorials/First program/KF5Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for BeginnersDevelopment/Tutorials/Metadata/Nepomuk/TipsAndTricksDevelopment/Tutorials/Physical SimulationDevelopment/Tutorials/Qt4 Ruby TutorialDevelopment/Tutorials/Qt4 Ruby Tutorial/Chapter 01Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3Development/Tutorials/Saving and loadingDevelopment/Tutorials/Setting UpDevelopment/Tutorials/Using ActionsDevelopment/Tutorials/Using KXmlGuiWindowDocumentation PrimerEdit MarkupGetting StartedHelp:ContentsHelp:ContributeHow To Convert a UserBase Manual to DocbookKDE FrameworksKDE Frameworks/Getting StartedKDE Frameworks/Getting Started/Source CodeKDE TechBase:AboutKDE TechBase:ContributorsKDE TechBase:General disclaimerKDE TechBase:Privacy policyOff-line TranslationProjects/Calligra/Plugin TutorialsToolboxTranslate a PageTranslation WorkflowTypographical GuidelinesUser:NeverendingoWelcome to KDE TechBaseLanguageaa - Afarab - Abkhazianabs - Ambonese Malayace - Achineseady - Adygheady-cyrl - Adyghe (Cyrillic script)aeb - Tunisian Arabicaeb-arab - Tunisian Arabic (Arabic script)aeb-latn - Tunisian Arabic (Latin script)af - Afrikaansak - Akanaln - Gheg Albanianalt - Southern Altaiam - Amharicami - Amisan - Aragoneseang - Old Englishanp - Angikaar - Arabicarc - Aramaicarn - Mapuchearq - Algerian Arabicary - Moroccan Arabicarz - Egyptian Arabicas - Assamesease - American Sign Languageast - Asturianatj - Atikamekwav - Avaricavk - Kotavaawa - Awadhiay - Aymaraaz - Azerbaijaniazb - South Azerbaijaniba - Bashkirban - Balinesebar - Bavarianbbc - Batak Tobabbc-latn - Batak Toba (Latin script)bcc - Southern Balochibcl - Central Bikolbe - Belarusianbe-tarask - Belarusian (Taraškievica orthography)bg - Bulgarianbgn - Western Balochibh - Bhojpuribho - Bhojpuribi - Bislamabjn - Banjarbm - Bambarabn - Banglabo - Tibetanbpy - Bishnupriyabqi - Bakhtiaribr - Bretonbrh - Brahuibs - Bosnianbtm - Batak Mandailingbto - Iriga Bicolanobug - Buginesebxr - Russia Buriatca - Catalancbk-zam - Chavacanocdo - Min Dong Chinesece - Chechenceb - Cebuanoch - Chamorrocho - Choctawchr - Cherokeechy - Cheyenneckb - Central Kurdishco - Corsicancps - Capiznoncr - Creecrh - Crimean Turkishcrh-cyrl - Crimean Tatar (Cyrillic script)crh-latn - Crimean Tatar (Latin script)cs - Czechcsb - Kashubiancu - Church Slaviccv - Chuvashcy - Welshda - Danishde - Germande-at - Austrian Germande-ch - Swiss High Germande-formal - German (formal address)din - Dinkadiq - Zazakidsb - Lower Sorbiandtp - Central Dusundty - Dotelidv - Divehidz - Dzongkhaee - Eweegl - Emilianel - Greekeml - Emiliano-Romagnoloen - Englishen-ca - Canadian Englishen-gb - British Englisheo - Esperantoes - Spanishes-419 - Latin American Spanishes-formal - español (formal)et - Estonianeu - Basqueext - Extremaduranfa - Persianff - Fulahfi - Finnishfit - Tornedalen Finnishfj - Fijianfo - Faroesefr - Frenchfrc - Cajun Frenchfrp - Arpitanfrr - Northern Frisianfur - Friulianfy - Western Frisianga - Irishgag - Gagauzgan - Gan Chinesegan-hans - Gan (Simplified)gan-hant - Gan (Traditional)gcr - Guianan Creolegd - Scottish Gaelicgl - Galicianglk - Gilakign - Guaranigom - Goan Konkanigom-deva - Goan Konkani (Devanagari script)gom-latn - Goan Konkani (Latin script)gor - Gorontalogot - Gothicgrc - Ancient Greekgsw - Swiss Germangu - Gujaratigv - Manxha - Hausahak - Hakka Chinesehaw - Hawaiianhe - Hebrewhi - Hindihif - Fiji Hindihif-latn - Fiji Hindi (Latin script)hil - Hiligaynonho - Hiri Motuhr - Croatianhrx - Hunsrikhsb - Upper Sorbianht - Haitian Creolehu - Hungarianhu-formal - magyar (formal)hy - Armenianhyw - Western Armenianhz - Hereroia - Interlinguaid - Indonesianie - Interlingueig - Igboii - Sichuan Yiik - Inupiaqike-cans - Eastern Canadian (Aboriginal syllabics)ike-latn - Eastern Canadian (Latin script)ilo - Ilokoinh - Ingushio - Idois - Icelandicit - Italianiu - Inuktitutja - Japanesejam - Jamaican Creole Englishjbo - Lojbanjut - Jutishjv - Javaneseka - Georgiankaa - Kara-Kalpakkab - Kabylekbd - Kabardiankbd-cyrl - Kabardian (Cyrillic script)kbp - Kabiyekg - Kongokhw - Khowarki - Kikuyukiu - Kirmanjkikj - Kuanyamakjp - Eastern Pwokk - Kazakhkk-arab - Kazakh (Arabic script)kk-cn - Kazakh (China)kk-cyrl - Kazakh (Cyrillic script)kk-kz - Kazakh (Kazakhstan)kk-latn - Kazakh (Latin script)kk-tr - Kazakh (Turkey)kl - Kalaallisutkm - Khmerkn - Kannadako - Koreanko-kp - Korean (North Korea)koi - Komi-Permyakkr - Kanurikrc - Karachay-Balkarkri - Kriokrj - Kinaray-akrl - Karelianks - Kashmiriks-arab - Kashmiri (Arabic script)ks-deva - Kashmiri (Devanagari script)ksh - Colognianku - Kurdishku-arab - Kurdish (Arabic script)ku-latn - Kurdish (Latin script)kum - Kumykkv - Komikw - Cornishky - Kyrgyzla - Latinlad - Ladinolb - Luxembourgishlbe - Laklez - Lezghianlfn - Lingua Franca Novalg - Gandali - Limburgishlij - Ligurianliv - Livonianlki - Lakilld - Ladinlmo - Lombardln - Lingalalo - Laoloz - Lozilrc - Northern Lurilt - Lithuanianltg - Latgalianlus - Mizoluz - Southern Lurilv - Latvianlzh - Literary Chineselzz - Lazmai - Maithilimap-bms - Basa Banyumasanmdf - Mokshamg - Malagasymh - Marshallesemhr - Eastern Marimi - Maorimin - Minangkabaumk - Macedonianml - Malayalammn - Mongolianmni - Manipurimnw - Monmo - Moldovanmr - Marathimrj - Western Marims - Malaymt - Maltesemus - Muscogeemwl - Mirandesemy - Burmesemyv - Erzyamzn - Mazanderanina - Naurunah - Nāhuatlnan - Min Nan Chinesenap - Neapolitannb - Norwegian Bokmålnds - Low Germannds-nl - Low Saxonne - Nepalinew - Newaring - Ndonganiu - Niueannl - Dutchnl-informal - Nederlands (informeel)nn - Norwegian Nynorskno - Norwegiannov - Novialnqo - N’Konrm - Normannso - Northern Sothonv - Navajony - Nyanjanys - Nyungaroc - Occitanolo - Livvi-Karelianom - Oromoor - Odiaos - Osseticpa - Punjabipag - Pangasinanpam - Pampangapap - Papiamentopcd - Picardpdc - Pennsylvania Germanpdt - Plautdietschpfl - Palatine Germanpi - Palipih - Norfuk / Pitkernpl - Polishpms - Piedmontesepnb - Western Punjabipnt - Ponticprg - Prussianps - Pashtopt - Portuguesept-br - Brazilian Portuguesequ - Quechuaqug - Chimborazo Highland Quichuargn - Romagnolrif - Riffianrm - Romanshrmy - Vlax Romanirn - Rundiro - Romanianroa-tara - Tarantinoru - Russianrue - Rusynrup - Aromanianruq - Megleno-Romanianruq-cyrl - Megleno-Romanian (Cyrillic script)ruq-latn - Megleno-Romanian (Latin script)rw - Kinyarwandasa - Sanskritsah - Sakhasat - Santalisc - Sardinianscn - Siciliansco - Scotssd - Sindhisdc - Sassarese Sardiniansdh - Southern Kurdishse - Northern Samisei - Serises - Koyraboro Sennisg - Sangosgs - Samogitiansh - Serbo-Croatianshi - Tachelhitshi-latn - Tachelhit (Latin script)shi-tfng - Tachelhit (Tifinagh script)shn - Shanshy-latn - Shawiya (Latin script)si - Sinhalasimple - Simple Englishsk - Slovakskr - Saraikiskr-arab - Saraiki (Arabic script)sl - Sloveniansli - Lower Silesiansm - Samoansma - Southern Samismn - Inari Samisn - Shonaso - Somalisq - Albaniansr - Serbiansr-ec - Serbian (Cyrillic script)sr-el - Serbian (Latin script)srn - Sranan Tongoss - Swatist - Southern Sothostq - Saterland Frisiansty - себертатарsu - Sundanesesv - Swedishsw - Swahiliszl - Silesianszy - Sakizayata - Tamiltay - Tayaltcy - Tulute - Telugutet - Tetumtg - Tajiktg-cyrl - Tajik (Cyrillic script)tg-latn - Tajik (Latin script)th - Thaiti - Tigrinyatk - Turkmentl - Tagalogtly - Talyshtn - Tswanato - Tongantpi - Tok Pisintr - Turkishtru - Turoyotrv - Tarokots - Tsongatt - Tatartt-cyrl - Tatar (Cyrillic script)tt-latn - Tatar (Latin script)tum - Tumbukatw - Twity - Tahitiantyv - Tuviniantzm - Central Atlas Tamazightudm - Udmurtug - Uyghurug-arab - Uyghur (Arabic script)ug-latn - Uyghur (Latin script)uk - Ukrainianur - Urduuz - Uzbekuz-cyrl - Uzbek (Cyrillic script)uz-latn - Uzbek (Latin script)ve - Vendavec - Venetianvep - Vepsvi - Vietnamesevls - West Flemishvmf - Main-Franconianvo - Volapükvot - Voticvro - Võrowa - Walloonwar - Waraywo - Wolofwuu - Wu Chinesexal - Kalmykxh - Xhosaxmf - Mingrelianxsy - Saisiyatyi - Yiddishyo - Yorubayue - Cantoneseza - Zhuangzea - Zeelandiczgh - Standard Moroccan Tamazightzh - Chinesezh-cn - Chinese (China)zh-hans - Simplified Chinesezh-hant - Traditional Chinesezh-hk - Chinese (Hong Kong)zh-mo - Chinese (Macau)zh-my - Chinese (Malaysia)zh-sg - Chinese (Singapore)zh-tw - Chinese (Taiwan)zu - Zuluqqq - Message documentationFormatExport for off-line translationExport in native format Fetch <languages/> {{TutorialBrowser| series=Beginner Tutorial| name=How To Use KXmlGuiWindow| pre=[[Development/Tutorials/First_program|Tutorial 1 - Hello World]]| next=[[Development/Tutorials/Using_Actions|Tutorial 3 - QActions and XMLGUI]]| reading={{class|KXmlGuiWindow}} }} ==Abstract== This tutorial carries on from [[Development/Tutorials/First_program/KF5|First Program Tutorial]] and will introduce the {{class|KXmlGuiWindow}} class. In the previous tutorial, the program caused a dialog box to pop up but we're going to take steps towards a functioning application. [[image:tutorial2-kf5.png|frame|center]] ==KXmlGuiWindow== {{class|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 XMLGUI and is part of the KF5::XmlGui framework). While we will not be using XMLGUI 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, a <tt>mainwindow.cpp</tt> and a <tt>mainwindow.h</tt> which will contain our code. ===mainwindow.h=== <syntaxhighlight lang="cpp-qt"> #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <KXmlGuiWindow> class KTextEdit; class MainWindow : public KXmlGuiWindow { public: explicit MainWindow(QWidget *parent = nullptr); private: KTextEdit* textArea; }; #endif </syntaxhighlight> First we subclass KXmlGuiWindow with <tt>class MainWindow : public KXmlGuiWindow</tt> then we declare the constructor with <tt>MainWindow(QWidget *parent = nullptr);</tt>. And finally, we declare a pointer to the object that will make up the bulk of our program. {{class|KTextEdit}} is a generic rich text editing widget with some niceties like cursor auto-hiding. ===mainwindow.cpp=== <syntaxhighlight lang="cpp-qt"> #include "mainwindow.h" #include <KTextEdit> MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent) { textArea = new KTextEdit(); setCentralWidget(textArea); setupGUI(); } </syntaxhighlight> First, of course, we have to include the header file containing the class declaration. We initialise our text editor with an object and use KXmlGuiWindow's built-in setCentralWidget() function on it which tells the KXmlGuiWindow what should appear in the central section of the window. Finally, KXmlGuiWindow::setupGUI() is called which does a lot of behind-the-scenes stuff and creates the default menu bars (Settings, Help). ==Back to main.cpp== In order to actually run this window, we need to add a few lines in main.cpp: ===main.cpp=== <syntaxhighlight lang="cpp-qt"> #include <cstdlib> #include <QApplication> #include <QCommandLineParser> #include <KAboutData> #include <KLocalizedString> #include "mainwindow.h" int main (int argc, char *argv[]) { QApplication app(argc, argv); KLocalizedString::setApplicationDomain("tutorial2"); KAboutData aboutData( // The program name used internally. (componentName) QStringLiteral("tutorial2"), // A displayable program name string. (displayName) i18n("Tutorial 2"), // The program version string. (version) QStringLiteral("1.0"), // Short description of what the app does. (shortDescription) i18n("A simple text area"), // The license this code is released under KAboutLicense::GPL, // Copyright Statement (copyrightStatement = QString()) i18n("(c) 2015"), // Optional text shown in the About box. // Can contain any information desired. (otherText) i18n("Some text..."), // The program homepage string. (homePageAddress = QString()) QStringLiteral("http://example.com/"), // The bug report email address // (bugsEmailAddress = QLatin1String("submit@bugs.kde.org") QStringLiteral("submit@bugs.kde.org")); aboutData.addAuthor(i18n("Name"), i18n("Task"), QStringLiteral("your@email.com"), QStringLiteral("http://your.website.com"), QStringLiteral("OSC Username")); KAboutData::setApplicationData(aboutData); QCommandLineParser parser; aboutData.setupCommandLine(&parser); parser.process(app); aboutData.processCommandLine(&parser); MainWindow* window = new MainWindow(); window->show(); return app.exec(); } </syntaxhighlight> Again, we include our new header file in order to create our MainWindow object which we then display. ==CMake== The best way to build the program is to use CMake. We add <tt>mainwindow.cpp</tt> to the sources list, include the XmlGui and TextWidgets (for KTextEdit) frameworks, and replace all <tt>tutorial1</tt> text to <tt>tutorial2</tt>. ===CMakeLists.txt=== <syntaxhighlight lang="cmake"> cmake_minimum_required(VERSION 3.0) project (tutorial2) set(QT_MIN_VERSION "5.3.0") set(KF5_MIN_VERSION "5.2.0") find_package(ECM 1.0.0 REQUIRED NO_MODULE) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(KDEInstallDirs) include(KDECMakeSettings) include(KDECompilerSettings NO_POLICY_SCOPE) include(FeatureSummary) find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS Core # QCommandLineParser, QStringLiteral Widgets # QApplication ) find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS CoreAddons # KAboutData I18n # KLocalizedString XmlGui # KXmlGuiWindow TextWidgets # KTextEdit ) feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) set(tutorial2_SRCS main.cpp mainwindow.cpp) add_executable(tutorial2 ${tutorial2_SRCS}) target_link_libraries(tutorial2 Qt5::Widgets KF5::CoreAddons KF5::I18n KF5::XmlGui KF5::TextWidgets ) install(TARGETS tutorial2 ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) </syntaxhighlight> === Compile and run === The best way to compile, link and run it is to [[Getting_Started/Build|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. This command takes care of all of that in one line: <syntaxhighlight lang="bash"> mkdir build && cd build && cmake .. && make && ./tutorial2 </syntaxhighlight> ==Moving On== Now you can move on to [[Development/Tutorials/Using_Actions|Using Actions]]. [[Category:C++]]