子线程可以通过信号量与槽来传递数据给主线程,让主线程更新,下面是一个最简单的例子,界面中只有一个label,主线程中通过movetothread的方法创建了一个子线程,然后子线程中不断触发showNum信号让主线程调用DisplayMsg来更新label。
头文件:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void DisplayMsg(int i);
};
class test : public QObject
{
Q_OBJECT
public:
int var=0;
public slots:
void first();
signals:
void showNum(int);
};
cpp文件:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
test *test_w;
QThread *thread;
test_w = new test();
thread = new QThread;
connect(thread, SIGNAL(started()), test_w, SLOT(first()));//新建的线程开始后执行test::first()
connect(test_w, SIGNAL(showNum(int)), this, SLOT(DisplayMsg(int)));//子线程触发的信号传递了值进来
test_w->moveToThread (thread);
thread->start();//开始线程
ui->setupUi(this);
}
void test::first() {
for(int i=0;i<10;i++)
{
var++;
emit showNum(var);//触发信号
QThread::currentThread()->msleep(500);
}
}
void MainWindow::DisplayMsg(int i)
{
ui->label->setText(QString::number(i));//更新UI
}