【问题标题】:Proper way to update QML object from C++?从 C++ 更新 QML 对象的正确方法?
【发布时间】:2020-06-24 01:06:07
【问题描述】:

我找到了这个How to modify a QML Text from C++,但我听说从 C++ 更新像这样的 QML 对象不是线程安全的

这样做的正确方法是什么?

我认为最简单的例子(文本小部件)足以让我理解。

【问题讨论】:

    标签: c++ qt qml qtquick2


    【解决方案1】:

    注意:我没有指出这段代码不是线程安全的,我已经指出你在your previous question 中的代码不是线程安全的,因为你修改了不同的 GUI线程比它所属的线程。

    我已经指出this answer的代码很危险,不推荐,因为QML元素的生命周期不是由开发者管理的,QML引擎可以在不通知我们的情况下消除它们,因此我建议创建QObject 在 C++ 和 QML 之间获取或发送信息。

    ma​​in.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"
    

    ma​​in.qml

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

    或

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 2021-09-14
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      相关资源
      最近更新 更多