Search code examples
c++qt4qtscript

Add class to QScriptEngine


Here is an example of how I add instances of a class to my QScriptEngine:

void Window::runCurrentScript(QRect rect)
{
    Rectangle *script_mouse = new Rectangle(rect.normalized());

    QScriptEngine engine;

    QScriptValue o2 = engine.newQObject(script_mouse);
    engine.globalObject().setProperty("mouse", o2);

    p_current_script = editor->toPlainText();

    // Run the currently selected script...
    QScriptValue result = engine.evaluate(p_current_script);

    canvas->repaint();
}

All of this works fine but I would like to be able to create new Rectangles in my scripts like so:

var rect = new Rectangle();

How do I do that?


Solution

  • static QScriptValue Window::RectangleConstructor(QScriptContext *context, QScriptEngine *engine)
    {
        QObject *parent = context->argument(0).toQObject();
    
        Rectangle *rectangle;
        switch(context->argumentCount())
        {
            case 2:
                rectangle = new Rectangle(context->argument(0).toInteger(), context->argument(1).toInteger());
            break;
    
            case 4:
                rectangle = new Rectangle(context->argument(0).toInteger(), context->argument(1).toInteger(),
                                        context->argument(2).toInteger(), context->argument(3).toInteger());
            break;
    
            default:
                rectangle = new Rectangle(parent);
            break;
        }
    
        return engine->newQObject(rectangle, QScriptEngine::ScriptOwnership);
    }
    
    
    
    void Window::runCurrentScript(QRect rect)
    {
        Rectangle *script_mouse = new Rectangle(rect.normalized());
    
        QScriptEngine engine;
    
        QScriptValue o2 = engine.newQObject(script_mouse);
        engine.globalObject().setProperty("mouse", o2);
    
        QScriptValue rectConstructor = p_engine->newFunction(RectangleConstructor);
        QScriptValue rectMetaObject = p_engine->newQMetaObject(&Rectangle::staticMetaObject, rectConstructor);
        engine.globalObject().setProperty("Rect", rectMetaObject);
    
        p_current_script = editor->toPlainText();
    
        // Run the currently selected script...
        QScriptValue result = engine.evaluate(p_current_script);
    
        canvas->repaint();
    }