Qt 记录update长时间频繁刷新后界面卡死问题

在项目中遇到了update频繁刷新场景, 一开始调用update可以正常刷新界面,在经过一段时间后界面卡死.

https://blog.csdn.net/windxgz/article/details/123812865 博客中找到了答案,不过没有写具体代码调用,为对新同学友好,简单写下.

这里遇到的情况是多线程情况下调用update,一开始正常,长时间调用后不刷新问题.

首先,update需要在GUI线程中调用如果想在非GUI线程中调用就需要使用信号槽, 需要在非GUI线程中发送信号, GUI线程中执行信号对应的槽.

例如此处有一个QDialog,需要频繁调用update 通过paintEvent重绘界面:

 

class Dialog : public QDialog
{
    Q_OBJECT
public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();
signals:
    void sigUpdate();
private:
    Ui::Dialog *ui;
protected:
    void paintEvent(QPaintEvent *event);
};

Dialog::Dialog(QWidget *parent)
 : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
connect(
this, &Dialog::sigUpdate, this, [this]() {
    //在GUI线程中执行update
this->
update(); }, Qt::QueuedConnection); QtConcurrent::run([this]() { while(true) {
       //非GUI线程调用 emit
this->sigUpdate(); QThread::msleep(100); } }); } Dialog::~Dialog() { delete ui; } void Dialog::paintEvent(QPaintEvent *event) { qDebug() << "paintEvent..."; }

此处注意关联信号时最后一个参数:Qt::QueuedConnection设置信号槽类型, 默认是: Qt::AutoConnection,可以看以下解释:

 

posted @ 2022-12-02 23:45  耿明岩  阅读(1781)  评论(0编辑  收藏  举报
希望能帮助到你,顺利解决问题! ...G(^_−)☆