我正在研究QtScript的可能性。我了解可以在C ++中创建QObject
,然后将其传递给QScriptEngine
:
QObject *someObject = new WindowWithText;
QScriptValue objectValue = engine.newQObject(someObject);
engine.globalObject().setProperty("window", objectValue);
这很有效 - 我能够调用我在C ++中定义的方法:
WindowWithText
声明:
#include <QWidget>
namespace Ui {
class WindowWithText;
}
class WindowWithText : public QWidget
{
Q_OBJECT
public:
explicit WindowWithText(QWidget *parent = 0);
~WindowWithText();
public slots:
void setHeading(const QString&);
void setContents(const QString&);
QString getHeading() const;
private:
Ui::WindowWithText *ui;
};
但是我想从qtscript本身实例化windows,就像这样:
var window = new WindowWithText();
我理解我可能要在构造函数和QtCcript之间编写一些代理,但是如何做呢?
到目前为止,我刚刚创建了创建对象的 static
方法newInstance
,但那不是new
:
QScriptValue WindowWithText::newInstance(QScriptContext *context, QScriptEngine *engine)
{
QObject *someObject = new WindowWithText;
QScriptValue objectValue = engine->newQObject(someObject);
return objectValue;
}
我按如下方式将其导出到引擎:
engine.globalObject().setProperty("WindowWithText", engine.newFunction(WindowWithText::newInstance));
这不使用new
但不是真正的javascript伪类:
以下代码将失败:
function Subclass() {
this.setHeading("bla bla");
}
Subclass.prototype = Object.create(WindowWithText.prototype);
var window = new dd();
window.show();
WindowWithText.prototype
与WindowWithText
没有任何关系导致的错误:
TypeError: Result of expression 'this.setHeading' [undefined] is not a function.
将C ++类导出到我的引擎是否有更可靠和不那么繁琐的方式?