Difference between revisions of "Development/Tutorials/Using KParts"

Jump to: navigation, search
(You don't add the .desktop extension when querying for services)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Template:I18n/Language Navigation Bar|Development/Tutorials/Using_KParts}}
+
 
  
 
{{TutorialBrowser|
 
{{TutorialBrowser|
Line 23: Line 23:
 
  /root/.kde/share/kde4/services/:/usr/local/share/kde4/services/
 
  /root/.kde/share/kde4/services/:/usr/local/share/kde4/services/
  
The first kPart we describe is KatePart, an editor representing a typical [http://api.kde.org/4.0-api/kdelibs-apidocs/kparts/html/classKParts_1_1ReadWritePart.html ReadWritePart]. A typical [http://api.kde.org/4.0-api/kdelibs-apidocs/kparts/html/classKParts_1_1ReadOnlyPart.html ReadOnlyPart] would be ]http://api.kde.org/4.5-api/kdebase-apps-apidocs/konsole/html/classKonsole_1_1Part.html konsolePart].
+
The first kPart we describe is KatePart, an editor representing a typical [http://api.kde.org/4.0-api/kdelibs-apidocs/kparts/html/classKParts_1_1ReadWritePart.html ReadWritePart]. A typical [http://api.kde.org/4.0-api/kdelibs-apidocs/kparts/html/classKParts_1_1ReadOnlyPart.html ReadOnlyPart] would be [http://api.kde.org/4.5-api/kdebase-apps-apidocs/konsole/html/classKonsole_1_1Part.html konsolePart].
  
 
== Using Katepart ==
 
== Using Katepart ==
Line 158: Line 158:
 
     //query the .desktop file to load the requested Part
 
     //query the .desktop file to load the requested Part
 
     KService::Ptr service = KService::serviceByDesktopPath
 
     KService::Ptr service = KService::serviceByDesktopPath
                           ("katepart.desktop");
+
                           ("katepart");
  
 
     if (service)
 
     if (service)
Line 184: Line 184:
 
         // if we couldn't find our Part, we exit since the Shell by
 
         // if we couldn't find our Part, we exit since the Shell by
 
         // itself can't do anything useful
 
         // itself can't do anything useful
         KMessageBox::error(this, "service katepart.desktop not found");
+
         KMessageBox::error(this, "service katepart not found");
 
         qApp->quit();
 
         qApp->quit();
 
         // we return here, cause qApp->quit() only means "exit the
 
         // we return here, cause qApp->quit() only means "exit the

Latest revision as of 23:29, 14 July 2013


How To Use KParts
Tutorial Series   Plugins and KParts
Previous   Tutorial 5 - Command line arguments
What's Next   n/a
Further Reading   KParts Documentation

Contents

[edit] Introduction

KPart technology is used in kde to reuse GUI components. The advantage that a KPart presents is that it comes with predefined toolbar actions. By using kparts in applications developers can spend less time implementing text editor or command line features, for example and just use a katepart or a konsolepart instead. KParts are also used with Plugin technology to embed applications inside another, such as integrating PIM applications into Kontact.

This tutorial will show you how to use a KPart in your application, and how to create your own KPart.

KParts consist of a .desktop file describing the KPart and a .so file containing the function names and code. The .desktop file resides in KDE's services directory, you can find it out like this:

# kde4-config --path services
/root/.kde/share/kde4/services/:/usr/local/share/kde4/services/

The first kPart we describe is KatePart, an editor representing a typical ReadWritePart. A typical ReadOnlyPart would be konsolePart.

[edit] Using Katepart

Simple KDE applications use a MainWindow derived from KMainWindow (such as in previous tutorials). To use a KPart in an application, the MainWindow must instead be derived from KParts::MainWindow. This will then take care of integrating the toolbar and menu items of the kpart together.

The following code creates a KParts::MainWindow with a kpart inside it.

[edit] main.cpp

#include <KApplication>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KUrl>
 
#include "mainwindow.h"
 
int main (int argc, char *argv[])
{
    KAboutData aboutData( "kparttut1", "kparttut1",
        ki18n("KPart Tutorial 1"), "0.1",
        ki18n("A MainWindow for a KatePart."),
        KAboutData::License_GPL,
        ki18n("Copyright (c) 2007 Developer") );
    KCmdLineArgs::init( argc, argv, &aboutData );
 
    KCmdLineOptions options;
    options.add("+[file]", ki18n("Document to open"));
    KCmdLineArgs::addCmdLineOptions(options);
 
    KApplication app;
 
    MainWindow* window = new MainWindow();
    window->show();
 
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if(args->count())
    {
        window->load(args->url(0).url());
    }
 
    return app.exec();
}

The main.cpp file is the same as that used in Tutorial 5 - Command line arguments.The only difference is in the details of the KAboutData.

[edit] mainwindow.h

#ifndef KPARTTUTORIAL1_H        
#define KPARTTUTORIAL1_H        
 
#include <kparts/mainwindow.h>  
 
/**                             
 * This is the application "Shell".  It has a menubar, toolbar, and
 * statusbar but relies on the "Part" to do all the real work.     
 *                                                                 
 * @short Application Shell                                        
 * @author Developer <developer@kde.org>                           
 * @version 0.1
 */
class MainWindow : public KParts::MainWindow
{
    Q_OBJECT
public:
    /**
     * Default Constructor
     */
    MainWindow();
 
    /**
     * Default Destructor
     */
    virtual ~MainWindow();
 
public slots:
    /**
     * Use this method to load whatever file/URL you have
     */
    void load(const KUrl& url);
 
    /**
     * Use this method to display an openUrl dialog and
     * load the URL that gets entered
     */
    void load();
 
private:
    void setupActions();
 
private:
    KParts::ReadWritePart *m_part;
};
 
#endif // KPARTTUT1_H

The mainwindow.h file is very simple. The important thing to notice here is that the MainWindow class inherits from KParts::MainWindow.

[edit] mainwindow.cpp

#include "mainwindow.h"
 
#include <kaction.h>
#include <kactioncollection.h>
#include <kconfig.h>
#include <kedittoolbar.h>
#include <kfiledialog.h>
#include <kshortcutsdialog.h>
#include <klibloader.h>
#include <kmessagebox.h>
#include <kservice.h>
#include <kstandardaction.h>
#include <kstatusbar.h>
#include <kurl.h>
 
#include <QApplication>
 
MainWindow::MainWindow()
    : KParts::MainWindow( )
{
 
    // Setup our actions
    setupActions();
 
    //query the .desktop file to load the requested Part
    KService::Ptr service = KService::serviceByDesktopPath
                           ("katepart");
 
    if (service)
    {
      m_part = service->createInstance<KParts::ReadWritePart>(0);
 
      if (m_part)
      {
            // tell the KParts::MainWindow that this is indeed
            // the main widget
            setCentralWidget(m_part->widget());
 
            setupGUI(ToolBar | Keys | StatusBar | Save);
 
            // and integrate the part's GUI with the shell's
            createGUI(m_part);
      }
      else
      {
          return;//return 1; 
      }
    }
    else
    {
        // if we couldn't find our Part, we exit since the Shell by
        // itself can't do anything useful
        KMessageBox::error(this, "service katepart not found");
        qApp->quit();
        // we return here, cause qApp->quit() only means "exit the
        // next time we enter the event loop...
        return;
    }
}
 
MainWindow::~MainWindow()
{
}
 
void MainWindow::load(const KUrl& url)
{
    m_part->openUrl( url );
}
 
void MainWindow::setupActions()
{
    KStandardAction::open(this, SLOT(load()), 
        actionCollection());
    KStandardAction::quit(qApp, SLOT(closeAllWindows()),
        actionCollection());
}
 
void MainWindow::load()
{
    load(KFileDialog::getOpenUrl());
}

The mainwindow.cpp file contains the implementation of MainWindow. The constructor of this class contains all the code used to load the KPart.

First it sets up the actions used by the main window (Open and Quit), and then sets up the gui elements to go with these items (toolbar items, menu items, keyboard shortcuts). Next is the standard code used to load the KPart. The createGUI method is responsible for merging the toolbars and menus of the KPart with the rest of the application.

Note: although the part can also be loaded using KPluginLoader, this method is depricated.

   KPluginFactory* factory = KPluginLoader("katepart").factory();

[edit] kparttut1ui.rc

<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
<kpartgui name="kparttut1" version="1">
<MenuBar>
  <Menu noMerge="1" name="file"><text>&amp;File</text>
    <Action name="file_open"/>
    <Separator/>
    <Merge/>
    <Separator/>
    <Action name="file_quit"/>
  </Menu>
 
  <Merge />
</MenuBar>
<ToolBar noMerge="1" name="mainToolBar"><text>Main Toolbar</text>
  <Action name="file_open"/>
  <Merge/>
</ToolBar>
</kpartgui>

The kparttut1ui.rc file is used to define how the actions in the part and the actions in the main window will be merged together. The <Merge /> element in the file menu for example indicates that any part containing actions in a file menu should list its parts after the file_open action and before the file_quit action.

[edit] CMakeLists.txt

project(kparttut1)
 
FIND_PACKAGE(KDE4 REQUIRED)
INCLUDE_DIRECTORIES( ${KDE4_INCLUDES} . )
 
set(kparttut1_SRCS
   main.cpp
   mainwindow.cpp
 )
 
kde4_add_executable(kparttut1 ${kparttut1_SRCS})
 
target_link_libraries(kparttut1 ${KDE4_KDEUI_LIBS} ${KDE4_KPARTS_LIBS})
 
########### install files ###############
install(TARGETS kparttut1 DESTINATION ${BIN_INSTALL_DIR} )
install( FILES kparttut1ui.rc 
    DESTINATION  ${DATA_INSTALL_DIR}/kparttut1 )

The CMakeLists.txt file is very simple in this case.

[edit] Running the Application

After compiling, linking and installing the application with

mkdir build && cd build && cmake .. && make -j4 && make install

it can be executed with

kparttut1 filename

where filename is a text file to load. One of the source files would be a good example.

When the file loads you will have a full-featured kate editor running in its own window. All of the editor features of kate are available in the toolbars and menu.

You will notice that the 'Open' action you defined in the MainWindow class has also appeared in the toolbar and in the menu along with the 'Quit' action.

The next tutorial will deal with creating your own kparts for use (and reuse) in other applications.


This page was last modified on 14 July 2013, at 23:29. This page has been accessed 18,607 times. Content is available under Creative Commons License SA 3.0 as well as the GNU Free Documentation License 1.2.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V.Legal