-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathScrollLabel.cpp
97 lines (86 loc) · 2.42 KB
/
ScrollLabel.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "ScrollLabel.h"
#include <QTimerEvent>
#include <QPaintEvent>
#include <QResizeEvent>
#include <QPainter>
#include <QDebug>
ScrollLabel::ScrollLabel(QWidget *parent)
: QLabel(parent)
{
//启动定时器,触发this的timerevent
scrollTimer.start(interval,this);
}
ScrollLabel::ScrollDirection ScrollLabel::getDirection() const
{
return direction;
}
void ScrollLabel::setDirection(ScrollLabel::ScrollDirection direction)
{
if(this->direction!=direction){
this->direction=direction;
offset=0;
}
}
int ScrollLabel::getInterval() const
{
return interval;
}
void ScrollLabel::setInterval(int interval)
{
if(this->interval!=interval){
this->interval=interval;
scrollTimer.start(interval,this);
}
}
void ScrollLabel::timerEvent(QTimerEvent *event)
{
//定时器timeout
if(event->timerId()==scrollTimer.timerId()){
event->accept();
++offset;
if(offset>textWidth+labelWidth){
offset=0;
}
update();
}else{
QLabel::timerEvent(event);
}
}
void ScrollLabel::paintEvent(QPaintEvent *event)
{
event->accept();
QPainter painter(this);
const int text_width = painter.fontMetrics().width(text());
//字体绘制坐标为左下角,y值就是 labelheight-(labelheight-textheight)/2
//因为取的字体高度还受基线影响,height=descent+ascent,这里去掉descent
//也可以用Qt5.8提供的capHeight
/*const int text_height = painter.fontMetrics().capHeight();
const int text_y = (height()+text_height) / 2;*/
const int text_height = painter.fontMetrics().height();
const int text_y = (height()+text_height) / 2-painter.fontMetrics().descent();
if (textWidth != text_width && text_width > 0) {
textWidth = text_width;
offset = 0;
}else {
if(direction==RightToLeft){
//从右往左
painter.drawText(labelWidth - offset, text_y, text());
}else{
//从左往右
painter.drawText(offset - textWidth, text_y, text());
}
}
}
void ScrollLabel::resizeEvent(QResizeEvent *event)
{
const int old_width = event->oldSize().width();
const int new_width = event->size().width();
if (new_width > 10) {
labelWidth = new_width;
//新宽度更小,就重置偏移
if (new_width < old_width) {
offset = 0;
}
}
QLabel::resizeEvent(event);
}