main.cpp
没有用的main.cpp
···
#include
#include <mythread.h>
#include
#include “myclass.h”
#include
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
myclass *mm = new myclass();
return a.exec();
}
···
myclass.cpp 主线程
在myclass.cpp中写主线程:
注意:
- 一定要在for循环外面发送信号
- 要传参就向子线程构造函数中传
#pragma execution_character_set("utf-8")
#include "myclass.h"
#include <mythread.h>
#include <QDebug>
#include <QThread>
myclass::myclass()
{
qDebug()<<"myclass线程号:"<<QThread::currentThreadId();
//1. mythread类,在这个类中需要进行耗时操作,把入口函数声明为槽函数
//2. mythread类在主线程中new出,并不设置任何父对象()
//explicit mythread(QObject *parent = 0);
for(int i = 0 ; i< 4 ;i++){
qDebug()<<i<<"myclass线程号";
mythread * thread1 = new mythread(i);//子线程
//3. 声明一个QThread 类对象
QThread *Qtt = new QThread;
//4. 把一个QObject通过moveToThread移动到一个线程里去,
//moveToThread是QObject的线程转移函数,这个函数可以把一个顶层Object转移到一个新的线程里去
thread1->moveToThread(Qtt);
//这个派生自QObject的类的代码就会在新的线程里面直线
//5. 把线程的finished信号和object的deleteLater槽连接
connect(Qtt,&QThread::finished,Qtt,&QObject::deleteLater);
//6. 正常连接其他信号和槽
connect(Qtt,&QThread::finished,thread1,&QObject::deleteLater);
connect(this,&myclass::emitsignal,thread1,&mythread::begin);
//7. 初始化完后调用'QThread::start()'来启动线程
Qtt->start();
}
//一定要在for循环外面发送信号,否则会产生 1+ 2+3+4...个子线程
emit emitsignal();
}
myclass.h 主线程头文件
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
class myclass: public QObject
{
Q_OBJECT
public:
myclass( );
signals:
void emitsignal( );
};
#endif // MYCLASS_H
mythread.h 子线程
#pragma execution_character_set("utf-8")
#include "mythread.h"
#include <QDebug>
#include <QThread>
mythread::mythread(int a ){//要传参向子线程构造函数中传
i = a;
}
void mythread::begin( )
{
qDebug()<<i<<"mythread线程号:"<<QThread::currentThreadId();
}
mythread.h 子线程头文件
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
class mythread: public QObject
{
Q_OBJECT
public:
// explicit mythread(QObject *parent = 0);
int i ;
mythread(int i );
public slots:
void begin();
};
#endif // MYTHREAD_H