首先创建一个带ui的项目,添加三个控件,lable显示当前时间,pushButton启动线程,pushButton_2用来模拟能否点击,到点删除
mainwindow.h
signals:
//点击pushButton时发出信号,启动线程
void fun_singl();
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myThread.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->pushButton_2->setEnabled(false);
myThread *my = new myThread();
connect(ui->pushButton,&QPushButton::clicked,this,[=](){
emit fun_singl();
qDebug()<<"开启线程";
});
connect(this,&MainWindow::fun_singl,my,&myThread::fun);
//检测到信号,删除
connect(my,&myThread::delbtn,this,[=](){
// qDebug()<<"aa";
if(ui->pushButton_2 != nullptr)
{
ui->pushButton_2->deleteLater();
ui->pushButton_2 = nullptr;
}
});
//更新时间
connect(my,&myThread::renewal,this,[=](){
QDateTime t = QDateTime::currentDateTime();
QString time = t.toString("yyyy-MM-dd hh:mm:ss");
ui->label->setText(time);
if(ui->pushButton_2 != nullptr)
{
ui->pushButton_2->setEnabled(true);
}
});
}
myThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QThread>
#include <QTimer>
#include <QDateTime>
#include <QDebug>
class myThread : public QThread
{
Q_OBJECT
public:
explicit myThread(QObject *parent = nullptr);
~myThread();
signals:
void delbtn();
void renewal();
public slots:
void fun();
private:
QTimer *timer;
};
#endif // MYTHREAD_H
myThread.cpp
void myThread::fun()
{
// MainWindow *mainUi = new MainWindow();
timer = new QTimer();
connect(timer,&QTimer::timeout,this,[=](){
QDateTime t = QDateTime::currentDateTime();
// QString time = t.toString("yyyy-MM-dd hh:mm:ss");
// mainUi->getLabel()->setText(time);
QDateTime anticipateTime = QDateTime::fromString("2023-10-13 14:18:20", "yyyy-MM-dd hh:mm:ss");
QDateTime delTime = QDateTime::fromString("2023-10-13 14:18:30", "yyyy-MM-dd hh:mm:ss");
if(t >= anticipateTime)//达到启动时间
{
//通知主线程更新时间
emit renewal();
// qDebug()<<time;
}
if(t >= delTime)//达到删除时间
{
emit delbtn();
// terminate();
}
});
timer->start(1000);
}
效果
开始时需点击启动按钮启动线程,lable不显示,pushButton_2不能点击
到达anticipateTime pushButton_2能点击,lable显示当前时间
到达delTime pushButton_2删除,lable继续显示时间
暂时就这样了,欢迎大佬来指教