如何在 QML Javascript 中创建和使用 C++ 对象

2022-01-19 00:00:00 qt5 qtquick2 qml qt-quick javascript

我的应用同时使用 c++ 和 QML.

My app uses both c++ and QML.

我在 C++ 部分定义了几个对象来访问 SQL 等.

I've defined several objects in C++ part to access SQL etc.

看起来像:

class MyObject : public QObject
{
    Q_OBJECT
public:
    MyObject(QObject *parent = 0);
    Q_INVOKABLE void someFunction(const QString &query);
};

qmlRegisterType<MyObject>("xxx.xxx", 1, 0, "MyObject");

理想情况下,我只需要在 Javascript 而不是 QML 中使用这些对象.

Ideally, I need to use these objects only in Javascript not in QML.

我尝试了很多示例并阅读了所有文档,但仍然无法解决我的问题.

I tried a lot of examples and read all the documentation but still can't solve my problem.

所以我的问题:

  • 如何在 Javascript 中实例化在 C++ 中定义的对象?我试过 var obj = Qt.createComponent("MyObject"); 但它似乎不起作用.是否可以以普通 JS 样式定义新对象 - var obj = new MyObject;?
  • 如何在 javascript 中访问这个创建的对象?我尝试了 obj.someFunction("xxx") 但出现了一些错误 - TypeError: Property 'someFunction' of object QQmlComponent(0x3605f5c0) is not a function. 我在这里做错了什么?我的对象派生自 QObject,而不是 QQmlComponent.
  • How can I instance in Javascript an object defined in C++? I tried var obj = Qt.createComponent("MyObject"); but it seems not works. Is it possible to define new object in normal JS style - var obj = new MyObject;?
  • How can I access this created object in javascript? I tried obj.someFunction("xxx") but got some error - TypeError: Property 'someFunction' of object QQmlComponent(0x3605f5c0) is not a function. What I do wrong here? My object derived from QObject, not from QQmlComponent.

推荐答案

你的对象不是Component,但是你可以使用Qt.createQmlObject 代替.

Your object isn't a Component, but you can use Qt.createQmlObject instead.

相关文章