mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
class mythread : public QObject
{
Q_OBJECT
public:
explicit mythread(QObject *parent = nullptr);
//线程处理函数
public:
void myTimeout();
void setFlag( bool flag);
signals:
void mysignal();
public slots:
private:
bool isStop;
};
#endif // MYTHREAD_H
mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include"mythread.h"
#include<QThread>
namespace Ui {
class myWidget;
}
class myWidget : public QWidget
{
Q_OBJECT
public:
explicit myWidget(QWidget *parent = 0);
~myWidget();
public:
void init();
signals:
void startthread();//启动子线程的信号函数
private slots:
void on_btn_Start_clicked();
void dealsingal();
void close_Window();
void on_btn_Stop_clicked();
private:
Ui::myWidget *ui;
mythread*myT;
QThread*thread;
};
#endif // MYWIDGET_H
main.cpp
#include "mywidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
myWidget w;
w.show();
return a.exec();
}
mythread.cpp
#include "mythread.h"
#include<QThread>
#include<QDebug>
mythread::mythread(QObject *parent) : QObject(parent)
{
isStop=false;
}
void mythread::myTimeout()
{
while(isStop==false)
{
QThread::sleep(1);//每隔一秒发一下
emit mysignal();
qDebug()<<QStringLiteral("子线程号")<<QThread::currentThread();
}
}
void mythread::setFlag(bool flag)
{
isStop=flag ;
}
mywidget.cpp
#include "mywidget.h"
#include "ui_mywidget.h"
#include<QDebug>
myWidget::myWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::myWidget)
{
ui->setupUi(this);
init();
}
myWidget::~myWidget()
{
delete ui;
}
void myWidget::init()
{
//动态分配空间
myT=new mythread;//不能指定父对象,因为他要移到主线程中: myT->moveToThread(thread);// QObject::moveToThread: Cannot move objects with a parent
//创建子线程
thread=new QThread(this);
//把自定义的线程加入子线程中
myT->moveToThread(thread);
connect(myT,SIGNAL(mysignal()),this,SLOT(dealsingal()));
qDebug()<<QStringLiteral("主线程号")<<QThread::currentThread();
connect(this,&myWidget::startthread,myT,&mythread::myTimeout,Qt::AutoConnection);//直接用作用域符限制可以运行,用slot-signal不能实现
connect(this,SIGNAL(destroyed(QObject*)),this,SLOT(close_Window()));
}
void myWidget::on_btn_Start_clicked()
{
if(thread->isRunning()==true)
{
return ;//在运行的过程中,按下start无反应
}
//启动线程,但是没有启动线程函数
thread->start();
myT->setFlag(false);
//myT->myTimeout();不能直接调用线程处理函数,直接调用线程,导致线程处理函数和主线程在同一个线程
//"主线程号" QThread(0x28e9041b9c0)
// "子线程号" QThread(0x28e9041b9c0)发现线程号是一样的
//只能通过信号和槽的方式调用
emit startthread();
}
void myWidget::dealsingal()
{
static int i=0;
i++;
ui->lcdNumber->display(i);
}
void myWidget::close_Window()
{
on_btn_Stop_clicked();
}
void myWidget::on_btn_Stop_clicked()
{
if(thread->isRunning()==false)
{
return;
}
myT->setFlag(true);
thread->quit();
thread->wait();
delete myT;
}