2017-10-06 117 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");