wai*_*r92 0 c++ qt qml qtquick2
我正在尝试使用QtQuick与C++文件中的qml对象进行交互。但遗憾的是暂时没有成功。知道我做错了什么吗?我尝试了两种方法,第一种方法的结果是findChild()返回了nullptr,第二次尝试时我收到Qml 组件未准备好错误。什么是正确的方法呢?
主要的:
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();
}
主文件
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
    visible: true
    width: 640
    height: 480
        Page1 {
        }
        Page {
        }
    }
}
第1页.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
    }
}
findChild将对象名称作为第一个参数。但不是身份证。
http://doc.qt.io/qt-5/qobject.html#findChild。
在您的代码中,您正在尝试使用 id 进行查询 mrect。所以它可能不起作用。
添加 objectName您的 QML,然后尝试findChild使用对象名称进行访问。
类似于下面的东西(我没有尝试过。所以编译时错误的机会):
在 QML 中添加 objectName
Rectangle
{
    id: mrect
    objectName: "mRectangle"
    x: 10
    y: 20
    height: 10
    width: 10
}
然后你的 findChild 如下所示
QObject *mrect = object->findChild<QObject*>("mRectangle");