6

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

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

我正在尝试的是:

主文件

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

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

3 回答 3

6

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

要访问Text属性,您可以像这样创建属性别名:

Window {
    property alias text: whot.text
    ...
    Text {
        id: whot
        text: ""
        ...
    }
}

这将使您可以从' 上下文中访问whot'属性。textWindow

还有另一种稍微迂回的方式。将objectName属性分配ididwhot

Text {
    id: whot // <--- optional
    objectName: "whot" // <--- required
    text: ""
    ...
 }

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

QObject *whot = object->findChild<QObject*>("whot");
if (whot)
    whot->setProperty("text", thisString);

附带说明:我认为您不应该object在调用app.exec(). 否则,它将......好吧,被删除。:)

于 2014-12-20T22:33:58.000 回答
0
#include <QQmlContext>
#include <qquickview.h>
#include <qdir.h>

QQmlApplicationEngine engine;
QString root = QCoreApplication::applicationDirPath();
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
        return -1;
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow*>(topLevel);
window->setProperty("root", root);

对于 qml

ApplicationWindow  {
    property string root
    onRootChanged: {
        console.log("root : "+ root);
    }
}
于 2018-09-25T12:16:20.320 回答
0

对于 QML 属性,您应该改用QQmlProperty

QQmlProperty::write(whot, "text", thisString);
于 2021-03-31T14:48:25.380 回答