2016-07-13 35 views
0

QTでC++でQMLを使用しようとしていますが、現在は失敗しています。 rootObjects()関数を使用してC++コードからQML要素にアクセスできません。私は間違って何をしていますか?QTのC++コードからのQML要素へのアクセス

QMLの一部:

import QtQuick 2.5 
import QtQuick.Controls 1.4 
import QtQuick.Dialogs 1.2 

ApplicationWindow { 
    id: window 
    visible: true 
    width: 640 
    height: 520 
    title: qsTr("My app") 

    Item { 
     anchors.fill: parent 
     Rectangle { 
      id: rectangle1 
      x: 0 
      y: 0 
      width: 640 
      height: 370 
      color: "#ffffff" 
      } 


     Button { 
      id: startButton 
      x: 325 
      y: 425 
      text: qsTr("Start") 
     } 
    } 
} 

C++パート:

int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 

    QQmlApplicationEngine engine; 
    engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); 

    QObject *rootObject = engine.rootObjects().first(); 
    qDebug() << rootObject->objectName();//prints "" 


    QObject *qmlObject = rootObject->findChild<QObject*>("window");// or "startButton" 
    //qDebug() << qmlObject->objectName(); //app fails, because window was not found 


    QList<QObject *> allQObjects = rootObject->findChildren<QObject *>(); 
    for(int i=0;i< allQObjects.length();++i) 
    { 
     qDebug() << allQObjects[i]->objectName(); //prints everytime "" 
    } 
    qDebug() << "len: " << allPQObjects.length(); //prints 132 


    return app.exec(); 
} 

答えて

0

最初はQML

ApplicationWindow { 
    id: window 
    objectName: "window" 
    ... 
} 
1

にObjectNameのを追加する必要があります。あなたがオブジェクト名を設定しない場合がありますいいえ!

QML:

Rectangle { id : frame; objectName : "objFrame" color : "blue" } 

のQt:

QObject *pRootObject = m_pQmlView->rootObject(); 
QObject *pobjFrame = m_pRootObject->findChild<QObject *>("objFrame"); 

arroundの他の方法:

のQt: m_pQmlView-> rootContext() - > setContextProperty( "_VIEW"、この) ;

QML:

Component.onCompleted: { 

    /********************** Connections ***************************/ 

    // connect signal MyView::retranslate() with slot retranslate   
    _view.retranslate.connect(retranslate) 
} 
関連する問題