Difference between revisions of "User:Dipesh/Kross-Tutorial"

(fix links)
m (fixed errors in the example code)
Line 101: Line 101:
   Q_PROPERTY(QString name READ name WRITE setName)
   Q_PROPERTY(QString name READ name WRITE setName)
     MyObject(QObject* parent) : QObject(parent) {}
     MyObject(QObject* parent = 0) : QObject(parent) {}
     virtual ~MyObject() {}
     virtual ~MyObject() {}
     QString name() const { return objectName(); }
     QString name() const { return objectName(); }
Line 114: Line 114:
       return obj;
       return obj;
     QObject* parent() const { return parent(); }
     QObject* parent() const { return QObject::parent(); }
     void setParent(QObject* parent) {
     void setParent(QObject* parent) {
       emit parentChanged();  
       emit parentChanged();  

Revision as of 13:05, 5 April 2007

This section needs improvements: Please help us to

cleanup confusing sections and fix sections which contain a todo


The purpose of this tutorial is to offer a step-by-step introduction how to integrate Kross into your application. While you can integrate Kross also in non-kpartified applications, it's easier to do with the KPart system. This tutorial will assume that you have a kpart application and what we will do is to go step by step through the process of creating a KPart plugin that integrates into your application and provides all the scripting. The scripting functionality is strictly separated from the application. The plugin that implements scripting is optional and the application does not need to know any details about what the plugin does.

This tutorial needs kdelibs4 based on Qt 4.2. While Kross and the KDE Javascript backend are included in kdelibs4, it is needed to compile the KOffice2 libraries to install the Ruby and Python support (will be moved to kdebindings soon).

The whole sourcecode we will produce within this tutorial could also be downloaded as kross2tutorial.tar.gz and contains all files needed to build a simple example that demonstrates how Kross could be used. Download and extract the tarball. Compile, install and run the kross2tutorialapp application and its kross2tutorial KPart plugin now with;

cd src && mkdir _build && cd _build
cmake -DCMAKE_INSTALL_PREFIX=`kde4-config --prefix` ..
sudo make install

For additional examples where Kross is used you may also like to look at;


The Kross scripting framework provides full Python, Ruby and KDE JavaScript scripting support. The goal was to limit the work needed on applications to have them fully scriptable and to provide a modular way to transparently integrate additional interpreters and in that way extend your application with a new scripting-backend without any new line of code and even without any recompile. To achieve this internally Qt's introspection-functionality like signals, slots, properties, enums, QVariant, QObject, QMetaObject, QMetaType, etc. are used to deal with functionality at runtime.

The Interpreter plugins

Kross offers a plugin-interface to integrate interpreter backends like Python, Ruby and KDE-Javascript. They are loaded on demand at runtime. Neither the application nor Kross needs to know any details about the backends. This clear separation between the application and scripting details enables at the one hand, to deal with scripting at an abstract level without being bound to only one backend, and at the other hand makes it easy to integrate scripting into an already existing application.

Currently Kross comes with support for 3 scripting backends;

Each interpreter plugin needs to implement two abstract classes;

  • The Kross::Interpreter class is a singleton controlled by the Kross::Manager and could be used to setup the interpreter or do other things to share functionality between instances of the Script class.
  • The Kross::Script class handles exactly one script instance. An application is able to deal with multiple scripts at the same time where each of them has it's own instance of the Kross::Script class controlled by an instance of the more abstract Kross::Action class.

The Module plugins

Modules are plugins loaded on demand at runtime to provide additional functionality. They are somewhat wrappers/bindings/adaptors to offer access to functionality your application or a library of your application likes to expose to scripting backends. TODO: this parag doesn't parse for me

Since Qt's introspection functionality is used, we are able to throw in just QObject's and have them act as classes/objects within a scripting backend. Slots are membermethods while properties and enumerations are membervariables. If your application also likes to offer DBus support it may be an idea to reuse the QDBusAbstractAdaptor implementations your application has also for scripting, like for example KSpread did.

Let's take a look at the following code that implements such a module;

class MyObject : public QObject {
  Q_PROPERTY(QString name READ name WRITE setName)
    MyObject(QObject* parent = 0) : QObject(parent) {}
    virtual ~MyObject() {}
    QString name() const { return objectName(); }
    void setName(const QString& name) {
      return setObjectName(name);
  public slots:
    QObject* create(const QString& name,
                    QObject* parent=0) {
      MyObject* obj = new MyObject(parent);
      return obj;
    QObject* parent() const { return QObject::parent(); }
    void setParent(QObject* parent) {
      emit parentChanged(); 
    void parentChanged();
extern "C" {
  QObject* krossmodule() {
    return new MyObject();

Then we just need to have our myobject.h and myobject.cpp files, filled with the content above, defined in the CMakeLists.txt file. The library needs to be named "krossmodule..." where the "..." is then the name the module is accessible as. For our example we use "krossmodulemyobjectmod" and therefore we are able to access the module if installed as "myobjectmod". The example does not depend on Kross, so you may like to replace ${KROSS_INCLUDES} with whatever else your module depends on.

install(TARGETS krossmodulemyobjectmod

The following Python sample code accesses then the module at runtime and uses the QObject, calls it's slots and properties and connects a signal with a python function (e.g. save as file named "myobjecttest.py" and execute with "kross ./myobjecttest.py");

#!/usr/bin/env kross
import Kross
m = Kross.module("myobjectmod")
m.name = "MyObjectModuleName"
obj1 = m.create("OtherObjectName")
def myCallbackFunc(args):
    print "The parent of obj1 changed"
print "%s %s" % (obj1.name,obj1.parent().name)

Manager, GuiClient, Action

The Kross::Manager class is a singleton that provides access to the interpreters, to actions and to the modules. The Kross::Manager is available within scripting code as module named "Kross". Following Python script uses the Kross module to create a new Kross::Action instance, fills it with JavaScript code and executes that JavaScript code.

#!/usr/bin/env kross
import Kross
a = Kross.action("MyKjsScript")
a.setCode("println(\"Hello world from Kjs\");")

The Kross::GuiClient class implements KXMLGUIClient to provide GUI functionality, handling of XML configuration files on a more abstract level and offers some predefined actions that could be optionally used in your application.

The Kross::Action class offers an abstract container to deal with scripts like a single standalone scriptfile. Each action holds a reference to the by the matching Kross::Interpreter instance created by Kross::Script instance. Following Python script accesses the Kross module and the self variable which is our Kross::Action instance that provides the context for the running Python script.

#!/usr/bin/env kross
import Kross
print "objectName=%s" % Kross.objectName()
print "interpreters=%s" % Kross.interpreters()
print "objectName=%s" % self.objectName()
print "text=%s" % self.text
print "enabled=%s" % self.enabled
print "currentPath=%s" % self.currentPath()
print "interpreter=%s" % self.interpreter()
print "description=%s" % self.description()
print "code=%s" % self.code()

DBus and Kross

With the QtDBus module Qt provides a library that a Qt/KDE application is able to use to make Inter-Process Communication using the D-BUS protocol.

The QtDBus module uses the Qt Signals and Slots mechanism. Applications that like to provide parts of there functionality to the DBus world are able to do so by implementing classes that inherit from the QDBusAbstractAdaptor class.

Kross is able to reuse such by an application provided bindings. So, once your application supports dbus, Kross is able to reuse those already existing code and offers transparent access to the scripting-backends to them. How does this differ from e.g. the python-dbus package? Well, first method-calls don't go through the dbus-socket and then it's not dbus-related at all except, that we are able to reuse what your application offers anyway: a clean interface to the outside world. But that's not all, we are not limited to what's possible with dbus. We are also able to exchange instance-pointers to QObject or QWidget instances.

For an example you may like to take a look at how it was done in the KSpread ScriptingModule class.

The application

This section deals with the question how to integrate Kross into a KPart-application to be able to extend your application with scripting.

For testing purposes we first create a simple KPart application. If you already have an application you may like to skip this section and continue with the KPart Plugin.

Relevant files within the kross2tutorial.tar.gz are;

The CMake build system

The src/CMakeLists.txt file;


find_package(KDE4 REQUIRED)
find_package(Perl REQUIRED)

add_subdirectory( plugin )

  mainwindow.cpp main.cpp)
  kparts krosscore )

The src/plugin/CMakeLists.txt file;

  module.cpp part.cpp)
  kparts )
install(TARGETS krossmoduletutorial
install(FILES krossmoduletutorial.desktop

The KApplication

The main function (main.cpp) creates the KApplication and shows the MainWindow.

int main(int argc, char **argv) {
  KAboutData about();
  KApplication app();
  MainWindow *mainWin = new MainWindow();
  return app.exec();

The KPart main window

The MainWindow class (mainwindow.h mainwindow.cpp) contains the top-level KParts::MainWindow implementation.

class MainWindow
    : public KParts::MainWindow
      : KParts::MainWindow()
      KLibFactory* factory =
      KParts::ReadWritePart* part =
          ( factory->create(this) );
    virtual ~MainWindow() {}

The plugin

The KPart plugin

The Part class (part.h part.cpp) implements a KParts::ReadWritePart.

class Part
  : public KParts::ReadWritePart
    Part(QWidget*, QObject* parent,
      const QStringList&)
      : KParts::ReadWritePart(parent)
      , m_guiclient(
          new Kross::GUIClient(this,this))
      , m_action(0) {}
    virtual ~Part() { delete m_action; }
    virtual bool openFile() {
      delete m_action;
      m_action = new Kross::Action(m_file);
    virtual bool saveFile() {return false;}
    Kross::GUIClient* m_guiclient;
    Kross::Action* m_action;

The Module

The Module class (module.h module.cpp) implements the "KrossModuleTutorial" module.

class Module : public QObject {
    Module(Part* part=0)
      : QObject(part), m_widget(0) {}
    virtual ~Module() {}
  public slots:
    QWidget* widget() {
      if(m_widget) return m_widget;
      Part* part = 
      m_widget = new QWidget(
        part ? part->widget() : 0 );
        new QVBoxLayout(m_widget) );
      QWidget* w = 
        part ? part->widget() : 0;
      if(w && w->layout())
      return m_widget;
    QWidget* m_widget;


Following sample scripts are also included in the kross2tutorial.tar.gz and should be executed using the "kross2tutorialapp" application.

Python forms script

The sample_forms.py Python script demonstrates usage of into an application embedded Kross forms.

#!/usr/bin/env kross
import Kross
import KrossModuleTutorial
forms = Kross.module("forms")
w = KrossModuleTutorial.widget()
l = forms.createWidget(w,"QLabel")
l.wordWrap = True
l.text = "The labels text."
b = forms.createWidget(w,"QPushButton")
def buttonClicked():
  global forms
    "Caption", "the message text")
b.connect("clicked()", buttonClicked)
b.text = "Show messagebox"

Python Tkinter script

The sample_tkinter.py Python script uses the Tkinter to show a modal dialog.

#!/usr/bin/env kross
class TkTest:
  def __init__(self):
    import Tkinter
    self.root = Tkinter.Tk()
    self.mainframe =
    self.button1 = Tkinter.Button(
  def callback1(self):
    import tkMessageBox
      "Callback1", "Callback1 called.")

Ruby forms script

The sample_forms.rb Ruby script uses the Kross forms module to create and embedded a QLabel instance.

#!/usr/bin/env kross
require 'Kross'
require 'KrossModuleTutorial'
forms = Kross.module("forms")
w = KrossModuleTutorial.widget()
l = forms.createWidget(w,"QLabel")
l.wordWrap = true
l.text = "Some labels text"

JavaScript with KjsEmbed script

The sample_kjsembed.js JavaScript script creates and embeddes a QFrame using KjsEmbed.

#!/usr/bin/env kross
w = KrossModuleTutorial.widget()
var f = new Widget("QFrame", w);
f.frameShape = f.StyledPanel;
f.frameShadow = f.Sunken;
f.lineWidth = 4;

This page was last edited on 5 April 2007, at 13:05. Content is available under Creative Commons License SA 4.0 unless otherwise noted.