简体   繁体   English

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

[英]Interaction with qml objects from C++ code

I am trying to interact with an qml object from C++ file using QtQuick . 我正在尝试使用QtQuickC ++文件中的qml对象进行交互。 But unfortunatelly unsuccessfully for now. 但不幸的是目前还没有成功。 Any idea what Im doing wrong? 知道我在做什么错吗? I tried 2 ways how to do it, result of the first was that findChild() returned nullptr , and in second try I am getting Qml comnponent is not ready error. 我尝试了两种方法,第一种方法是findChild()返回nullptr ,第二种方法是获得Qml组件未准备好错误。 What is the proper way to do it? 正确的做法是什么?

main: 主要:

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 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: Page1.qml:

import QtQuick 2.7

Page1Form {
...
}

Page1.Form.ui.qml 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 takes object name as first parameter. findChild将对象名称作为第一个参数。 But not ID. 但不是ID。

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

Here in your code, you are trying to query with id mrect . 在您的代码中,您尝试使用id mrect查询。 So it may not work. 因此它可能无法正常工作。

Add objectName in your QML and then try accessing with findChild using object name. 在您的QML中添加objectName ,然后尝试使用对象名称通过findChild访问。

Something like below (I did not try it. So chances of compile time errors): 如下所示(我没有尝试过。所以编译时错误的可能性):

Add objectName in QML 在QML中添加objectName

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

And then your findChild as shown below 然后您的findChild如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM