首页 > 代码库 > qt使用定时器的例子

qt使用定时器的例子

小例子 练习习作

#ifndef TICKER_H#define TICKER_H#include <QWidget>class Ticker : public QWidget{    Q_OBJECTpublic:    Ticker(QWidget *parent = 0);    void setText(const QString &newText);    QString text() const { return myText; }    QSize sizeHint() const;protected:    void paintEvent(QPaintEvent *event);    void timerEvent(QTimerEvent *event);    void showEvent(QShowEvent *event);    void hideEvent(QHideEvent *event);private:    QString myText;    int myTimerId;};#endif
#include <QtGui>#include "ticker.h"Ticker::Ticker(QWidget *parent)    : QWidget(parent){    myTimerId = 0;}void Ticker::setText(const QString &newText){    myText = newText;    update();    updateGeometry();}QSize Ticker::sizeHint() const{    return fontMetrics().size(0, text());}void Ticker::paintEvent(QPaintEvent * /* event */){    QPainter painter(this);    static int i = 0;    i++;    if(i%2)    {        myText = tr("odd");    }else    {        myText = tr("even");    }     int textWidth = fontMetrics().width(text());    painter.drawText(0, 0, textWidth, height(),            Qt::AlignLeft | Qt::AlignVCenter, text());}void Ticker::showEvent(QShowEvent * /* event */){    myTimerId = startTimer(1000);}void Ticker::timerEvent(QTimerEvent *event){    if (event->timerId() == myTimerId) {        update();        updateGeometry();    } else {        QWidget::timerEvent(event);    }}void Ticker::hideEvent(QHideEvent * /* event */){    killTimer(myTimerId);    myTimerId = 0;}
View Code
#include <QApplication>#include "ticker.h"int main(int argc, char *argv[]){    QApplication app(argc, argv);    Ticker ticker;    ticker.setWindowTitle(QObject::tr("Ticker"));    ticker.setText(QObject::tr("4"));    ticker.show();    return app.exec();}

 

 

qt使用定时器的例子