如何从Qt中的QThread管理主窗口 [英] How to manage mainwindow from QThread in Qt

查看:106
本文介绍了如何从Qt中的QThread管理主窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是以下问题:我有2个类(mainwindow和mythread),我从mainwindow运行线程,我想从mythread显示我的mainwindow的QLabel:

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:

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:

mainwindow.cpp :

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

推荐答案

您应使用 Qt的信号/插槽机制.该线程将发出一个信号,表明已读取新数据.任何感兴趣的对象都可以连接到该信号,并根据该信号执行操作.

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.

这也适用于线程边界,如您的示例所示.在Qt中,要求只有主线程才能与UI元素进行交互.

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

这是一个大纲:

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

这篇关于如何从Qt中的QThread管理主窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆