How to create and use C++ objects in QML Javascript

前端 未结 4 581
北海茫月
北海茫月 2021-02-05 21:43

My app uses both c++ and QML.

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

It looks like:



        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 22:12

    The documentation is pretty clear but the confusion looks like it is on the QML side of the equation. This should get you started:

    //C++
    class MyObject : public QObject
    {
        Q_OBJECT
    public:
        MyObject(QObject *parent = 0);
        Q_INVOKABLE void someFunction(const QString &query) { qDebug() << query;}
    };
    ....
    qmlRegisterType("foo.bar", 1, 0, "MyObject");
    

    The QML is below:

    import foo.bar 1.0 //This is your register type
    Item {
      MyObject { //here's the instance, remember it is declarative
        id: myObject;
      }
      MyObject {
        id: myObjectInstance2
      }
      Button {
        onClicked: {
          myObject.someFunction("doSomething"); //here is using a reference
          myObjectInstance2.someFunction("doSomethingElse");
        }
      }
    }
    

    On clicking you should see the strings in the output (I didn't compile or test this). Be sure to register the type in your main class.

    You should check out the local storage object if you're using SQL on a mobile device. It is a pretty simple callback API that works with SQLite. I use it for desktop applications and don't have much trouble. Returning lists is a little annoying so just try to stick to simple types for easy JavaScript integration.

    I hope that helps. I absolutely love working in QML, it is quite fun once you learn it (1-2 weeks to be proficient enough to work).

提交回复
热议问题