Qt 线程的创建和使用(一)

#pragma once

#include <QObject>
#include <QThread>

class QtMyThread : public QThread
{
	Q_OBJECT

public:
	QtMyThread(QObject *parent);
	~QtMyThread();

signals:
	void isDone();

protected:
	//QThread 的虚函数  线程入口函数 不能直接调用
	void run();
};
#include "QtMyThread.h"

QtMyThread::QtMyThread(QObject *parent)
	: QThread(parent)
{
}

QtMyThread::~QtMyThread()
{
}
void QtMyThread::run()
{
	//很复杂的数据处理 
	sleep(5);

	//线程处理完后 发送一个信号
	emit isDone();
}
#pragma once

#include <QtWidgets/QWidget>
#include "ui_QtThread.h"
#include <QTimer>
#include "QtMyThread.h"

class QtThread : public QWidget
{
	Q_OBJECT

public:
	QtThread(QWidget *parent = Q_NULLPTR);

private slots:
	void slotStart();
	void slotDealDone();
	void slotStopThread();		//关闭线程

private:
	Ui::QtThreadClass ui;
	QTimer *ptimer;
	QtMyThread *pthread;
};
#include "QtThread.h"
#include <QThread>

QtThread::QtThread(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	ptimer = new QTimer(this);
	pthread = new QtMyThread(this);

	connect(ptimer, &QTimer::timeout, [=]() {
		static int i = 0;
		i++;
		ui.lcdNumber->display(i);
	});

	connect(ui.pushButton, &QPushButton::clicked, this,&QtThread::slotStart);

	//线程运行结束 触发信号 关闭定时器
	connect(pthread, &QtMyThread::isDone, this, &QtThread::slotDealDone);
	//当按窗口右上角 X(关闭) 按钮 窗口触发 destroyed 信号
	connect(this, &QtThread::destroyed, this, &QtThread::slotStopThread);
}
void QtThread::slotStart()
{
	if (!ptimer->isActive())		//判断定时器是否被激活
	{
		ptimer->start(100);
	}
	pthread->start();
}
void QtThread::slotDealDone()
{
	ptimer->stop();		//关闭定时器
}
void QtThread::slotStopThread()
{
	pthread->quit();		//线程退出 停止
	//等待线程处理完
	pthread->wait();
}

你可能感兴趣的:(Qt基础)