How to use javascript with QScript in Qt
This article demonstrates how to use simple JavaScript with your Qt application. 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.
Article Metadata
Contents |
Header File
No header file is used in this example. Complete code is written in the single file.
Source file
#include <QApplication>
#include <QPushButton>
#include <QtScript>
#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
button.text = 'jajal mehul!';
button.styleSheet = 'color:red;font-style: italic';



I have just added Abstract in the article. --somnathbanik 17:12, 19 May 2011 (EEST)