与C++代码中的 qml 对象交互

Interaction with qml objects from C++ code

本文关键字:qml 对象 交互 C++ 代码      更新时间:2023-10-16

我正在尝试使用QtQuick与文件中C++qml对象进行交互。但不幸的是,目前没有成功。知道我做错了什么吗?我尝试了 2 种方法,第一次的结果是 findChild() 返回 nullptr,在第二次尝试中我得到 Qml comnponent 未准备好错误。正确的方法是什么?

主要:

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

主.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
    visible: true
    width: 640
    height: 480
        Page1 {
        }
        Page {
        }
    }
}

第 1 页:

import QtQuick 2.7
Page1Form {
...
}

第1页.表单.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 进行查询。所以它可能不起作用。

在 QML 中添加objectName,然后尝试使用对象名称进行findChild访问。

如下所示(我没有尝试过。所以编译时出错的可能性):

在 QML 中添加对象名称

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

然后你的查找子,如下所示

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