2

我正在研究 QtScript 的可能性。我知道可以QObject在 C++ 中创建,然后将其传递给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 本身实例化窗口,如下所示:

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++ 类导出到我的引擎是否有更可靠且不那么繁琐的方法?

4

0 回答 0