How to use javascript with QScript in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:Abstract The program in this article will create a button and the text of the button to display is set by the JavaScript file and again button will be shown by Qt application.

Template:ArticleMetaData

Header File[edit | edit source]

No header file is used in this example. Complete code is written in the single file.

Source file[edit | edit source]

  1. include <QApplication>
  1. include <QPushButton>
  2. include <QtScript>
  3. include <QLabel>


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

   Q_INIT_RESOURCE(hello);
   QApplication app(argc, argv);
   QScriptEngine engine;
   QPushButton button;
   QScriptValue scriptButton = engine.newQObject(&button);
   engine.globalObject().setProperty("button", scriptButton);
   QString fileName(":/hello.js");
   QFile scriptFile(fileName);
   scriptFile.open(QIODevice::ReadOnly);
   QTextStream stream(&scriptFile);
   QString contents = stream.readAll();
   scriptFile.close();
   QScriptValue result = engine.evaluate(contents, fileName);
   
   button.show();
   return app.exec();

}


Script file[edit | edit source]

button.text = 'jajal mehul!'; button.styleSheet = 'color:red;font-style: italic';

Output[edit | edit source]

File:Scrpt.jpg