• Qt如何保证控件调用时候的线程安全


    m_title->setText("Data"); 
    m_threadCaculate = std::thread(&MeasurementData::getPointLaserMeasureData, this); 
    
    线程getPointLaserMeasureData中执行m_title->setText("1");
    
    • 1
    • 2
    • 3
    • 4

    会有什么后果?

    多线程环境中直接调用 Qt 组件的方法(如 setText())是不安全的,因为 Qt 大部分的类和方法都不是线程安全的。在你的情况下,m_title->setText("1") 在一个新的线程中被调用,这可能会导致程序崩溃或产生未定义的行为。

    Qt 提供了一种方式来确保在正确的线程上执行 Qt 对象的方法,即使用信号槽机制。你可以在新线程中发出信号,然后将这个信号连接到主线程中的槽函数,这样就能在主线程中更新 Qt 组件。以下是一个示例:

    #include 
    #include 
    #include 
    
    class MeasurementData : public QObject {
        Q_OBJECT
    public:
        MeasurementData(QLabel* title) : m_title(title) {}
    
    public slots:
        void updateTitle(const QString& text) {
            m_title->setText(text);
        }
    
        void getPointLaserMeasureData() {
            // 执行获取数据的操作...
            emit newDataReceived("1"); // 发送信号
        }
    
    signals:
        void newDataReceived(const QString& data);
    
    private:
        QLabel* m_title;
    };
    
    int main() {
        QLabel title("Data");
        MeasurementData data(&title);
    
        QThread thread;
        data.moveToThread(&thread);
    
        QObject::connect(&data, &MeasurementData::newDataReceived, &data, &MeasurementData::updateTitle);
        QObject::connect(&thread, &QThread::started, &data, &MeasurementData::getPointLaserMeasureData);
    
        thread.start();
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    在这个示例中,MeasurementData 类继承自 QObject,它包含一个槽函数 updateTitle(),用于更新标题文本。在 getPointLaserMeasureData() 中,当获取到新数据时,它会发出 newDataReceived 信号。在 main() 函数中,我们将 data 对象移动到新的线程中,并将信号 newDataReceived 连接到槽函数 updateTitle(),这样就确保了在主线程中更新 Qt 组件的安全性。

  • 相关阅读:
    js的cookie设置
    Node.js环境搭建
    如何在 .NET Core WebApi 中处理 MultipartFormDataContent
    查看Mysql数据库版本
    EE5811-Computer vision-Filter and resample
    shell脚本
    图像主题颜色提取(Median cut)
    SNMP信息收集与利用
    ASP.NET电子购物商城系统(源代码+论文+开题报告+答辩PPT)
    API自动化(四)
  • 原文地址:https://blog.csdn.net/qq_39054069/article/details/136674786