Development/Tutorials/Using KParts (de)

From KDE TechBase
Revision as of 14:47, 23 September 2008 by DrSlowDecay (talk | contribs) (Page created and initial translation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Development/Tutorials/Using_KParts


Wie man KParts benutzt
Anleitungsserie   Plugins und KParts
Voriges Kapitel   Anleitung 5 - Kommandozeilenargumente
Nächstes Kapitel   n/a
Weiterführende Texte   KParts Dokumentation (englisch)
Navigation   Deutsche Startseite

Einführung

Die KPart Technologie wird in KDE benutzt, um GUI Komponenten wiederzuverwerten. Der Vorteile eines KParts sind dabei die vordefinierte Aktionen, wie Werkzeugleistenknöpfe. Indem man kparts in Applikationen benutzt, braucht ein Entwickler weniger Zeit in die Implementation eines Texteditors oder Kommandozeilenaktionen investieren und statt dessen einfach ein katepart oder ein konsolepart benutzen. KParts werden auch mit der Plugin Technologie benutzt, um Applikationen in andere einzubetten, wie es zum Beispiel die PIM Applikationen in Kontact machen.

Diese Anleitung zeigt, wie man ein KPart in der eigenen Applikation einsetzt und wie man sein eigenes KPart erzeugt.

Katepart benutzen

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.

main.cpp

  1. include <KApplication>
  2. include <KAboutData>
  3. include <KCmdLineArgs>
  4. include <KUrl>
  1. include "mainwindow.h"

int main (int argc, char *argv[]) {

   KAboutData aboutData( "kparttutorial1", "kparttutorial1",
       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.

mainwindow.h

  1. ifndef KPARTTUTORIAL1_H
  2. define KPARTTUTORIAL1_H
  1. 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 <[email protected]>
* @version 0.1
*/

class MainWindow : public KParts::MainWindow {

   Q_OBJECT

public:

   /**
    * Default Constructor
    */
   MainWindow();
   /**
    * Default Destructor
    */
   virtual ~MainWindow();
   /**
    * Use this method to load whatever file/URL you have
    */
   void load(const KUrl& url);

private:

   void setupActions();

private:

   KParts::ReadWritePart *m_part;

};

  1. 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.

mainwindow.cpp

  1. include "mainwindow.h"
  1. include <kaction.h>
  2. include <kactioncollection.h>
  3. include <kconfig.h>
  4. include <kedittoolbar.h>
  5. include <kfiledialog.h>
  6. include <kshortcutsdialog.h>
  7. include <klibloader.h>
  8. include <kmessagebox.h>
  9. include <kstandardaction.h>
  10. include <kstatusbar.h>
  11. include <kurl.h>
  1. include <QApplication>

MainWindow::MainWindow()

   : KParts::MainWindow( )

{

   // Setup our actions
   setupActions();
   // this routine will find and load our Part.  
   KLibFactory *factory = KLibLoader::self()->factory("katepart");
   if (factory)
   {
       // now that the Part is loaded, we cast it to a Part to get
       // our hands on it
       m_part = static_cast<KParts::ReadWritePart *>
                (factory->create(this, "KatePart" ));
       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
   {
       // if we couldn't find our Part, we exit since the Shell by
       // itself can't do anything useful
       KMessageBox::error(this, "Could not find our Part!");
       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(fileOpen()), 
       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.

kparttut1ui.rc

<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"> <kpartgui name="kparttut1" version="1"> <MenuBar>

 <Menu noMerge="1" name="file"><text>&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.

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})

                      1. install files ###############

install(TARGETS kparttut1 DESTINATION ${BIN_INSTALL_DIR} ) install( FILES kparttut1ui.rc

   DESTINATION  ${DATA_INSTALL_DIR}/kparttut1 )

Die CMakeLists.txt Datei ist in diesem Fall sehr einfach.

Die Applikation ausführen

Nach dem Kompilieren der Appikation kann diese mit kparttut1 filename ausgeführt werden. filename ist dabei eine Textdatei, die geladen werden soll. Eine der Quellcodedateien wäre ein gutes Beispiel dafür.

Wenn die Datei geladen wird, steht einem ein kompletter kate-Editor in seinem eigenen Fenster zu Verfügung. Alle Features des Editors sind über die Werkzeugleiste und Menüs verfügbar.

Weiterhin fällt die 'Öffnen' Aktion auf, welche in der MainWindow class definiert wurde und auch in der Werkzeugleiste und im Menü neben der 'Beenden' Aktion erscheint.

Die nächste Anleitung wird sich mit dem Erzeugen eigener kparts für die Benutzung in anderen Applikationen beschäftigen.