代码 qtimer_thread.cpp
#include "qtimer_thread.h"
#include "ui_qtimer_thread.h"
Qtimer_thread::Qtimer_thread(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Qtimer_thread)
{
ui->setupUi(this);
btn = new QPushButton(this);
connect(btn, SIGNAL(clicked()),
this, SLOT(creat_thread()));
}
void Qtimer_thread::thread()
{
std::cout << "sleep" << std::endl;
}
void Qtimer_thread::creat_thread()
{
tim = new QTimer(this);
connect(tim, SIGNAL(timeout()), this, SLOT(thread()));
tim->start(1000);
}
Qtimer_thread::~Qtimer_thread()
{
std::cout << "Qtimer_thread::~Qtimer_thread()" << std::endl;
thread_exit = 0;
delete btn;
delete tim;
delete ui;
}
void Qtimer_thread::closeEvent(QCloseEvent *event)
{
std::cout << "closeEvent execed" << std::endl;
thread_exit = 0;
}
代码 qtimer_thread.h
#ifndef QTIMER_THREAD_H
#define QTIMER_THREAD_H
#include <QWidget>
#include <QPushButton>
#include <iostream>
#include <QTimer>
#include <QCloseEvent>
extern "C"
{
#include <unistd.h>
}
QT_BEGIN_NAMESPACE
namespace Ui { class Qtimer_thread; }
QT_END_NAMESPACE
class Qtimer_thread : public QWidget
{
Q_OBJECT
public:
Qtimer_thread(QWidget *parent = nullptr);
~Qtimer_thread();
protected slots:
void thread();
void creat_thread();
protected:
void closeEvent(QCloseEvent *event);
private:
QPushButton *btn = nullptr;
QTimer *tim = nullptr;
Ui::Qtimer_thread *ui;
int thread_exit;
};
#endif // QTIMER_THREAD_H