How to create new instance of a Q_GADGET struct in QML?

北战南征 提交于 2019-12-05 16:04:06

You don't create Q_GADGETs in QML, QML objects need to be QObject derived, and are not created via new - that's for JS objects only. Gadgets just generate meta data so that you can access their members and such from QML and pass around, that's about it.

Is it possible send such a struct from QML to a C++ slot?

It is possible to send, but it would not be created in QML. It could be returned to QML from a C++ function or be exposed as a property of some object.

struct Test {
    Q_GADGET
    Q_PROPERTY(int test MEMBER test)
  public:
    Test() : test(qrand()) {}
    int test;
    Q_SLOT void foo() { qDebug() << "foo"; }
};

class F : public QObject { // factory exposed as context property F
    Q_OBJECT
  public slots:
    Test create() { return Test(); }
    void use(Test t) { qDebug() << t.test; }
};


    // from QML
    property var tt: F.create()

    Component.onCompleted: {
      F.use(F.create()) // works
      var t = F.create()
      console.log(t.test) // works
      F.use(t) // works
      console.log(tt.test) // works
      F.use(tt) // works
      tt.test = 555
      F.use(tt) // works
      t.test = 666
      F.use(t) // works
      t.foo() // works
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!