以下是我如何向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();
我该怎么做?
答案 0 :(得分: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();
}