1. 程式人生 > >QML與C++交換資料

QML與C++交換資料

C++呼叫QML方法

QML和C++物件之間可以通過訊號、槽、屬性修改等機制進行通訊。對於一個C++物件,任何一個暴露在Qt的元物件系統中的資料–屬性–訊號–槽和使用Q_INVOKEABLE標記的方法都可以在QML中訪問。在QML端,所有QML物件的資料都可以在Qt元物件系統和C++中訪問。

//MyItem.qml
import QtQuick 1.0
Item {
    function myQmlFunction(msg){
        console.log("Got message:",msg)
        return "some return value"
    }
}

對應的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));

QML呼叫C++中類物件

//MyItem.qml
import QtQuick 1.0
Item {
    width:100;
    height:100;
    MouseArea{
        anchor.fill:parent
        onClicked:{
            myObject.cppMethod("hello from QML");
            myObject.cppSlot(12345)
        }
    }
}

對應的cpp

class MyClass: public Object{
    Q_OBJECT
    public:
    Q_INVOKABLE void
cppMethod(const QString &msg){ qDenug()<<"Called c++ method with"<<msg; } public slots: void sppSlot(int number){ qDebug()<<"Called with C++ slot with"<<number; } }; int main(int argc,char *argv[]){ QApplication app(argc,argv); MyClass myClass; view.rootContext()->setContextProperty("myObject",&myClass); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); }

//可以將物件轉換成實際型別,這樣做的好處是可以在呼叫函式的時候獲得編譯器檢查。

import QtQuick 2.2
Item{
    width:100;height:200;
}

//在main.cpp中

int main(int argc,char *argc[]){
    QGuiApplication app(argc,argv);
    QQmlEngine engine;
    QQmlComponent component(&engine,QUrl(QStringLiteral("qrc:///main.qml")));
    QObject *object=component.create();
    ...
    ...
}

如下方式,可以將物件轉換成實際型別,這樣做的好處是可以在呼叫函式的時候獲得編譯器檢查。
普通寫法:
object->setProperty(‘width’,500);
QQmlProperty(object,’width’).write(500);

//QQuickItem *item=qobject_cast

QGCQmlWidgetHolder::setContextPropertyObject(const QString &name,QObject * object){
_ui.qmlWidget->rootContext()->setContextProperty(name,object);

}