Skip to content

QtScript 101

Saturday, 6 January 2007  |  Rich

As you might have read in Kent's blog post yesterday, the latest Qt 4.3 snapshots just gained a javascript interpreter. I had a bit of a play with it yesterday and it's pretty neat. Unfortunately it doesn't expose any fun objects by default, so I decided to make it possible to create QWidgets.

The result is a tiny demo that gives you the ability to create instances of any QWidget that Designer supports. The glue code itself is tiny:

void UiUtils::installWidgets( QScriptEngine *engine )
{
    QScriptValue globalObject = engine->globalObject();
    QUiLoader loader;

    QStringList widgets = loader.availableWidgets();
    for ( int i=0; i < widgets.size(); ++i ) {
	QScriptValue fun = engine->scriptValue( createWidget );
	fun.setProperty( QString("functionName"), engine->scriptValue(widgets[i]) );

	globalObject.setProperty(widgets[i], fun);
    }
}

QScriptValue UiUtils::createWidget(QScriptContext *context, QScriptEngine *engine)
{
    QString self = context->callee().property( "functionName" ).toString();
    QUiLoader loader;
    QWidget *w = loader.createWidget( self );
    return engine->scriptValueFromQObject( w );
}

And now you can use the qscriptdemo command prompt to run code like this:

var x= new QTextEdit();
x.show();
testobj.exec(); // This just provides access to app.exec()

Neat eh?

Edit: Here's a link to the code http://xmelegance.org/devel/qscriptdemo.tar.gz.