首页 > 代码库 > Qt: 多线程, 就是这么简单(确实非常简洁明了)

Qt: 多线程, 就是这么简单(确实非常简洁明了)

#include <iostream>
#include <QApplication>
#include <QThread>
#include <QString>

class Thread : public QThread {
public:
Thread(QString name = "") {
stopped = false;
this->name = name;
}

void run() {
while (!stopped) {
std::cout << "In " << name.toStdString() << "‘s run()." << std::endl;
QThread::msleep(400);
}
}

void stop() {
stopped = true;
}

private:
volatile bool stopped;
QString name;
};

int main(int argc, char *argv[]) {
QApplication app(argc, argv);

Thread thread;
thread.start();
Thread thread1("Thread1");
thread1.start();
Thread thread2("Thread2");
thread2.start();

return app.exec();
}

在Widget中, 还可以使用如在继承自QObject 的 void showEvent(QShowEVent *event)中使用myTimerId = startTimer();
在void hideEvent(QHideEVent *event)中使用killTimer(myTimerId);
在void timerEvent(QTimerEvent *event)中更新数据
在void paintEvent(QPaintEvent *event)中动态显示数据.

 

http://www.cppblog.com/biao/archive/2008/03/21/45053.html

Qt: 多线程, 就是这么简单(确实非常简洁明了)