Development/Tutorials/Kross/Hello World: Difference between revisions

    From KDE TechBase
    (inline-dox++)
    Line 31: Line 31:


    === main.cpp ===
    === main.cpp ===
    The main.cpp contains the entry-point for our sample application.


    <code cpp>
    <code cpp>

    Revision as of 19:55, 7 October 2007

    Hello world in kross
    Tutorial Series   Kross tutorials
    Previous   Kross introduction
    What's Next   Scripts as plugins
    Further Reading   n/a
    Warning
    This section needs improvements: Please help us to

    cleanup confusing sections and fix sections which contain a todo


    This tutorial is intended to be a simple introduction to kross for the kde4 application writer in multiple scripting languages.

    Additional Bindings

    If you have already set up your environment as described in Getting Started/Build/KDE4, you can already use kross with the javascript language. You can choose optionally to install support for python and ruby from kdebindings. Either checkout and build kdebindings, or just the kdebindings/python and kdebindings/ruby subdirectories (Installing_a_subset_of_a_module).

    cs KDE svn co -N kdebindings cd kdebindings svn up python svn up ruby cmakekde

    Hello World

    In this tutorial a simple dialog is created which contains a drop-down list and a label. When an interpreter is selected from the list, some scripting code is executed and the label text is updated in the script.

    Create a krosshello folder in the kde-devel home directory (or choose another location). Create the following files and run cmakekde:

    main.cpp

    The main.cpp contains the entry-point for our sample application.

    // First some Qt and KDE includes

    1. include <QString>
    2. include <KApplication>
    3. include <KAboutData>
    4. include <KMessageBox>
    5. include <KCmdLineArgs>
    6. include <KLocalizedString>

    // Also include the MainWindow class

    1. include "mainwindow.h"

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

       // Used to store information about a program.
       KAboutData aboutData("krosshello",
           0,
           ki18n("Kross Hello World"),
           "1.0",
           ki18n("Hello World application for Kross"),
           KAboutData::License_GPL,
           ki18n("(c) 2007"),
           ki18n("Some text..."),
           "http://kross.dipe.org",
           "[email protected]");
    
       // Access to the command-line arguments.
       KCmdLineArgs::init( argc, argv, &aboutData );
       // Initialize the application.
       KApplication app;
    
       // Create and show the main window.
       MainWindow* window = new MainWindow();
       window->show();
    
       // Finally execute the application.
       return app.exec();
    

    }

    mainwindow.h

    1. ifndef MAINWINDOW_H
    2. define MAINWINDOW_H
    1. include <QComboBox>
    2. include <QLabel>

    class MainWindow : public QWidget {

       Q_OBJECT
     public:
       MainWindow(QWidget *parent=0);
     private Q_SLOTS:
       void interpreterActivated(const QString &);
     private:
       QLabel* lblHello;
       QComboBox* cmbHello;
    

    };

    1. endif

    mainwindow.cpp

    This code creates a simple dialog with a combobox showing available interpreters along with a label for displaying a message. The kross/core/manager.h and kross/core/action.h are included to provide kross functionality, which is invoked when a selection is made on the combobox. The code below makes the lblHello label available to scripts as a MyLabel object, and executes different code depending on the interpreter chosen.

    1. include <QVBoxLayout>
    2. include <QDebug>
    3. include "mainwindow.h"
    1. include <kross/core/manager.h>
    2. include <kross/core/action.h>

    MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {

     cmbHello = new QComboBox ();
     cmbHello->addItem("Choose Interpreter", "");
    
     foreach(QString s, Kross::Manager::self().interpreters())
       cmbHello->addItem(s);
    
     connect(cmbHello, SIGNAL(activated(const QString &)), SLOT(interpreterActivated(const QString &)));
    
     lblHello = new QLabel("Hello");
    
     QVBoxLayout *layout = new QVBoxLayout;
     layout->addWidget(cmbHello);
     layout->addWidget(lblHello);
     setLayout(layout);
    

    }

    void MainWindow::interpreterActivated(const QString &strSelectedInterpreter) {

     if(strSelectedInterpreter.isEmpty())
     {
       lblHello->setText("-");
       return;
     }
    
     Kross::Action action(this, "MyScript");
     if(strSelectedInterpreter == "python")
       action.setCode("import MyLabel\nMyLabel.text = 'Hello from python!'");
     else if(strSelectedInterpreter == "ruby")
       action.setCode("require 'MyLabel'\nMyLabel.text = 'Hello from ruby!'");
     else if(strSelectedInterpreter == "javascript")
       action.setCode("MyLabel.setText('Hello from javascript!')");
     else
       return;
     action.setInterpreter(strSelectedInterpreter);
     action.addObject(lblHello, "MyLabel");
    
     action.trigger();
    

    }


    CMakeLists.txt

    project (krosshello)

    find_package(KDE4 REQUIRED) include_directories( ${KDE4_INCLUDES} )

    set(krosshello_SRCS main.cpp mainwindow.cpp)

    kde4_add_executable(krosshello ${krosshello_SRCS}) target_link_libraries(krosshello ${KDE4_KDEUI_LIBS} ${KDE4_KROSSUI_LIBS})

    Using separate script files

    The next step is to extract the scripts into separate files. This has the obvious advantage of being editable without being recompiled. Edit the MainWindow::interpreterActivated in mainwindow.cpp to the following:

    void MainWindow::interpreterActivated(const QString &strSelectedInterpreter) {

     if(strSelectedInterpreter.isEmpty())
     {
       lblHello->setText("-");
       return;
     }
    
     QString filename;
    
     Kross::Action action(this, "MyScript");
     if(strSelectedInterpreter == "python")
       filename = "krosshello.py";
     else if(strSelectedInterpreter == "ruby")
       filename = "krosshello.rb";
     else if(strSelectedInterpreter == "javascript")
       filename = "krosshello.js";
     else
       return;
    
     action.setFile(filename);
     //action.setInterpreter(strSelectedInterpreter);
     action.addObject(lblHello, "MyLabel");
    
     action.trigger();
    

    It is no longer neccessary to set the interpreter for the action explicitly. Kross chooses the correct interpreter based on the filename given in setFile().

    For example, edit krosshello.py file to include the following:

    1. !/usr/bin/env kross

    import MyLabel

    MyLabel.text = "Hello from inside a python file."


    It is also possible to call a function and return the result to the application.

    def reverseString(s):

       s = s[::-1]
       return s
    

    function reverseString(s){

       return s.split("").reverse().join("");
    

    }

    Add the above to krosshello.js or krosshello.py and edit the mainwindow.cpp again to include the following after action.trigger():

    QVariant result = action.callFunction("reverseString", QVariantList() << "Hello World"); lblHello->setText(result.toString());


    Ususally it will not make sense to use callFunction in an application, but instead connect signals and slots directly between the application and the script.

    Edit this with a simple signals/slots example.
    TODO


    Add note about automatic connection of signals and slots.
    TODO


    This is the more practical way to use kross, and is described in more detail at Scripts as plugins.