Hello World Using QtScript

From Qt Wiki
Jump to navigation Jump to search

Template:Abstract It demonstrates how to embed a script engine into the application, how to evaluate a script, and how to process the result of the evaluation.

Template:ArticleMetaData

Source[edit | edit source]

  1. include <QApplication>
  2. include <QMessageBox>
  3. include <QPushButton>
  4. include <QtScript>


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

   // load the script file to evaluate from a resource
   Q_INIT_RESOURCE(helloscript);
   QApplication app(argc, argv);
   QScriptEngine engine;
   // 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
   QPushButton button;
   QScriptValue scriptButton = engine.newQObject(&button);
   engine.globalObject().setProperty("button", scriptButton);
   // read the contents of the script file
   QString fileName(":/helloscript.js");
   QFile scriptFile(fileName);
   scriptFile.open(QIODevice::ReadOnly);
   QTextStream stream(&scriptFile);
   QString contents = stream.readAll();
   scriptFile.close();


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


   // If any Error, Display line number and error in a message box.
   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;
   }
   // App Event loop is entered if everything went well
   return app.exec();

}

Script File (helloscript.js)[edit | edit source]

// set the text and stylesheet of button in script button.text = 'Hello World!'; button.styleSheet = 'font-style: italic'; button.show();


Project file (helloscript.pro)[edit | edit source]

You need following linkage in your .pro file.

QT += script RESOURCES += helloscript.qrc SOURCES += main.cpp

  1. install

target.path = $$[QT_INSTALL_EXAMPLES]/script/helloscript sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS helloscript.pro sources.path = $$[QT_INSTALL_EXAMPLES]/script/helloscript INSTALLS += target sources

symbian: include($$PWD/../../symbianpkgrules.pri)

Resource file (helloscript.qrc)[edit | edit source]

Add helloscript.js file in Resource file.

<RCC>
    <qresource prefix="/" >
        <file>helloscript.js</file>
    </qresource>
</RCC>

References[edit | edit source]