QTimerEvent定时器事件的使用

本文详细介绍了Qt中定时器的使用方法,包括如何在多线程中使用QThread的sleep和msleep函数,以及如何在Qt中创建和管理定时器。通过一个具体的UI界面Demo,演示了定时器的启动、停止及事件处理过程。

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

注意:在定时器中

1、this->m_switch = this->startTimer(1000);括号里面的是毫秒计算

2、在多线程中的 QThread::sleep(1);括号里面是以秒来计算

 QThread::msleep(1);这个时候括号里是以毫秒来计算

新建一个ui界面的demo

.h(头文件中)

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QTimerEvent>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected:
    //这是一个虚函数,从QEvent继承而来.
    void timerEvent(QTimerEvent*event);

private slots:
    void startTimerSlot();//两个槽函数,执行开始和停止的功能
    void stopTimerSlot();

private:
    Ui::Widget *ui;
    int  m_switch;//设置定时器ID
    bool m_Status = false;//设置当前的状态,默认为false

};

#endif // WIDGET_H

在.cpp(源文件中)

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //连接信号与槽.
      connect(ui->startButton, SIGNAL(clicked()), this, SLOT(startTimerSlot()));
      connect(ui->stopButton, SIGNAL(clicked()), this, SLOT(stopTimerSlot()));

}

Widget::~Widget()
{
    delete ui;
}

void Widget::timerEvent(QTimerEvent*event)
{
    //判断当前定时器对应的是哪个Id.
        if (event->timerId() == this->m_switch)
        {
            if (this->m_Status == false)
            {
                //更改按钮上的文字
                ui->toolButton->setText("123");
                this->m_Status = true;
            }
            else
            {
                //更改按钮上的文字
                ui->toolButton->setText("234");
                this->m_Status = false;
            }
        }
}
//开始
void Widget::startTimerSlot()
{
    //设置定时器,返回一个timerld.注意单位为毫秒,1000毫秒等于1秒.
    this->m_switch = this->startTimer(1000);
}

void Widget::stopTimerSlot()
{
    //停止定时器.
    this->killTimer(this->m_switch);
}

在main函数中:

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

现象是在点击完开始按钮之后,就会实现切换的功能 :

参考:https://blog.youkuaiyun.com/qq_37233607/article/details/78218596

并作出一些修改!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值