方法一:继承QThread老式方法
1.定义继承QThread的类A 复写run()函数;
2.在主线程中实例化A对象a
3.通过调用a->start()启动线程,线程会自动调用run()虚函数;run不可直接调用;
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> class myThread: public QThread { public: myThread(); void run(); //声明继承于QThread虚函数 run() }; #endif // MYTHREAD_H
//mythread.cpp #include "mythread.h" #include <QDebug> myThread::myThread() { } void myThread::run() { qDebug() << "hello world!"; //复写QThread类的 run()函数 }
//main.cpp #include <QCoreApplication> #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(&