Skip to content

QtScript 102

Sunday, 7 January 2007  |  rich

I've done a bit of tidying up of the QtScript code I was working on, so here's another version. Now, as well as being able to create individual widgets, you can load UI files from Designer. I've also cleaned up the API for calling exec().

The new code looks like this:

void UiUtils::install( QScriptEngine *engine )
{
    installWidgets( engine );

    QScriptValue globalObject = engine->globalObject();
    QScriptValue utilsObject = engine->newObject();
    globalObject.setProperty( "UiUtils", utilsObject );

    QScriptValue fun = engine->scriptValue( UiUtils::load );
    utilsObject.setProperty("load", fun);
    fun = engine->scriptValue( UiUtils::exec );
    utilsObject.setProperty("exec", fun);
}

The installWidgets() call just calls the old implementation. What's new is that we're now creating an object call UiUtils that will have a couple of class methods load() and exec() available. The load method is implemented like this:

QScriptValue UiUtils::load(QScriptContext *context, QScriptEngine *engine)
{
    if ( context->argumentCount() != 1 ) {
	return context->throwError("Load takes one argument");
    }

    QUiLoader loader;
    QFile f( context->argument(0).toString() );
    f.open(QIODevice::ReadOnly);
    QWidget *w = loader.load( &f );

    return engine->scriptValueFromQObject( w );
}

This code for exec() is even simpler. The result is that we can now write Javascript code like this:

var ui = UiUtils.load( 'calc.ui' );
ui.show();
ui.clearButton.animateClick();

UiUtils.exec();

The UiUtils class itself should be reusable in real applications. The code is at http://xmelegance.org/devel/qscriptdemo2.tar.gz

It should be noted, that while it's nice that we can do these things with QtScript we can do them all with kjsembed too, and have been able to do so for years.