Introduction to KDE/QT programming
| Written by: | dimport | | Published by: | thinkt4nk | | Published on: | 2003-06-21 07:19:46 | | Topic: | linux |
|
| |
| This is a paper i wrote which is an introduction for creating a basic gui app with kdevelop. The output of the skeleton program kdevelop creates for you is discussed among other things. |
Introduction to QT/KDE programming and
A Comparison of KDE and MFC Application Development Environments
1.0 Introduction
KDE is a free, open-source desktop environment that traditionally stands for Kool Desktop Environment. The purpose of creating KDE was to provide a complete GUI environment using Qt, which could be used on a Linux platform (and Unix variants) by end users. On October 15 1996, Matthias Ettrich posted his humble idea of a new GUI to sit on top of X11 (http://www.X.org) to a Qt-Interest Forum, little did he know that only a few years later it would be used by 70% of Unix users on a number of different Unix variants.
Qt, developed by Trolltech (http://www.trolltech.com), is a cross platform GUI toolkit written in C++ and is totally component based. Qt is also open-source and is basically free to use for non-profit development on the *nix platform (the term *nix will be used throughout this paper to describe Unix, Linux and both of their variants and distributions). KDE libs extend the functionality of the Qt libs specific to a *nix desktop and in doing so provides a unique, but at the same time uniform, development environment for application programmers. The KDE libs are not cross platform due to underlying dependencies on the Xwindows system. However, due to the nature of linux developers, a port has been done whereby KDE runs on CygWin a posix emulation layer and CyWin XFree86 server for windows (http://kde-cygwin.sourceforge.net/).
KDE itself consists of many components, the main package being KDE-Base, which consists of:
KWin - the window manager
KDesktop - the desktop manager
Kicker - the panel (similar to Start Menu)
KControl - the control center (similar to control panel)
KHelpcenter and
Konqueror - file/internet browser/viewer (similar to IE)
As well as KDE-libs, KDevelop is another important package shipped with KDE. KDevelop provides an IDE not just for KDE Application Programming but also for other environments (see Appendix A). KDevelop can also be used in much the same way as Visual C++ with MFC, by using an application wizard to create a simple framework you can build more complex applications.
2.0 User Guide
2.1 Qt, KDE and the KDevelop 2.0 Application Wizard
Since the majority of KDE''s libraries are derived from Qtmany classes are similar if not the same. Appendix 6.4 shows the source for a very simple application that displays a button widget created for Qt and then KDE. As can be seen in the code the only differences are the names of a class Qapplication and Kapplication, and the method used to set the main widget setMainWidget and setTopWidget. To create a KDE application all that is required is a few simple steps:
1. create an instance of Kapplication
2. create a button widget and pass it a value to be displayed
3. make the button the main widget
4. display it to the screen
5. and finally enter the main event loop so user input can occur.
User input->window system->KApplication->active window->widget decides what to do. Qwidget::event(QEvent*) is the main event handler. The event handler then passes the event to event filters, if none of these take responsibility then specialized event handlers are called. All of these event handlers are virtual so they can be reimplemented with ease
in a new application.
There is also an additional step in the program that can be left out, it basically connects the inherited clicked signal of the button widget with the quit slot inherited from KApplication. Signals and slots will be covered in more depth in the next section.
Both Qt and KDE come with their own IDE Qt Designer and KDevelop respectively. Many *nix programmers still choose to write and build their applications from the Command Line Interface (CLI) simply, because they can. The tools that the IDE''s use to automate the necessary tasks are, themselves, available from the CLI. Using these however is no trivial matter. KDevelop was originally created so application developers in a *nix environment did not have to worry about the processes involved in writing code which would compile and run optimally on the different *nix platforms. Some of these ''processes'' will be mentioned in relation to their handling by the KDevelop Application Wizard.
For the purposes of this paper the main focus will lie on creating a KDE 2 MDI application with the KDevelop IDE and its Application Wizard. After opening KDevelop, the Application Wizard can be accessed by choosing Project->New from the menubar. Appendix 6.1 shows screenshots of the Application Wizard, the frameworks that are available for use with the IDE and other options.
Continuing on to the next screen after selecting a KDE 2 MDI application the developer is presented with a list of options that can be added to the project by the IDE. Part of building a successful application in *nix is being able to contact the author easily to let them know about any bugs encountered or ideas for extra functionality which could be added. In the main function created the author and email fields are also used to create the about dialog in the help menu of the application.
KDevelop will create all of the source and header files needed for a fully functional basic application, it will also create gnu standard files used to build the application on different platforms. User and API documentation can also be created at this point in sgml and an initial html documentation set respectively. Purpose and requirements of the program are generally stored in a .lsm file (linux software map) and can be created also. The .kdelnk-File can be used, so when installed, your application is added to the Application tree of the KPanel, similar to Start->Programs in Windows. Generating a .desktop file will place a shortcut on the desktop to your application using the standard program-icon.
Version Control System support is recommended for any project being developed by more than one developer in a different location or if you want the latest builds and source to be available in a central repository. Concurrent Version System (CVS) is a mechanism used to implement this.
Moving on to the next two screens the developer is presented with a header and source template. This is an opportunity to have a description of your project commented at the start of all the source and header files. Standard information included is the file and its description, date generated, copyright information, contact details and the default GNU General Public License (GPL).
Finally the point of creation is reached, now is the time that the IDE does all of its voodoo with making directories, generating makefiles and configure scripts, setting flags for compilation, checking for need programs, system independent verifications, checking for libraries, linking characteristics, operating systems variables length and checking for required Qt/KDE/X includes.
Now that a simple framework has been created the application can be built and run to see what it has achieved. By default the logical file viewer is displayed as the left panel of the IDE window and this can be browsed to see what has
been created.
Invoking make from the build menu will build the application and display what it is doing. Make works recursively through the directories of your project and the first step is to invoke g++ the gnu c++ compiler. DHAVE_CONFIG_H is a macro used to tell make about the config.h file in the main project directory which will be used to access platform and application dependent macros. O0 sets the optimization to 0, -g enables debugging (using gdb - gnu debugger), -Wall tells make to display all warnings and -c to only compile the source - create only object files. The meta object compiler (moc) is then called to process the header files and expand macros such as QOBJECT (discussed later). These files are then also compiled to create a binary which includes paths to the libraries for X11,Qt and KDE.
Success!! A KDE 2 MDI application with session-management, menubar, toolbar, statusbar and support for a document-view codeframe model has been created. On executing the application it will provide several different default menu options.
File: New, Open, Open Recent, Save, Save As, Close, Print, New Window and Quit
Edit: Cut, Copy and Paste
Settings: Show Toolbar and Show Statusbar
Help: Contents->KHelpCenter, What''s This, Report Bugs->generates a bug report email form to the author''s email address, About-> about the program, author and standard gnu gpl.
2.2 The application wizard?s output
In Appendix 6.3 the following files generated by KDevelop''s Application Wizard can be found.
First of all is the .cpp file header generated by the app wizard, secondly is a list of includes for the newly created application. kcmdlineargs.h, as its name suggests, provides access to command line arguments which may be supplied to an application. These may be specific to Qt, KDE or the application itself. kaboutdata.h stores the information which can be accessed by choosing Help -> About from a KDE application. klocale.h provides internationalisation support to a KDE application. Finally the application base classes header file, ExampleMDI.h, is included.
static const char *description = I18N_NOOP("Test1");
I18N_NOOP(const char* text) is a function which will translate a string provided to the native language of the person using the application (provided they are using an international version and a language different to yours?).
static KCmdLineOptions options[] =
{
{ "+[File]", I18N_NOOP("file to open"), 0 }, { 0, 0, 0 }
};
The next function call in the main function specifies a default file open method and also allows you to implement other methods relative to the application.
Generally when writing a C++ program on a *nix platform it is desirable to both return an integer value (to comply with ISO standards, and also for a clean exit) and allow the program to be passed arguments or parameters at run-time. Therefore the main function''s declaration will take on the form int main( int argc, char* argv[] ), argc is an integer value of the number of arguments and argv contains the text of the actual arguments.
After entering the main function, an instance of KaboutData is created and defined with the information which will be displayed with the About option of the Help menu. This will contain the name of the program, a translation, if required, of the purpose of the program, the version, licensing and copyright details, the author and their email address. The addAuthor method is then set to contain the name of the author and email address. Command line arguments are then initiated and accommodation is provided for your own.
Every KDE application contains exactly one instance of KApplication. bool isRestored() is then called to find out whether the application was started by the KDE window manager or by the user. If it was restored by the session manager, there may be some instance specific data to reload. Otherwise an instance of the application is created and set to show.
The next few lines determine whether there were any command line arguments passed to the application, by default the open file method from the base class is called.
Finally the application''s exec() method is called to enter the main event loop, so user input can occur, and waits for either exit() to be called or the main window to die somehow.
ExampleMDI.cpp is the implementation file for the base class and is therefore where the menubar, statusbar and toolbar are implemented. It also provides a forward declaration of the other two classes ExampleMDIdoc and ExampleMDIview. All three of the default class implementation files contain three different sections of includes which are specific to Qt, KDE and the application itself. Class indexes can be found for Qt and KDE at http://doc.trolltech.com/2.3/classes.html and http://developer.kde.org/documentation/library/2.0-api/classref/index.html respectively.
Following the includes is the constructor for ExampleMDIApp. The application will inherit KmainWindow(Qwidget* parent=0, const char* name=0, flags?), being a top level widget, and passes 0 (there is usually no parent for top level widgets) and its name. The config instance is of type KConfig* and is now set to the application which is used to save or read a previous state the application was in. untitledCount is an integer value which is incremented each time the user of the application creates a new document. A doubly linked list is then created to implement the recent files list in the File menu. initStatusBar() is called to create a status bar.
initView() is called to create the main view for the MDI. An instance of QVBox, view_back is then created insidei nitView() to manage the vertical position of it''s windows and view_back is passed to create a new workspace and to set the central widget for the window.
Qt provides an effective mechanism for interaction between objects known as Signals and Slots. Header files of classes wishing to use signals and slots must: contain the QOBJECT macro, be derived from the QObject class or one of its subclasses and must also be compiled using the Meta Object Compiler (MOC) to expand the macro. Signals are emitted from within any legal class member function and the object itself is then unaware of what happens. Signals that are not inherited are defined in a special section of the class declaration (signals:). Slots are normal member functions (public, private or protected), which can be used for receiving signals; they are also defined in there own section of a class declaration (slots:). When an objects state has changed it uses the emit keyword. All that is needed now is a communication channel between the emit signal and slot, this is initiated by a function calling the connect() method.
Now, returning to the constructor initActions() is called. The purpose of this function is to connect all of the signals and slots used to decide what to do when the user makes a selection from the menu. Status texts will then be created to display when the user hovers over a menu option.
Before the start of the slot implementations in ExampleMDI.cpp an event filter is implemented. The event filter waits for a user to close a view and providing it''s not the last one, removes the view from the main window. Now that the base class has been covered it is time to move on to the Document/View implementation.
Firstly, the implementation of the Document. ExampleMDIDoc.cpp, a linked list is created to contain a list of the views created by the application or user. The addView function adds a new view to the list, or the document, and the changedViewList method is called to write the filename as the title of the window. There is a method for deleting a view from the list, document, updating all of the views, closing, creating, opening and saving a document. Finally the canCloseFrame method is used to find out whether a view has been modified before it is closed, if it has it interacts with the user until the file is saved or cancelled.
Secondly is the implementation of the View. Since there can''t be a view without a document, the constructor makes sure one exists. Most of the setup, configuration and intialisations have already been completed by the base and document classes so there is not much left for the view to do, at this stage. A method is provided to access the document, repaint the view and print the view.
2.3 Extending the application
KDevelop provides a dialog editor as part of the IDE. This means the developer can design dialogs in a wysiwyg fashion. Once the design has been created KDevelop can take charge and create the background source needed to add the dialog to the application.
There is a multitude of widgets that can be added to an application. Pictures of most of these widgets can be found at http://doc.trolltech.com/2.3/pictures.html and also provide links to the class reference of the widgets being used.
The bibliography contains links to a few Qt and KDE sites that may be useful in gaining a more in depth understanding of the methods discussed here.
3.0 Critical Analysis
Through the use of KDevelop; KDE is an easy to learn, high productivity development environment that respects industry standards. Although high productivity may be debatable when compared to an environment on Windows it is certainly true for a *nix desktop. An important note on the comparison between KDE and an environment such as MFC is that Windows only runs on x86 architecture. As KDE runs on many different *nix platforms it also runs on different hardware architectures. KDE''s productivity gain pertains mainly to situations where an application is written on a different hardware platform. Through the use of such utilities as KDevelop and/or automake, productivity is substantially increased, as the developer does not have to worry about this factor.
Perhaps KDE''s biggest strength however is that it uses Qt as its underlying framework. Qt uses an enticing method for object-to-object communication. Slots and Signals can be emitted/received by objects without knowing where they are sent/originate, which allows for a high level of code reuse providing a totally component based approach to application development. Slots and Signals are also completely type safe as opposed to message maps in MFC, although substantial improvements have been made in MFC 7. GTK, the framework that the GNOME desktop environment is built on uses a similar mechanism to signals however it is not implemented as well, or as easy to use for the developer. GNOME is probably KDE''s biggest competitor in the Linux desktop arena but seems to be geared more toward aesthetic appeal to the user rather than being a development environment that provides libraries to allow application to have a similar or consistent look.
Qt is written from the ground up in C++, which gives it an advantage over MFC being only a thin layer on top of the Win32 API. It also means it doesn''t inherit the nuances of the C programming language and the complexity of the Win32 API. Another advantage of Qt is that it sits directly on top of X11 so performance issues like that of java virtual machine''s environment are avoided. As an example of how well designed and powerful the Qt toolkit is a team of seven (albeit very talented) programmers
were able to port the front end of Netscape to Qt in five days as a challenge. The front end of Netscape at that time consisted of several hundred lines of Motif (C) and MFC based code and was replaced with only 20 000 lines of Qt code. The result of this performance is a gimmicky browser called qtmozilla and can be found at their website where the source can be downloaded freely.
Both Qt and KDE provide a high quality level of internationalisation support. Since KDE developers themselves are from all corners of the globe this feature helps both the core development of KDE itself and also benefits users who wish to take advantage of this capability. Currently KDE supports a base of over fifty languages.
One of the quasi-disadvantages of KDE is portability. KDE depends on X for mostly low-level functions like inter-process communication. Handling of dynamic libraries is also an issue preventing portability to other platforms like Windows. However, KDE was not designed with this purpose, it was designed in one sense as a way of bringing Linux to the desktop.
KDE libraries are released to the public under the GNU LGPL. The lesser GPL allows the libraries to be used in propriety programs. Most of the other restrictions still apply as usual with the GPL a link to which can be found in the appendix. When deciding to use an application development environment in a commercial sense saving money anywhere possible is generally a major concern. MFC has various issues relating to its redistribution. For starters, if you plan to redistribute an application using MFC 6 you need to include mfc42.dll and msvcrt.dll unless it is statically linked. Next, you must make sure that it is the retail and not the debug version as they are not re-distributable. Obviously the same steps will need to be both discovered and applied for any additional libraries you wish to add and re-distribute with your application. Whilst KDE already has its libraries installed, as KDE applications run on KDE, this is still an extra step slowing productivity and also adding to the size of your distribution.
With KDE''s diverse range of developers from all around the world some programming ''guidelines'' were introduced. These guidelines are fairly standard C++ related but by implementing them, program consistency and efficiency are held at a high standard. As can be seen in the source examples in the appendices, class names are generally a lot more intuitive then that of MFC and other object oriented programming languages.
MFC of course has its own advantages over other frameworks. One of these advantages is that the framework itself controls the main execution of the application. Both Qt and KDE use a more traditional C++ approach in this respect requiring the developer to provide a main function. Recently C++ programmers on thewindows platform have been a bit concerned with all the new .NET hype. Microsoft however claims that in no way is being phased out. They have implemented two different schemes known as managed and unmanaged C++. Basically, unmanaged stays in line with ISO standards and issues, and managed provides a mechanism of interacting with the .NET architecture. MFC has alsoreceived new features as well as the VC++ IDE.
Another option available for creating applications similar to MDI''s on the windows platform is Windows Forms. This method utilizing VB and C# seems to be more the future focus of Microsoft. While it''s main design goal is to create enhanced multi-tier applications it can be used as a similar and possibly ''simpler'' method of creating MDI like applications.
4.0 Usage/Popularity
KDE''s user base is currently estimated to be in the millions. Mentioned earlier was also the statistic that 70% of *nix users run KDE as their desktop environment. As more and more people migrate their systems to linux as a
free platform for servers, development, desktops, stability and even ideology this continues to grow almost exponentially. As this number continues to grow, so do the flavours or distributions of Linux. Most of the major distributions such as Redhat, SuSE, Mandrake, Caldera etc ship KDE as part of their distribution. Qt is also quickly gaining momentum not only on the Linux platform but also Windows, Mac and various embedded platforms.
There are now thousands of developers around the world enhancing, fixing bugs, and writing new useful applications for KDE itself. Perhaps KDE''s success is due somewhat to its development model. Since developers (usually) don''t get paid for developing KDE it must be fun and there must also be something to play or experiment with at all times. Developers have the choice of starting their own project with an idea of their own or joining in one of the multitude of projects currently in development, which is usually everything. KDE also has no steadfast blueprint as to how the various parts should be coded but relies on developers intuition and insight. Since KDE also treats all developers on a peer basis (there is no formal hierarchy), developer''s prestige comes from their proven effort that a lot of the time is different to industry situations.
5.0 Bibliography
KDE 2.0 architecture [http://developer.kde.org/documentation/library/kdeqt/kde2arch/index.html]
Sweet, David. et al KDE 2.0 Development, Sams Publishing, 2001 [http://developer.kde.org/documentation/books/kde-2.0-development/index.html]
KDE e.V. What is KDE? [http://www.kde.org/whatiskde/index.html]
KDE Developer Faq [http://developer.kde.org/documentation/other/developer-faq.html]
Jimenez, Antonio Larrosa. KDE Tutorial v1.2, 2002 [http://devel-home.kde.org/~larrosa/tutorial/index.html]
Faure, David. KDE, OpenSource Desktop and Development Platform, 2001
Granroth, Kurt. KDE 2.0 Features ? LinuxWorld Expo 2000, 2000 [http://devel-home.kde.org/~granroth/LWE2000/index.html]
Ettrich, Matthias. Qt-interest Archive: New Project:KDE(based on Qt), 1996
The KDE on Cygwin Project [http://sourceforge.net/projects/kde-cygwin/]
Pictures of Most Qt Widgets [http://doc.trolltech.com/2.3/pictures.html]
K Desktop Environment [http://www.kde.org]
Trolltech - Creators of Qt [http://www.trolltech.com]
http://www.X.org
Qt - Class Index [http://doc.trolltech.com/2.3/classes.html]
KDE 2.0 API Reference , Class Index [http://developer.kde.org/documentation/library/2.0-api/classref/index.html]
Schwartz, David. Redistributing Microsoft Visual C++ 6.0 Applications, Microsoft Corporation 1999 [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvc60/html/redistribvc6.asp]
Tsao, Anson. Sullivan, Walter. What?s New for MFC Developers? Msdn news 2001 [http://msdn.microsoft.com/msdnnews/2001/Sept/VCNet/VCNet.asp]
GTK+ Reference Manual: Signals [http://developer.gnome.org/doc/API/gtk/gtk-signals.html]
QtMozilla, the Qt based port of Netscape Navigator 5.0 beta [http://www.trolltech.com/qtmozilla/]
Stallman, Richard. Why you shouldn''t use the Library GPL for your next library, Free
Software Foundation 1999 [http://www.gnu.org/philosophy/why-not-lgpl.html]
Links for the User Guide:
http://dot.kde.org
http://lists.kde.org
http://developer.kde.org
http://devel-home.kde.org
http://kde.org
http://kdevelop.org
http://apps.kde.com
http://www.troll.no
Subscribing to the mailing lists on the above sites can also prove to be very beneficial.
6.0 Appendices
6.1 KDevelop 2.0: Application Wizard
As a basic outline of the development environments KDevelop 2.0 provides, following is an overview of the different application wizards that are available on a standard installation. Other options/versions may also be available depending on what you have installed on the system.
Project->New... After choosing to create a new project the application wizard will popup and present you with a variety of frameworks to use.
( reformatted application options as displayed on the kde application popup screen )
KDE
- KDE 2 Mini
o Create a KDE-2 application with an empty main widget.
- KDE 2 Normal
o Create a KDE-2 application with session-management, menubar, toolbar, statusbar and support for a document-view codeframe model.
- KDE 2 Mdi
o Create a KDE-2 MDI (Multiple Document Interface) application with menubar, toolbar, statusbar and support for a document-view codeframe model.
- KDE 2 KControl Module
o Create a KDE-2 Control Center Module. This template enables you to write your own modules to add new system-wide configuration dialogs.
- Konqueror Plugin
o Create a KDE-2 KPart Plugin. To create a generic plugin for the Konqueror web browser use this template. This template can also be modified to make generic plugins.
- KDE 2 Kicker Applet
o Create a KDE-2 Kicker Applet. These are applets for KDE2''s panel.
- KDE 2 Kio Slave
o Create a KDE-2 KIO Slave. KIOSlaves are the foundation for all protocols in KDE2.
- KDE 2 Desktop Theme
o Create a native KDE2 Theme. Use this template to create native KDE-2 widget themes in C++.
GNOME
- Normal
o Create a GNOME application with session-management, menubar, toolbar, statusbar and initial event handling
Qt
- Qt 2.2 SDI
o Create a Qt-2.x Application with a main window containing a menubar, toolbar and statusbar, including support for a Single Document View interface (SDI) model.
- Qt 2.2 MDI
o Create a Qt-2.2 Application with a main window containing a menubar, toolbar and statusbar, including support for a Multiple Document View interface (MDI) model.
- QextMDI
o Create an MDI Framework based on the QextMDI library and Qt-2.0x. Allows to switch between both modes, Toplevel and Childframe. Requires QextMDI!!! [www.geocities.com/gigafalk/qextmdi.htm]
TERMINAL
- C
o Create a C Application. The program will run in a terminal and doesn''t contain any support for classes and Graphical User Interface.
- C++
o Create a C++ Application. The program will run in a terminal and doesn''t contain any support for a Graphical User Interface.
OTHERS
- custom project
o Creates an empty project to work with existing development projects. KDevelop will not take care of any Makefiles as those are supposed to be included with your old project.
6.3 Kdevelop 2.0: Application Wizard?s creation, Source code
Since there was so much source code I thought it better not to submit it, so
you''ll just have to look at your own. Sorry... I also didn''t include the screen shots obviously.
Written by goltor.
This article was originally written by goltor |
| This is an article from http://www.osix.net - view the original at: http://www.osix.net/modules/article/?id=372 |
|