<QTimer>:The QTimer class provides repetitive and single-shot timers.
本次练习使用LCD简单记录时间,利用线程设定一段具体时间后关闭定时器,两者各做各的事,互不影响
简单展示:
定时器类:
头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer>
#include "mythread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pb_start_clicked();
void display();
void on_pushButton_2_clicked();
void dealDone();
void stopThread();
private:
Ui::Widget *ui;
QTimer *time;
MyThread *thread;
};
#endif // WIDGET_H
具体实现:
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
time = new QTimer(this);
connect(time, SIGNAL(timeout()),
this, SLOT(display()));
thread = new MyThread(this);
connect(thread, SIGNAL(isDone()),
this, SLOT(dealDone()));
connect(this, SIGNAL(destroyed(QObject*)),
this,SLOT(stopThread()));
}
void Widget::stopThread()
{
thread->quit();
//等待线程处理完再结束
thread->wait();
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pb_start_clicked()
{
if(time->isActive() == false)
{
time->start(100);
}
//开启线程
thread->start();
}
void Widget::on_pushButton_2_clicked()
{
// if(time->isActive() == true)
// {
// time->stop();
// }
}
void Widget::display()
{
static int i = 0;
i++;
ui->lcdNumber->display(i);
}
void Widget::dealDone()
{
qDebug() << "it is over!!!";
time->stop();
}
线程的简单加入:
头文件:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
signals:
void isDone();
public slots:
void run();
public:
QThread *thread;
};
#endif // MYTHREAD_H
具体实现:
#include "mythread.h"
#include <QTimer>
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
sleep(5);
emit isDone();
}
Qt_Designer界面展示: