码迷,mamicode.com
首页 > 其他好文 > 详细

qt使用定时器的例子

时间:2014-10-13 20:42:07      阅读:640      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   sp   

小例子 练习习作

#ifndef TICKER_H
#define TICKER_H

#include <QWidget>

class Ticker : public QWidget
{
    Q_OBJECT

public:
    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
bubuko.com,布布扣
#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使用定时器的例子

标签:style   blog   http   color   io   os   使用   ar   sp   

原文地址:http://www.cnblogs.com/itdef/p/4022748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!