Skip to content

QtScript 103

Sunday, 7 January 2007  |  rich

Now we can create widgets and load .ui files, we can take the time to fix a few other things. Initially, we could create widgets, but we couldn't specify their parents. Handling this is quite a small change:

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

    QWidget *parent = 0;
    if ( context->argumentCount() ) {
	parent = qscript_cast<QWidget*>(context->argument(0));

	if ( !parent )
	    return context->throwError("The argument to load should be a QWidget");
    }

    QString self = context->callee().property( "functionName" ).toString();
    QUiLoader loader;
    QWidget *w = loader.createWidget( self, parent );
    return engine->scriptValueFromQObject( w );
}

The new code first checks that the arguments are ok and throws an exception to the script if they're not. If a parent has been passed, we convert it to a QWidget * using qscript_cast. Finally, we use the parent or 0 when we call createWidget().

To let you layout widgets created like this nicely, I've also added support for creating QHBox and QVBox widgets. This means that code like:

var xx = new QHBox();
var yy = new QTextEdit(xx);
var zz = new QPushButton(xx);
xx.show();
Will create a Q3HBox and layout the edit field and the button for us. The qscript_cast call is particularly useful as it gives us a clean way to convert the javascript value stored in the parameter into a C++ object.

The code for this version is available at http://xmelegance.org/devel/qscriptdemo3.tar.gz.