从QT中的C ++代码访问QML元素

时间:2016-07-13 07:24:05

标签: c++ qt qml

我试图在QT中使用QML和C ++,但是现在还没有成功。我无法使用rootObjects()函数从C ++代码访问我的QML元素。我做错了什么?

qml part:

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 ++ Part:

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();
}

2 个答案:

答案 0 :(得分:1)

首先:如果你没有设置一个对象名,就没有了!

QML:

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

Qt:

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

另一种方式:

Qt的:        m_pQmlView-&gt; rootContext() - &gt; setContextProperty(“_ view”,this);

QML:

 Component.onCompleted: {

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

    // connect signal MyView::retranslate() with slot retranslate        
     _view.retranslate.connect(retranslate)
}

答案 1 :(得分:0)

需要将对象名称添加到QML

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