1. 程式人生 > >Qt學習: QTimerEvent定時器事件的處理程序代碼示例

Qt學習: QTimerEvent定時器事件的處理程序代碼示例

軟件 window 編程

重要函數:
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);
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546

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

#ifndef C_H#define C_H#include <QtWidgets/QMainWindow>#include "ui_c.h"#include <QLabel>#include <QTimerEvent>class c : public QMainWindow
{
    Q_OBJECTpublic:    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_H12345678910111213141516171819202122232425262728293031

最後是”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();
}


本文出自 “13109855” 博客,請務必保留此出處http://13119855.blog.51cto.com/13109855/1971837

Qt學習: QTimerEvent定時器事件的處理程序代碼示例