How to manage mainwindow from QThread in Qt

半城伤御伤魂 提交于 2020-01-16 14:33:41

问题


My problem is the following one: I have 2 classes (mainwindow and mythread), I run the thread from the mainwindow and I would like to display some QLabel of my mainwindow from mythread :

mythread.cpp :

void mythread::run()
{
   while(1)
   {
       this->read();
   }
}

void mythread::read()
{
    RF_Power_Control(&MonLecteur, TRUE, 0);
    status = ISO14443_3_A_PollCard(&MonLecteur, atq, sak, uid, &uid_len);
    if (status != 0){
        //display Qlabel in mainwindow
    }
}

mainwindow.cpp :

_thread = new mythread();
_thread->start();

回答1:


You should use Qt's signal/slot mechanism. The thread will emit a signal, that new data has been read. Any interested object can connect to that signal, and perform actions depending on it.

This also works across thread-boundaries, as in your example. In Qt, it is required that only the main-thread interacts with UI elements.

Here is an outline:

// Your mainwindow:
class MyWindow : public QMainWindow {
Q_OBJECT
   // as needed
private slots:
    void setLabel(const QString &t) { m_label->setText(t); }
};


// Your thread
class MyThread:  public QThread {
Q_OBJECT
  // as needed
signals:
  void statusUpdated(const QString &t);
};

// in your loop
if (status != 0) {
   emit statusUpdated("New Status!");
}

// in your mainwindow
_thread = new MyThread;
connect(_thread, &MyThread::statusUpdated, this, &MyWindow::setLabel);
_thread->start();


来源:https://stackoverflow.com/questions/56182455/how-to-manage-mainwindow-from-qthread-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!