1. 程式人生 > >QML 與C++函式互相呼叫

QML 與C++函式互相呼叫

QML函式可在C++中呼叫,反之亦然.

所有的QML函式都被暴漏在了元資料系統中,並可通過QMetaObject::invokeMethod()呼叫.C++應用程式呼叫QML函式:

// MyItem.qml
 import QtQuick 1.0

 Item {
     function myQmlFunction(msg) {
         console.log("Got message:", msg)
         return "some return value"
     }
 }



 // main.cpp  
 QDeclarativeEngine engine;  
 QDeclarativeComponent component(&engine, "MyItem.qml"
); QObject *object = component.create(); QVariant returnedValue; QVariant msg = "Hello from C++"; QMetaObject::invokeMethod(object, "myQmlFunction", Q_RETURN_ARG(QVariant, returnedValue), Q_ARG(QVariant, msg)); qDebug() << "QML function returned:" << returnedValue.toString();

注意QMetaObject::invokeMethod()中Q_RETURN_ARG() 和Q_ARG()的引數必須指定為QVariant型別,這是QML函式和返回值的通用資料型別.

在QML中呼叫C++函式,函式必須是Qt的槽或標記了Q_INVOKABLE巨集的函式,才能在QML中訪問.下面範例中,QML程式碼呼叫了(使用QDeclarativeContext::setContextProperty()設定到QML中的)myObject物件的方法:

 // MyItem.qml
 import QtQuick 1.0

 Item {
     width: 100; height: 100

     MouseArea {
         anchors.fill: parent
         onClicked: {
             myObject.cppMethod("Hello from QML"
) myObject.cppSlot(12345) } } } //main.cpp class MyClass : public QObject { Q_OBJECT public: Q_INVOKABLE void cppMethod(const QString &msg) { qDebug() << "Called the C++ method with" << msg; } public slots: void cppSlot(int number) { qDebug() << "Called the C++ slot with" << number; } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; MyClass myClass; view.rootContext()->setContextProperty("myObject", &myClass); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); }

QML支援呼叫C++的過載函式.如果C++中有多個同名不同參的函式,將根據引數數量和型別呼叫正確的函式