Solved How to control MainWindow widget from Thread ?
-
Hi All,
I create a MainWindow , a button and a listWidget on my mainwindow.cpp by:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) void MainWindow::on_pushButton_2_clicked() { ui->listWidget_2->addItem("abc"); }
Then I create a thread by Qthread as below:
class T3Thread : public QThread { Q_OBJECT private: void run() { //ui->listWidget_2->addItem("567"); for (int i = 0; i <= 100; i++) { delay(20); } } };
I want to show some information to my listWiget_2, however listWidget_2 not belong to "T3Thread",
so compiler will fail if I add "ui->listWidget_2->addItem("567");".I understand this issue is cause by ui not declared in T3Thread, but I do not now how to fix it.
Any suggestion will be very appreciate.
Thanks,
-
- Create a signal in the thread like
Q_SIGNAL void addItemToList(const QString&);
- Create a slot in
MainWindow
likevoid addItemToList(const QString& val){ui->listWidget_2->addItem(val);}
- connect them
connect(t3thread,&T3Thread::addItemToList,this,&MainWindow::addItemToList,Qt::QueuedConnection);
- emit the signal from the thread when you want to add an item
emit addItemToList("567");
P.S.
Almost mandatory reading: https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ - Create a signal in the thread like
-
This post is deleted! -
@VRonin
Thanks for your help. I should spend some time to try your suggestion and study the link in more detail.