【问题标题】:Interaction with qml objects from C++ code与 C++ 代码中的 qml 对象交互
【发布时间】:2017-10-07 04:29:17
【问题描述】:

我正在尝试使用 QtQuickC++ 文件中的 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();
}

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
    }
}

【问题讨论】:

    标签: c++ qt qml qtquick2


    【解决方案1】:

    findChild 将对象名称作为第一个参数。但不是身份证。

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

    在您的代码中,您尝试使用 id mrect 进行查询。所以它可能不起作用。

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

    类似下面的东西(我没有尝试过。所以编译时错误的机会):

    在 QML 中添加 objectName

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

    然后你的 findChild 如下图所示

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

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多