Important: Please read the Qt Code of Conduct -

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()

    Then I create a thread by Qthread as below:

    class T3Thread : public QThread
        void run()
             for (int i = 0; i <= 100; i++)

    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.


    • Create a signal in the thread like Q_SIGNAL void addItemToList(const QString&);
    • Create a slot in MainWindow like void 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");

    Almost mandatory reading:

  • 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.

Log in to reply