Qt_QTimer定时器结合线程的简单使用

本文介绍如何在Qt中使用QTimer类创建重复和单次触发的定时器,并通过线程控制定时器的运行,实现LCD显示时间计数功能。文章详细展示了Widget类和MyThread类的定义及其实现过程,包括信号与槽的连接,以及线程的启动与停止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<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界面展示:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Star星屹程序设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值