0

这是我如何将类的实例添加到 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();
}

所有这一切都很好,但我希望能够在我的脚本中创建新的矩形,如下所示:

var rect = new Rectangle();

我怎么做?

4

1 回答 1

0
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();
}
于 2013-04-21T20:37:17.563 回答