Hello Script Example

The Hello Script example shows the basic use of Qt Script: How to embed a script engine into the application, how to evaluate a script, and how to process the result of the evaluation. The example also shows how to apply internationalization to scripts.

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

The application will load the script file to evaluate from a resource, so we first make sure that the resource is initialized.

    QApplication app(argc, argv);

    QScriptEngine engine;

    QTranslator translator;
    translator.load("helloscript_la");
    app.installTranslator(&translator);
    engine.installTranslatorFunctions();

We attempt to load a translation, and install translation functions in the script engine. How to produce a translation is explained later.

    QPushButton button;
    QScriptValue scriptButton = engine.newQObject(&button);
    engine.globalObject().setProperty("button", scriptButton);

A push button is created and exported to the script environment as a global variable, button. Scripts will be able to access properties, signals and slots of the button as properties of the button script object; the script object acts as a proxy to the C++ button object.

    QString fileName(":/helloscript.js");
    QFile scriptFile(fileName);
    scriptFile.open(QIODevice::ReadOnly);
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();

The contents of the script file are read.

button.text = qsTr('Hello World!');
button.styleSheet = 'font-style: italic';
button.show();

The script sets the text (note that the qTr() function is used to allow for translation) and styleSheet properties of the button, and calls the button's show() slot.

    QScriptValue result = engine.evaluate(contents, fileName);

The script is evaluated. Note that the file name is passed as the (optional) second parameter; this makes it possible for the script engine to produce a meaningful backtrace if something goes wrong, and makes the qTr() function be able to resolve the translations that are associated with this script.

    if (result.isError()) {
        QMessageBox::critical(0, "Hello Script",
                              QString::fromLatin1("%0:%1: %2")
                              .arg(fileName)
                              .arg(result.property("lineNumber").toInt32())
                              .arg(result.toString()));
        return -1;
    }

If the result is an Error object (e.g. the script contained a syntax error, or tried to call a function that doesn't exist), we obtain the line number and string representation of the error and display it in a message box.

    return app.exec();
}

If the evaluation went well, the application event loop is entered.

Translating the Application

The Qt Script internalization support builds on what Qt already provides for C++; see the Hello tr() Example for an introduction.

Since we haven't made the translation file helloscript_la.qm, the source text is shown when we run the application ("Hello world!").

To generate the translation file, run lupdate as follows:

lupdate helloscript.js -ts helloscript_la.ts

You should now have a file helloscript_la.ts in the current directory. Run linguist to edit the translation:

linguist helloscript_la.ts

You should now see the text "helloscript.js" in the top left pane. Double-click it, then click on "Hello world!" and enter "Orbis, te saluto!" in the Translation pane (the middle right of the window). Don't forget the exclamation mark!

Click the Done checkbox and choose File|Save from the menu bar. The TS file will no longer contain

<translation type='unfinished'></translation>

but instead will have

<translation>Orbis, te saluto!</translation>

To see the application running in Latin, we have to generate a QM file from the TS file. Generating a QM file can be achieved either from within Qt Linguist (for a single TS file), or by using the command line program lrelease which will produce one QM file for each of the TS files listed in the project file. Generate hellotr_la.qm from hellotr_la.ts by choosing File|Release from Qt Linguist's menu bar and pressing Save in the file save dialog that pops up. Now run the helloscript program again. This time the button will be labelled "Orbis, te saluto!".

Files:

© 2019 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.