如何从C ++设置QML属性

hek*_*kri 3 c++ qml qt5.4

我正在尝试做一个简单的任务,例如从C ++更改某些QML对象的属性(文本:),但我失败了。任何帮助表示赞赏。

我没有收到任何错误,出现了窗口,只是text属性没有(至少我认为)应有的变化。我在这里没做错什么吗?!

我正在尝试的是这样的:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQuickItem>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QString>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;


    QQmlComponent component(&engine, QUrl::fromLocalFile("main.qml"));
    QObject *object = component.create();

     engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    QString thisString = "Dr. Perry Cox";

    object->setProperty("text", thisString);  //<--- tried  instead of thisString putting "Dr. ..." but nope.
    delete object;



    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)

main.qml

import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    visible: true
    width: 360
    height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }

    Text {
        id: whot
        text: ""
        anchors.centerIn: parent
        font.pixelSize: 20
        color: "green"
    }
}
Run Code Online (Sandbox Code Playgroud)

Inn*_*der 5

调用时,QObject *object = component.create();您可以访问根上下文,即Window组件及其属性。

要访问Text属性,可以创建属性别名,如下所示:

Window {
    property alias text: whot.text
    ...
    Text {
        id: whot
        text: ""
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这样一来,您就可以在的上下文中访问whottext属性Window

还有另一种绕回的方式。将objectName属性分配给,而不是id(或者如果仍然需要id)分配给whot

Text {
    id: whot // <--- optional
    objectName: "whot" // <--- required
    text: ""
    ...
 }
Run Code Online (Sandbox Code Playgroud)

现在,您可以在代码中执行此操作:

QObject *whot = object->findChild<QObject*>("whot");
if (whot)
    whot->setProperty("text", thisString);
Run Code Online (Sandbox Code Playgroud)

附带说明:我不认为您应该object在致电之后删除app.exec()。否则,它将...被删除。:)