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); }
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 &); };
Create and move the GUIUpdater object to a secondary thread:
QThread *thread = new QThread(this); GUIUpdater *updater = new GUIUpdater(); updater->moveToThread(thread);
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)));
Invoke the newLabel method from the secondary thread to trigger the update:
updater->newLabel("h:/test.png");
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); }
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!