摆动范例展示如何动画 Widget 使用 QBasicTimer and timerEvent() 。此外,范例演示如何使用 QFontMetrics 确定屏幕中的文本大小。
摆动范例的屏幕截图
QBasicTimer 是针对计时器的低级类。不像 QTimer , QBasicTimer 并未继承自 QObject ;不是发射 timeout() 信号,当经过某些数量的时间后,它会发送 QTimerEvent 到 QObject 到我们的选择。这使 QBasicTimer 更轻量替代 QTimer 。Qt 的内置 Widget 会在内部使用它,且 Qt API 提供它是为高度优化的应用程序 (譬如:嵌入式应用程序)。
范例由 2 个类组成:
WigglyWidget
是以波浪线显示文本的自定义 Widget。
Dialog
是允许用户键入文本的对话框 Widget。它组合
WigglyWidget
和
QLineEdit
.
我们将首先快速查看
Dialog
类,然后审查
WigglyWidget
类。
class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = nullptr); };
Dialog
类提供允许用户键入文本的对话框 widget。然后文本的渲染是通过
WigglyWidget
.
Dialog::Dialog(QWidget *parent) : QDialog(parent) { WigglyWidget *wigglyWidget = new WigglyWidget; QLineEdit *lineEdit = new QLineEdit; QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(wigglyWidget); layout->addWidget(lineEdit); connect(lineEdit, &QLineEdit::textChanged, wigglyWidget, &WigglyWidget::setText); lineEdit->setText(tr("Hello world!")); setWindowTitle(tr("Wiggly")); resize(360, 145); }
在构造函数中,创建摆动 Widget 除了
行编辑
, and we put the two widgets in a vertical layout. We connect the line edit's
textChanged()
signal to the wiggly widget's
setText()
slot to obtain the real time interaction with the wiggly widget. The widget's default text is "Hello world!".
class WigglyWidget : public QWidget { Q_OBJECT public: WigglyWidget(QWidget *parent = nullptr); public slots: void setText(const QString &newText) { text = newText; } protected: void paintEvent(QPaintEvent *event) override; void timerEvent(QTimerEvent *event) override; private: QBasicTimer timer; QString text; int step; };
WigglyWidget
class provides the wiggly line displaying the text. We subclass
QWidget
and reimplement the standard
paintEvent()
and
timerEvent()
functions to draw and update the widget. In addition we implement a public
setText()
slot that sets the widget's text.
timer
变量,类型
QBasicTimer
, is used to update the widget at regular intervals, making the widget move. The
text
variable is used to store the currently displayed text, and
step
to calculate position and color for each character on the wiggly line.
WigglyWidget::WigglyWidget(QWidget *parent) : QWidget(parent), step(0) { setBackgroundRole(QPalette::Midlight); setAutoFillBackground(true); QFont newFont = font(); newFont.setPointSize(newFont.pointSize() + 20); setFont(newFont); timer.start(60, this); }
In the constructor, we make the widget's background slightly lighter than the usual background using the QPalette::Midlight color role. The background role defines the brush from the widget's palette that Qt uses to paint the background. Then we enlarge the widget's font with 20 points.
Finally we start the timer; the call to QBasicTimer::start () makes sure that this particular wiggly widget will receive the timer events generated when the timer times out (every 60 milliseconds).
void WigglyWidget::paintEvent(QPaintEvent * /* event */) { static constexpr int sineTable[16] = { 0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38 }; QFontMetrics metrics(font()); int x = (width() - metrics.horizontalAdvance(text)) / 2; int y = (height() + metrics.ascent() - metrics.descent()) / 2; QColor color;
paintEvent()
function is called whenever a
QPaintEvent
is sent to the widget. Paint events are sent to widgets that need to update themselves, for instance when part of a widget is exposed because a covering widget was moved. For the wiggly widget, a paint event will also be generated every 60 milliseconds from the
timerEvent()
槽。
sineTable
represents y-values of the sine curve, multiplied by 100. It is used to make the wiggly widget move along the sine curve.
QFontMetrics
object provides information about the widget's font. The
x
variable is the horizontal position where we start drawing the text. The
y
variable is the vertical position of the text's base line. Both variables are computed so that the text is horizontally and vertically centered. To compute the base line, we take into account the font's ascent (the height of the font above the base line) and font's descent (the height of the font below the base line). If the descent equals the ascent, they cancel out each other and the base line is at
height()
/ 2.
QPainter painter(this); for (int i = 0; i < text.size(); ++i) { int index = (step + i) % 16; color.setHsv((15 - index) * 16, 255, 191); painter.setPen(color); painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), QString(text[i])); x += metrics.horizontalAdvance(text[i]); } }
Each time the
paintEvent()
function is called, we create a
QPainter
对象
painter
to draw the contents of the widget. For each character in
text
, we determine the color and the position on the wiggly line based on
step
. In addition,
x
is incremented by the character's width.
For simplicity, we assume that
QFontMetrics::horizontalAdvance
(
text
) returns the sum of the individual character advances (
QFontMetrics::horizontalAdvance
(
text[i]
)). In practice, this is not always the case because
QFontMetrics::horizontalAdvance
(
text
) also takes into account the kerning between certain letters (e.g., 'A' and 'V'). The result is that the text isn't perfectly centered. You can verify this by typing "AVAVAVAVAVAV" in the line edit.
void WigglyWidget::timerEvent(QTimerEvent *event) { if (event->timerId() == timer.timerId()) { ++step; update(); } else { QWidget::timerEvent(event); }
timerEvent()
function receives all the timer events that are generated for this widget. If a timer event is sent from the widget's
QBasicTimer
,递增
step
以使文本移动,和调用
QWidget::update
() to refresh the display. Any other timer event is passed on to the base class's implementation of the
timerEvent()
函数。
QWidget::update
() slot does not cause an immediate repaint; instead the slot schedules a paint event for processing when Qt returns to the main event loop. The paint events are then handled by
WigglyWidget
's
paintEvent()
函数。