无聊学习着......
写一个 Ticker,练习下事件触发
部分代码如下:
ticker.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #ifndef TICKER_H #define TICKER_H #include <QtGui/QWidget> namespace Ui { class Ticker; } class Ticker : public QWidget { Q_OBJECT public: Ticker(QWidget *parent = 0); ~Ticker(); void setText(const QString &newText); QString text() const ; QSize sizeHint() const; protected: void paintEvent(QPaintEvent *event); void timerEvent(QTimerEvent *evnet); void showEvent(QShowEvent *event); void hideEvent(QHideEvent *event); private: Ui::Ticker *ui; QString tickerText; int offset; int timerID; }; #endif
|
ticker.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| *#include <QtGui> #include "ticker.h" #include "ui_ticker.h" Ticker::Ticker(QWidget *parent) : QWidget(parent), ui(new Ui::Ticker) { ui->setupUi(this); offset = 0; timerID = 0; } Ticker::~Ticker() { delete ui; }
void Ticker::setText(const QString &newText) { tickerText = newText; update(); updateGeometry(); }
QString Ticker::text() const { return tickerText; }
QSize Ticker::sizeHint() const { return fontMetrics().size(0,text()); }
void Ticker::paintEvent(QPaintEvent *) { QPainter painter(this); int textWidth = fontMetrics().width(text()); if (textWidth < 1) return ; int x = -offset; while (x < width()) { painter.drawText(x,0,textWidth,height(),Qt::AlignLeft | Qt::AlignVCenter,text()); x += textWidth; } }
void Ticker::timerEvent(QTimerEvent *event) { if (event->timerId() == timerID) { ++offset; if(offset >= fontMetrics().width(text())) offset = 0; scroll(-1,0); } else { QWidget::timerEvent(event); } }
void Ticker::showEvent(QShowEvent *) { timerID = startTimer(30); }
void Ticker::hideEvent(QHideEvent *) { killTimer(timerID); timerID = 0; }
|
界面截图如下:
可以自动向左滚动...(怎么感觉像楼下显示电费的....尴尬了)
继续无聊的暑假....