Qt 5 provides multiple methods for creating and using threads. You can choose between high-level methods and low-level ones.
High-level methods are much easier to get started, but are limited in what you can do with them.
Low-level methods, on the other hand, are more flexible, but not beginner-friendly.
Qt5提供了高级和低级线程编程方式。
首先,做一个高级的方式。
头文件
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
#include <QFutureWatcher>
#include <QThread>
#include <QDebug>
在main.cpp添加代码
#include "mainwindow.h"
#include <QApplication>
#include <QtOpenGL>
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
#include <QFutureWatcher>
#include <QThread>
#include <QDebug>
void printText(QString text, int count)
{
for(int i=0; i<count; ++i)
qDebug() << text << QThread::currentThreadId();
qDebug() << text << " Done";
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
// QOpenGLWindow window;
// window.setTitle("Hello World! OpenGL and Qt5");
// window.resize(640, 480);
// window.show();
//
QFuture<void> f1 = QtConcurrent::run(printText, QString("A"), 100);
QFuture<void> f2 = QtConcurrent::run(printText, QString("B"), 100);
QFuture<void> f3 = QtConcurrent::run(printText, QString("C"), 100);
QFutureWatcher<void> futureWatcher;
QObject::connect(&futureWatcher, QFutureWatcher<void>::finished, &w, MainWindow::mySlot);
futureWatcher.setFuture(f1);
f1.waitForFinished();
f2.waitForFinished();
f3.waitForFinished();
return a.exec();
}
运行结果如下:
多谢,亲爱的美美。