Development/Tutorials/First program: Difference between revisions

From KDE TechBase
m (CMakeLists.txt)
m (Update Qt link)
(64 intermediate revisions by 24 users not shown)
Line 1: Line 1:
{{Template:I18n/Language Navigation Bar|Development/Tutorials/First_program}}
<languages />
 
{{TutorialBrowser|
{{TutorialBrowser|


<translate>
<!--T:35-->
series=Beginner Tutorial|
series=Beginner Tutorial|


<!--T:36-->
name=Hello World|
name=Hello World|


pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [http://www.trolltech.com/products/qt/ Qt], [[Getting_Started/Build/KDE4|KDE4 development environment]]|
<!--T:37-->
pre=[http://mindview.net/Books/TICPP/ThinkingInCPP2e.html C++], [https://www.qt.io/ Qt], [[Getting_Started/Build|Building KDE]]|


<!--T:38-->
next=[[Development/Tutorials/Using_KXmlGuiWindow|Tutorial 2 - KXmlGuiWindow]]|  
next=[[Development/Tutorials/Using_KXmlGuiWindow|Tutorial 2 - KXmlGuiWindow]]|  


<!--T:39-->
reading=[[Development/Tutorials/CMake|CMake]]
reading=[[Development/Tutorials/CMake|CMake]]
}}
}}


==Abstract==
==Abstract== <!--T:6-->
 
<!--T:7-->
Your first program shall greet the world with a friendly "Hello World", what else? For that, we will use a {{class|KMessageBox}} and customise one of the buttons.
Your first program shall greet the world with a friendly "Hello World", what else? For that, we will use a {{class|KMessageBox}} and customise one of the buttons.
[[image:introtokdetutorial1.png|frame|center]]


{{tip|To get more information about any class you come across, Konqueror offers a quick shortcut. So to look for information about KMessageBox, just type "kde:kmessagebox" into Konqueror and you'll be taken to the documentation.}}
<!--T:40-->
[[image:Introtokdetutorial1-kf5.png|frame|center]]


{{tip|
<!--T:8-->
You might want to use KDevelop for your projects, which does many nice things like code completion, easy access to API documentation or debugging support.
{{Tip|To get more information about any class you come across, you can use the ‘kde’ search engine. For example, to look for information about KMessageBox, just type "kde:kmessagebox" into Konqueror, Rekonq or KRunner, and you’ll be taken to the documentation.}}


Read [[Getting_Started/Set_up_KDE_4_for_development#KDevelop|this tutorial]] to set up KDevelop correctly for this task. You probably want to check if the setup is working by testing opening an existing KDE 4 application with KDevelop first.
<!--T:9-->
{{Tip|
You might want to use [[KDevelop|KDevelop]] or [[qtcreator|QtCreator]] as IDE for your projects.
}}


You still need to edit the CMake files by hand though.
==The Code== <!--T:10-->
}}


==The Code==
<!--T:11-->
All the code we need will be in one file, <tt>main.cpp</tt>. Create that file with the code below:
All the code we need will be in one file, <tt>main.cpp</tt>. Create that file with the code below:
<code cppqt>
</translate>
#include <QString>
 
#include <KApplication>
<syntaxhighlight lang="cpp-qt">
#include <cstdlib>
 
#include <QApplication>
#include <QCommandLineParser>
#include <KAboutData>
#include <KAboutData>
#include <KLocalizedString>
#include <KMessageBox>
#include <KMessageBox>
#include <KCmdLineArgs>
#include <KLocalizedString>


int main (int argc, char *argv[])
int main (int argc, char *argv[])
{
{
     KAboutData aboutData("tutorial1",                  // The program name used internally.
     QApplication app(argc, argv);
                         0,                           // The message catalog name, use program name if null.
    KLocalizedString::setApplicationDomain("tutorial1");
                         ki18n("Tutorial 1"),         // A displayable program name string.
 
                         "1.0",                       // The program version string.
<translate>   
                         ki18n("KMessageBox popup"),   // A short description of what the program does.
    <!--T:60-->
                         KAboutData::License_GPL,     // License identifier
KAboutData aboutData(
                         ki18n("(c) 2007"),           // Copyright Statement
                        // The program name used internally. (componentName)
                         ki18n("Some text..."),       // Some free form text, that can contain any kind of information.
                         QStringLiteral("tutorial1"),
                         "http://tutorial.com",       // The program homepage string.
                        // A displayable program name string. (displayName)
                         "[email protected]");       // The bug report email address string.
                         i18n("Tutorial 1"),
                        // The program version string. (version)
                         QStringLiteral("1.0"),
                        // Short description of what the app does. (shortDescription)
                         i18n("Displays a KMessageBox popup"),
                        // 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("[email protected].org")
                         QStringLiteral("[email protected]"));
    aboutData.addAuthor(i18n("Name"), i18n("Task"), QStringLiteral("[email protected]"),
                        QStringLiteral("http://your.website.com"), QStringLiteral("OSC Username"));
    KAboutData::setApplicationData(aboutData);
</translate>


     KCmdLineArgs::init( argc, argv, &aboutData );
     QCommandLineParser parser;
     KApplication app;
    aboutData.setupCommandLine(&parser);
     KGuiItem guiItem( QString( "Hello" ), QString(),
     parser.process(app);
                      QString( "this is a tooltip" ),
    aboutData.processCommandLine(&parser);
                      QString( "this is a whatsthis" ) );
   
    KMessageBox::questionYesNo( 0, "Hello World", "Hello", guiItem );
     KGuiItem yesButton( i18n( "Hello" ), QString(),
                        i18n( "This is a tooltip" ),
                        i18n( "This is a WhatsThis help text." ) );
 
return
        KMessageBox::questionYesNo  
        (0, i18n( "Hello World" ), i18n( "Hello" ), yesButton )  
        == KMessageBox::Yes? EXIT_SUCCESS: EXIT_FAILURE;
}
}
</code>
</syntaxhighlight>
The first KDE specific code we come across in this program is {{class|KAboutData}}. This is the class used to store information about the program such as a short description, authors or license information. Pretty much every KDE application should use this class.


Then we come to {{class|KCmdLineArgs}}. This is the class one would use to specify command line switches to, for example, open the program with a specific file. However, in this tutorial, we simply initialise it with the {{class|KAboutData}} object we created so we can use the <tt>--version</tt> or <tt>--author</tt> switches.
<translate>
<!--T:45-->
First we need to create a [http://doc.qt.io/qt-5/qapplication.html QApplication] object. This needs to be done exactly once in each program since it is needed for things such as [[Development/Tutorials/Localization/i18n|i18n]]. It also should be created before any other KDE or Qt object. A call to {{class|KLocalizedString}}::setApplicationDomain() is required to properly set the translation catalog and must be done before the next step happens.


Then we create a {{class|KApplication}} object. This needs to be done exactly once in each program since it is needed for things such as [[Development/Tutorials/Localization/i18n|i18n]].
<!--T:15-->
The first KDE specific object we create in this program is {{class|KAboutData}}. This is the class used to store information about the program such as a short description, authors or license information. Pretty much every KDE application should use this class. We then call {{class|KAboutData}}::setApplicationData() to initialize the properties of the [http://doc.qt.io/qt-5/qapplication.html QApplication] object.


Now we've done all the necessary KDE setup, we can move on to doing interesting things with our application. We're going to create a popup box but we're going to customise one of the buttons. To do this customisation, we need to use a {{class|KGuiItem}} object. The first argument in the {{class|KGuiItem}} constructor is the text that will appear on the item (in our case, a button). Then we have an option of setting an icon for the button but we don't want one so we just give it <tt>QString()</tt>. Finally we set the tooltip (what appears when you hover over an item) and finally the "What's This?" (accessed through right-clicking or Shift-F1) text.
<!--T:16-->
Then we come to [http://doc.qt.io/qt-5/qcommandlineparser.html QCommandLineParser]. This is the class one would use to specify command line switches to, for example, open the program with a specific file. However, in this tutorial, we simply initialise it with the {{class|KAboutData}} object we created so we can use the <tt>--version</tt> or <tt>--author</tt> switches.


Now we have our item, we can create our popup. We call the <tt>{{class|KMessageBox}}::questionYesNo()</tt> function which, by default, creates a message box with a "Yes" and a "No" button. The second argument is the text that will appear in the middle of the popup box. The third is the caption the window will have and finally we set the KGuiItem for (what would normally be) the "Yes" button to the <tt>KGuiItem guiItem</tt> we created.
<!--T:17-->
Now we've done all the necessary KDE setup, we can move on to doing interesting things with our application. We're going to create a popup box but we're going to customise one of the buttons. To do this customisation, we need to use a {{class|KGuiItem}} object. The first argument in the {{class|KGuiItem}} constructor is the text that will appear on the item (in our case, a button). Then we have an option of setting an icon for the button but we don't want one so we just give it <tt>QString()</tt>. We then set the tooltip (what appears when you hover over an item) and finally the "What's This?" (accessed through right-clicking or Shift-F1) text.


<!--T:18-->
Now we have our item, we can create our popup. We call the <tt>{{class|KMessageBox}}::questionYesNo()</tt> function which, by default, creates a message box with a "Yes" and a "No" button. The second argument is the text that will appear in the message box above the buttons. The third is the caption the window will have and finally, we set the KGuiItem for (what would normally be) the "Yes" button to the <tt>KGuiItem yesButton</tt> we created.
<!--T:19-->
Note that all user-visible text is passed through the i18n() function; this is necessary for the UI to be translatable. More information on localization can be found in the [[Development/Tutorials/Localization/i18n|localization tutorial]].
<!--T:20-->
We're all done as far as the code is concerned. Now to build it and try it out.
We're all done as far as the code is concerned. Now to build it and try it out.


==Build==
== Build == <!--T:21-->
If you set up your environment as described in [[Getting Started/Build/KDE4]], you can compile this code with
 
<!--T:22-->
g++ main.cpp -o tutorial1 \
You want to [[Development/Tutorials/CMake|use CMake]] for your build environment. You provide a file CMakeLists.txt, cmake uses this file to generate all Makefiles out of it.
-I$QTDIR/include/Qt \
 
-I$QTDIR/include/QtCore \
=== CMakeLists.txt === <!--T:23-->
-I$QTDIR/include \
-I$KDEDIR/include/KDE \
-I$KDEDIR/include \
-L$KDEDIR/lib \
-L$QTDIR/lib -lQtCore -lQtGui -lkdeui -lkdecore
and then run it with
dbus-launch ./tutorial1


===Using CMake===
<!--T:24-->
If that worked, you may want to use [[Development/Tutorials/CMake|CMake]], just like the rest of KDE. This will automatically locate the libraries and headers for KDE, Qt etc. and will allow you to easily build your applications on other computers.
====CMakeLists.txt====
Create a file named CMakeLists.txt in the same directory as main.cpp with this content:
Create a file named CMakeLists.txt in the same directory as main.cpp with this content:
<code ini n>
</translate>
 
<syntaxhighlight lang="cmake">
cmake_minimum_required(VERSION 3.0)
 
project (tutorial1)
project (tutorial1)


find_package(KDE4 REQUIRED)
set(QT_MIN_VERSION "5.3.0")
include_directories(${KDE4_INCLUDES})
set(KF5_MIN_VERSION "5.2.0")
 
find_package(ECM 1.0.0 REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
 
include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings NO_POLICY_SCOPE)
include(FeatureSummary)
 
# Find Qt modules
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
    Core    # QCommandLineParser, QStringLiteral
    Widgets # QApplication
)
 
# Find KDE modules
find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS
    CoreAddons      # KAboutData
    I18n            # KLocalizedString
    WidgetsAddons  # KMessageBox
)


feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
   
set(tutorial1_SRCS main.cpp)
set(tutorial1_SRCS main.cpp)


kde4_add_executable(tutorial1 ${tutorial1_SRCS})
add_executable(tutorial1 ${tutorial1_SRCS})
target_link_libraries(tutorial1 ${KDE4_KDEUI_LIBS})
 
</code>
<!--T:54-->
The <tt>find_package()</tt> function locates the package that you ask it for (in this case KDE4) and sets some variables describing the location of the package's headers and libraries. In this case we will use the <tt>KDE4_INCLUDES</tt> variable which contains the path to the KDE4 header files.
target_link_libraries(tutorial1
    Qt5::Widgets
    KF5::CoreAddons
    KF5::I18n
    KF5::WidgetsAddons
)
 
install(TARGETS tutorial1  ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})
</syntaxhighlight>
 
<translate>
<!--T:61-->
The <tt>find_package()</tt> function locates the package that you ask it for (in this case ECM, Qt5, or KF5) and sets some variables describing the location of the package's headers and libraries. ECM, or Extra CMake Modules, is required to import special CMake files and functions for building KDE applications.


In order to allow the compiler to find these files, we pass that variable to the <tt>include_directories()</tt> function which adds the KDE4 headers to the header search path.
<!--T:25-->
Here we try to find the modules for Qt 5 and KDE Frameworks 5 required to build our tutorial. The necessary files are included by CMake so that the compiler can see them at build time. Minimum version numbers are set at the very top of CMakeLists.txt file for easier reference.


<!--T:26-->
Next we create a variable called <tt>tutorial1_SRCS</tt> using the <tt>set()</tt> function. In this case we simply set it to the name of our only source file.
Next we create a variable called <tt>tutorial1_SRCS</tt> using the <tt>set()</tt> function. In this case we simply set it to the name of our only source file.


Then we use <tt>kde4_add_executable()</tt> to create an executable called <tt>tutorial1</tt> from the source files listed in our <tt>tutorial1_SRCS</tt> variable. Finally we link our executable to the KDE4 kdeui library using <tt>target_link_libraries()</tt> and the <tt>KDE4_KDEUI_LIBS</tt> variable which was set by the <tt>find_package()</tt> function.
<!--T:27-->
Then we use <tt>add_executable()</tt> to create an executable called <tt>tutorial1</tt> from the source files listed in our <tt>tutorial1_SRCS</tt> variable. Afterwards, we link our executable to the necessary libraries using <tt>target_link_libraries()</tt> function. The line starting with <tt>install</tt> writes a default "install" target into the Makefile.


====Make And Run====
=== Make And Run === <!--T:28-->
Again, if you set up your environment as described in [[Getting_Started/Build/KDE4|Getting Started/Build/KDE4]], you can compile this code with:
cmakekde


Or if you did not:
<!--T:29-->
To compile, link and install your program, you must have several software installed, e.g. cmake, make and gcc-c++, and the Qt 5 and KDE Frameworks development files. To be sure you have everything, best follow [[Getting_Started/Build/Environment|this install guide]].


mkdir build
<!--T:30-->
cd build
While you can run cmake directly inside the source code directory itself, it is a best practice, and actually enforced in some KDE software, to use a separate build directory and run cmake from there:
cmake .. && make
</translate>


And launch it as:
<syntaxhighlight lang="bash">
./tutorial1.shell
mkdir build && cd build
</syntaxhighlight>
You can invoke CMake and make manually:
<syntaxhighlight lang="bash">
cmake .. && make
</syntaxhighlight>


==Moving On==
<translate>
<!--T:62-->
And launch it with:
</translate>
 
<syntaxhighlight lang="bash">
./tutorial1
</syntaxhighlight>
 
<translate>
==Moving On== <!--T:32-->
 
<!--T:33-->
Now you can move on to [[Development/Tutorials/Using_KXmlGuiWindow|using KXmlGuiWindow]].
Now you can move on to [[Development/Tutorials/Using_KXmlGuiWindow|using KXmlGuiWindow]].


<!--T:59-->
{{Tip||The source code on this page applies only the current KDE Frameworks 5 ("KF5") version. For the older KDE Development Platform ("KDE4"), See [[Development/Tutorials/First_program/KDE4]]}}
<!--T:34-->
[[Category:C++]]
[[Category:C++]]
</translate>

Revision as of 06:01, 16 March 2018

Other languages:
Hello World
Tutorial Series   Beginner Tutorial
Previous   C++, Qt, Building KDE
What's Next   Tutorial 2 - KXmlGuiWindow
Further Reading   CMake

Abstract

Your first program shall greet the world with a friendly "Hello World", what else? For that, we will use a KMessageBox and customise one of the buttons.

Tip
To get more information about any class you come across, you can use the ‘kde’ search engine. For example, to look for information about KMessageBox, just type "kde:kmessagebox" into Konqueror, Rekonq or KRunner, and you’ll be taken to the documentation.


Tip
You might want to use KDevelop or QtCreator as IDE for your projects.


The Code

All the code we need will be in one file, main.cpp. Create that file with the code below:

#include <cstdlib>

#include <QApplication>
#include <QCommandLineParser>
#include <KAboutData>
#include <KLocalizedString>
#include <KMessageBox>

int main (int argc, char *argv[])
{
    QApplication app(argc, argv);
    KLocalizedString::setApplicationDomain("tutorial1");

    
    KAboutData aboutData(
                         // The program name used internally. (componentName)
                         QStringLiteral("tutorial1"),
                         // A displayable program name string. (displayName)
                         i18n("Tutorial 1"),
                         // The program version string. (version)
                         QStringLiteral("1.0"),
                         // Short description of what the app does. (shortDescription)
                         i18n("Displays a KMessageBox popup"),
                         // 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("[email protected]")
                         QStringLiteral("[email protected]"));
    aboutData.addAuthor(i18n("Name"), i18n("Task"), QStringLiteral("[email protected]"),
                         QStringLiteral("http://your.website.com"), QStringLiteral("OSC Username"));
    KAboutData::setApplicationData(aboutData);

    QCommandLineParser parser;
    aboutData.setupCommandLine(&parser);
    parser.process(app);
    aboutData.processCommandLine(&parser);
    
    KGuiItem yesButton( i18n( "Hello" ), QString(),
                        i18n( "This is a tooltip" ),
                        i18n( "This is a WhatsThis help text." ) );

return 
        KMessageBox::questionYesNo 
        (0, i18n( "Hello World" ), i18n( "Hello" ), yesButton ) 
        == KMessageBox::Yes? EXIT_SUCCESS: EXIT_FAILURE;
}

First we need to create a QApplication object. This needs to be done exactly once in each program since it is needed for things such as i18n. It also should be created before any other KDE or Qt object. A call to KLocalizedString::setApplicationDomain() is required to properly set the translation catalog and must be done before the next step happens.

The first KDE specific object we create in this program is KAboutData. This is the class used to store information about the program such as a short description, authors or license information. Pretty much every KDE application should use this class. We then call KAboutData::setApplicationData() to initialize the properties of the QApplication object.

Then we come to QCommandLineParser. This is the class one would use to specify command line switches to, for example, open the program with a specific file. However, in this tutorial, we simply initialise it with the KAboutData object we created so we can use the --version or --author switches.

Now we've done all the necessary KDE setup, we can move on to doing interesting things with our application. We're going to create a popup box but we're going to customise one of the buttons. To do this customisation, we need to use a KGuiItem object. The first argument in the KGuiItem constructor is the text that will appear on the item (in our case, a button). Then we have an option of setting an icon for the button but we don't want one so we just give it QString(). We then set the tooltip (what appears when you hover over an item) and finally the "What's This?" (accessed through right-clicking or Shift-F1) text.

Now we have our item, we can create our popup. We call the KMessageBox::questionYesNo() function which, by default, creates a message box with a "Yes" and a "No" button. The second argument is the text that will appear in the message box above the buttons. The third is the caption the window will have and finally, we set the KGuiItem for (what would normally be) the "Yes" button to the KGuiItem yesButton we created.

Note that all user-visible text is passed through the i18n() function; this is necessary for the UI to be translatable. More information on localization can be found in the localization tutorial.

We're all done as far as the code is concerned. Now to build it and try it out.

Build

You want to use CMake for your build environment. You provide a file CMakeLists.txt, cmake uses this file to generate all Makefiles out of it.

CMakeLists.txt

Create a file named CMakeLists.txt in the same directory as main.cpp with this content:

cmake_minimum_required(VERSION 3.0)

project (tutorial1)

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} ${ECM_KDE_MODULE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake)

include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings NO_POLICY_SCOPE)
include(FeatureSummary)

# Find Qt modules
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS 
    Core    # QCommandLineParser, QStringLiteral
    Widgets # QApplication 
)

# Find KDE modules
find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS
    CoreAddons      # KAboutData
    I18n            # KLocalizedString
    WidgetsAddons   # KMessageBox
)

feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
    
set(tutorial1_SRCS main.cpp)

add_executable(tutorial1 ${tutorial1_SRCS})

<!--T:54-->
target_link_libraries(tutorial1
    Qt5::Widgets
    KF5::CoreAddons
    KF5::I18n
    KF5::WidgetsAddons
)

install(TARGETS tutorial1  ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})

The find_package() function locates the package that you ask it for (in this case ECM, Qt5, or KF5) and sets some variables describing the location of the package's headers and libraries. ECM, or Extra CMake Modules, is required to import special CMake files and functions for building KDE applications.

Here we try to find the modules for Qt 5 and KDE Frameworks 5 required to build our tutorial. The necessary files are included by CMake so that the compiler can see them at build time. Minimum version numbers are set at the very top of CMakeLists.txt file for easier reference.

Next we create a variable called tutorial1_SRCS using the set() function. In this case we simply set it to the name of our only source file.

Then we use add_executable() to create an executable called tutorial1 from the source files listed in our tutorial1_SRCS variable. Afterwards, we link our executable to the necessary libraries using target_link_libraries() function. The line starting with install writes a default "install" target into the Makefile.

Make And Run

To compile, link and install your program, you must have several software installed, e.g. cmake, make and gcc-c++, and the Qt 5 and KDE Frameworks development files. To be sure you have everything, best follow this install guide.

While you can run cmake directly inside the source code directory itself, it is a best practice, and actually enforced in some KDE software, to use a separate build directory and run cmake from there:

mkdir build && cd build

You can invoke CMake and make manually:

cmake .. && make

And launch it with:

./tutorial1

Moving On

Now you can move on to using KXmlGuiWindow.

The source code on this page applies only the current KDE Frameworks 5 ("KF5") version. For the older KDE Development Platform ("KDE4"), See Development/Tutorials/First_program/KDE4