如何在QML javascript功能块内创建C ++ QObject?

时间:2018-10-25 22:50:28

标签: qt qml qobject

Similar to this question,我想实例化QObject的子类, 但是 ,我想在javascript功能块本身中做到这一点。

我有一堂课

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子类:

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();
  }
}

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

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

我可以做到

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

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

2 个答案:

答案 0 :(得分:1)

newQML中不存在,与您想要的最接近的事情是创建类型为CoverageKind的属性,该属性最初为空,在Component.onCompleted中,您将被赋予使用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");
    }
}

答案 1 :(得分:1)

将您的物品放入组件

Component {
  id: myComponent
  CoverageKind {}
}

然后您可以在任何地方做

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

现在ckobj是一个新实例