Home > Backend Development > C++ > body text

How to Safely Update a Qt Main Window from a Secondary Thread?

DDD
Release: 2024-10-26 13:22:29
Original
830 people have browsed it

How to Safely Update a Qt Main Window from a Secondary Thread?

Qt - Updating Main Window from a Secondary Thread

Problem:

In a multithreaded Qt application, an attempt to update the main window's UI (mainwindow.ui) from a thread other than the main thread results in an error. Specifically, the following code fails:

mythread::run()
{
    QPixmap i1 (":/notes/pic/4mdodiyez.jpg");
    QLabel *label = new QLabel();
    label->setPixmap(i1);
    ana->ui->horizontalLayout_4->addWidget(label);
}
Copy after login

Solution:

Modifying the UI from a secondary thread is not directly possible in Qt due to thread safety concerns. The recommended approach is to move the UI modifications to a slot in the main window and connect a signal from the secondary thread to that slot.

Implementation:

Implement a worker class to handle the updates:

class GUIUpdater : public QObject
{
    Q_OBJECT

public:
    explicit GUIUpdater(QObject *parent = 0) : QObject(parent) {}
    void newLabel(const QString &image) { emit requestNewLabel(image); }

signals:
    void requestNewLabel(const QString &);
};
Copy after login

Create and move the GUIUpdater object to a secondary thread:

QThread *thread = new QThread(this);
GUIUpdater *updater = new GUIUpdater();
updater->moveToThread(thread);
Copy after login

Connect the updater's requestNewLabel signal to a slot that creates the label in the main window:

connect(updater, SIGNAL(requestNewLabel(QString)), this, SLOT(createLabel(QString)));
Copy after login

Invoke the newLabel method from the secondary thread to trigger the update:

updater->newLabel("h:/test.png");
Copy after login

In the main window's slot:

void createLabel(const QString &imgSource) {
    QPixmap i1(imgSource);
    QLabel *label = new QLabel(this);
    label->setPixmap(i1);
    layout->addWidget(label);
}
Copy after login

This solution allows for safe and efficient UI updates from secondary threads while maintaining Qt's thread safety guarantees.

The above is the detailed content of How to Safely Update a Qt Main Window from a Secondary Thread?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template