简体   繁体   English

从 C++ 更新 QML 对象的正确方法?

[英]Proper way to update QML object from C++?

I've found this How to modify a QML Text from C++ but I've hear that it's not thread-safe to update QML objects lik this from C++我发现了这个How to modify a QML Text from C++但我听说从 C++更新这样的 QML 对象不是线程安全的

What is the proper way of doing so?这样做的正确方法是什么?

I think the simplest example (a text widget) is enough for me to understand.我认为最简单的例子(一个文本小部件)足以让我理解。

Note: I have not pointed out that this code is not thread-safe, I have pointed out that your code in your previous question is not thread-safe since you modify the GUI from a different thread than the one it belongs to.注意:我没有指出此代码不是线程安全的,我已经指出您在上一个问题中的代码不是线程安全的,因为您从与其所属线程不同的线程修改 GUI。

I have pointed out that the code of this answer is dangerous and not recommended because the life cycle of the QML elements are not managed by the developer and the QML engine could eliminate them without notifying us, therefore I recommend creating QObject to obtain or send information between C++ and QML.我已经指出这个答案的代码是危险的,不推荐,因为 QML 元素的生命周期不是由开发人员管理的,QML 引擎可以在不通知我们的情况下消除它们,因此我建议创建 QObject来获取或发送信息在 C++ 和 QML 之间。

main.cpp主程序

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

class Helper: public QObject{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
    QString m_text;
public:
    using QObject::QObject;
    QString text() const{
        return m_text;
    }
public slots:
    void setText(QString text){
        if (m_text == text)
            return;
        m_text = text;
        emit textChanged(m_text);
    }
signals:
    void textChanged(QString text);
};

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    Helper helper;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("helper", &helper);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    helper.setText("Change you text here...");

    return app.exec();
}
#include "main.moc"

main.qml主文件

Text {
    id: text1
    color: "red"
    text: helper.text
    font.pixelSize: 12
}

or或者

Text {
    id: text1
    color: "red"
    text: "This text should change..."
    font.pixelSize: 12
}
Connections{ target: helper onTextChanged: text1.text = text }

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

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