2017-10-06 93 views
0

我試圖使用QtQuickC++文件與QML對象進行交互QML對象。但現在不幸地失敗了。任何想法我做錯了什麼?我試過2種方法怎麼辦呢,結果第一個是findChild()返回nullptr,並在第二次嘗試我得到Qml comnponent沒有準備好錯誤。什麼是正確的方法來做到這一點?互動與C++代碼

主:

int main(int argc, char *argv[]) 
{ 
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); 
    QGuiApplication app(argc, argv); 

    QQmlApplicationEngine engine; 
    engine.load(QUrl(QLatin1String("qrc:/main.qml"))); 
    if (engine.rootObjects().isEmpty()) 
     return -1; 
    // 1-st attempt how to do it - Nothing Found 
    QObject *object = engine.rootObjects()[0]; 
    QObject *mrect = object->findChild<QObject*>("mrect"); 
    if (mrect) 
     qDebug("found"); 
    else 
     qDebug("Nothing found"); 
    //2-nd attempt - QQmlComponent: Component is not ready 
    QQmlComponent component(&engine, "Page1Form.ui.qml"); 
    QObject *object2 = component.create(); 
    qDebug() << "Property value:" << QQmlProperty::read(object, "mwidth").toInt(); 

    return app.exec(); 
} 

main.qml

import QtQuick 2.7 
import QtQuick.Controls 2.0 
import QtQuick.Layouts 1.3 

ApplicationWindow { 
    visible: true 
    width: 640 
    height: 480 

     Page1 { 
     } 

     Page { 
     } 
    } 
} 

Page1.qml:

import QtQuick 2.7 

Page1Form { 
... 
} 

Page1.Form.ui.qml

import QtQuick.Controls 2.0 
import QtQuick.Layouts 1.3 

Item { 
    property alias mrect: mrect 
    property alias mwidth: mrect.width 

    Rectangle 
    { 
     id: mrect 
     x: 10 
     y: 20 
     height: 10 
     width: 10 
    } 
} 

回答

2

findChild將對象名稱作爲第一個參數。但不是ID。

http://doc.qt.io/qt-5/qobject.html#findChild

在您的代碼中,您嘗試使用ID mrect進行查詢。所以它可能無法正常工作。

在您的QML中添加objectName,然後嘗試使用對象名稱與findChild進行訪問。

類似下面(我沒有嘗試,所以編譯時錯誤的機會。):

添加對象名在QML

Rectangle 
{ 
    id: mrect 
    objectName: "mRectangle" 
    x: 10 
    y: 20 
    height: 10 
    width: 10 
} 

然後你findChild如下圖所示

QObject *mrect = object->findChild<QObject*>("mRectangle");