如何在 QML javascript 函数块中创建 C++ QObject?

How can a C++ QObject be created inside a QML javascript function block?

Similar to this question,我想实例化QObject的子class,但是我想在 javascript 功能块本身中执行此操作。

我有一个 class:

class CoverageKind : public QObject {
  Q_OBJECT    
public:

  int64_t        id;
  QString        coverage_kind;

  CoverageKind(QObject * parent=nullptr);

  Q_PROPERTY(int64_t id MEMBER id NOTIFY id_changed)
  Q_PROPERTY(QString coverage_kind MEMBER coverage_kind NOTIFY coverage_kind_changed)

signals:
  void id_changed();
  void coverage_kind_changed();
};

这是通过 QML 注册的,例如:

qmlRegisterType<CoverageKind>("com.example.CoverageKind", 0, 1, "CoverageKind");

导入 com.example.CoverageKind 后,我可以像这样实例化这个 QObject 子 class:

Item {
  CoverageKind {
    id: ck
    Component.onCompleted: {
      console.log('Created CoverageKind! ', ck);
    }
  }
}

打印:

Created CoverageKind!  CoverageKind(0x19b51b0)

但是,如果我这样做:

import com.example.CoverageKind 0.1;
Item {
  CoverageKind ck;
  Component.onCompleted: {
    ck = new CoverageKind();
  }
}

我在 ck = new ... 行得到 TypeError: Type error

我有一种惯用的方法可以从 QML javascript 块中实例化 C++ QObject subclass?

我能做到

var ck = Qt.createComponent("import com.example.CoverageKind 0.1; CoverageKind{}");

这感觉真的很笨拙。我也可以创建一个工厂函数,但我希望能够更符合人体工程学地在 javascript 中创建这些对象。

newQML 中不存在,最接近您想要的是创建类型 CoverageKind 的 属性,它最初为 null,并且在 Component.onCompleted you will be assigned the value created with Qt.createQmlObject().

import QtQuick 2.0
import com.example.CoverageKind 0.1;

Item {
    id: parentItem
    property CoverageKind ck: null
    Component.onCompleted: {
        ck = Qt.createQmlObject('import com.example.CoverageKind 0.1; CoverageKind{}',
                                parentItem,
                                "dynamicSnippet1");
    }
}

将您的项目变成一个组件

Component {
  id: myComponent
  CoverageKind {}
}

然后你可以在任何地方做:

var ckobj = myComponent.createObject (/*...*/)

现在ckobj是一个新实例