1.定义继承QThread的类A 复写run()函数;
2.在主线程中实例化A对象a
3.通过调用a->start()启动线程,线程会自动调用run()虚函数;run不可直接调用;
#ifndef MYTHREAD_H #define MYTHREAD_H #includeclass myThread: public QThread { public: myThread(); void run(); //声明继承于QThread虚函数 run() }; #endif // MYTHREAD_H
//mythread.cpp #include "mythread.h" #includemyThread::myThread() { } void myThread::run() { qDebug() << "hello world!"; //复写QThread类的 run()函数 }
//main.cpp #include#include "mythread.h" //包涵头文件 int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); myThread *thread1 = new myThread; //新建线程对象 thread1->start(); //启动线程 return a.exec(); }
1.创建继承Obeject的类A 将要在线程中实现的方法在A类中实现
2.在主线程中实例化A对象a,再实例化QThread类对象b
3.通过a.moveToThread(&b);将a对象的实现移入线程b对象作用范围内运行
4.b->start()启动线程;
5.通过信号与槽的方式启动调用A类成员函数;
// Worker 类定义 cpp
#include
class Worker : public QObject
{
Q_OBJECT
private slots:
void onTimeout()
{
qDebug()<<"Worker::onTimeout get called from?: "<
};
//main函数cpp
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"From main thread: "<
QThread t;
Worker worker;
worker.moveToThread(&t);
t.start();
connect(t,SIGNAL(started()),worker,SLOT(onTimeout()));
return a.exec();
}