QML C++ 混合編程 Qml元素實時獲取c++ 屬性

1 定義C++ 類  

class QMyModel : public QAbstractListModel
{
    Q_OBJECT

   注意事項: GetCurrentIndex 兩個地方要完全相同 

   NOTIFY CurrentIndexChanged  保證了當 數值變化時第一時間響應

    Q_PROPERTY(int GetCurrentIndex READ GetCurrentIndex WRITE SetCurrentIndex  NOTIFY CurrentIndexChanged)


     int GetCurrentIndex(){return currentIndex;}
    void SetCurrentIndex(const int curIndex) {currentIndex = curIndex; emit CurrentIndexChanged();}

signals:

   這裏只有信號定義沒有槽定義
    void CurrentIndexChanged();

private:

    int currentIndex;

}

2 main.qml 文件

PathView {
        id: pathView;
        anchors.fill: parent

               這裏屬性的賦值要和上面的方法保持一直

        currentIndex: MyModel.GetCurrentIndex;

 

}

3 主程序入口


int main(int argc, char *argv[])
{
    QMyModel model;
    gMyModel = &model;

    QGuiApplication app(argc, argv);

    QtQuick2ApplicationViewer viewer;
    QQmlContext *ctxt = viewer.rootContext();

    這裏 MyModel 就是在 QML 文件中用的名稱
    ctxt->setContextProperty("
MyModel", &model);

    viewer.setMainQmlFile(QStringLiteral("main.qml"));
    viewer.showExpanded();

    return app.exec();
}
 


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章