#pragma once
#include <QObject>
#include <QThread>
class QtMyThread : public QThread
{
Q_OBJECT
public:
QtMyThread(QObject *parent);
~QtMyThread();
signals:
void isDone();
protected:
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);
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();
}