和其他語言類似,不能直接在子線程更新UI,可以通過signal-slot機制在UI線程進行更新。
Signal-slot機制可以在不同對象,不同線程之間進行通訊。
例子:
<pre name="code" class="cpp">//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
</pre><pre name="code" class="cpp">
</pre><pre name="code" class="cpp">
</pre><pre name="code" class="cpp">//mythread.h
#include <QThread>
#include <QTextEdit>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
virtual void run();
signals:
void dataChanged(QString);
public slots:
};
//mythread.cpp
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
}
void MyThread::run()
{
long long int i;
for(i = 10000000000; i > 0; i--)
{
qDebug() << "now i is: " << i;
QThread::msleep(100);
/*can not operate the GUI directly from another thread, I guess signal-slot mechanism should be used.
//this->tEdit->setText("test");
*/
QString str = QString::number(i);
emit dataChanged("now i is: " + str);
}
}
//mainwindow.h
//#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "mythread.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
MyThread *t;
private slots:
void longRunningTask();
void testButtonClicked();
};
#endif // MAINWINDOW_H
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "mythread.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
t = new MyThread();
connect(ui->pushButton,SIGNAL(clicked()),this, SLOT(longRunningTask()));
connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(testButtonClicked()));
connect(t, SIGNAL(dataChanged(QString)), ui->textEdit, SLOT(append(QString)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::longRunningTask()
{
t->start();
}
void MainWindow::testButtonClicked()
{
int i;
for(i = 100; i > 0; i--)
{
qDebug() << "test button clicked for: " << i << "times";
}
ui->textEdit->setText("test button clicked");
}