首页 > 代码库 > 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;}
#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使用定时器的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。