Qt学习: QTimerEvent定时器事件的处理程序代码示例

本文介绍了一个简单的Qt定时器事件示例,演示了如何在Qt应用程序中使用定时器来周期性地更改按钮图标,包括定时器的启动、停止及事件处理。

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

重要函数:
1.int startTimer(int); //设置定时器,返回一个ld.
2.int event->timerld(); //返回当前的ld.
3.void killTimer(int); //停止定时器.


首先从Qt设计师中拖拽出三个按钮,由于只是演示定时器事件的使用,所以就没有布局的需要了.
这里写图片描述


以下是”c.cpp”的代码:

#include "c.h"

c::c(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);


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

c::~c()
{

}
void c::timerEvent(QTimerEvent*event)
{
    //判断当前定时器对应的是哪个ld.
    if (event->timerId() == this->m_lamp)
    {
        if (this->m_lampStatus == false)
        {
            //设置按钮的图标.
            ui.toolButton->setIcon(QIcon("Icons/lamp.png"));
            this->m_lampStatus = true;
        }
        else
        {
            ui.toolButton->setIcon(QIcon("Icons/space.png")); 
            this->m_lampStatus = false;
        }
    }
}
void c::startTimerSlot()
{
    //设置定时器,返回一个timerld.注意单位为毫秒,1000毫秒等于1秒.
    this->m_lamp = this->startTimer(1000);
}
void c::stopTimerSlot()
{
    //停止定时器.
    this->killTimer(this->m_lamp);
}

以下是”c.h”的代码:

#ifndef C_H
#define C_H

#include <QtWidgets/QMainWindow>
#include "ui_c.h"
#include <QLabel>
#include <QTimerEvent>


class c : public QMainWindow
{
    Q_OBJECT

public:
    c(QWidget *parent = 0);
    ~c();
protected:
    //这是一个虚函数,从QEvent继承而来.
    void timerEvent(QTimerEvent*event);
private slots:
    void startTimerSlot();
    void stopTimerSlot();

private:
    Ui::cClass ui;
    int m_lamp;
    bool m_lampStatus = false;
};

#endif // C_H

最后是”main.cpp”的代码:

#include "c.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    c w;
    w.show();
    return a.exec();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值