QML自定义滚动Text控件

QML自定义滚动Text控件

与系统Text一样的做法,但在这基础上添加自动滚动文本的功能


Text滚动效果

Text滚动效果


1 使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Rectangle {
width: 150; height: 30

color: "red"
clip: true

MyText {
anchors.verticalCenter: parent.verticalCenter
width: 150
anchors.centerIn: parent
text: "123456789abcdefghijklmnopqrstuvwxyz"
font.pixelSize: 20
}
}

2 源码

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
import QtQuick 2.6

Text {
id: root

onXChanged: _xChanged()
onTextChanged: _textChanged()

Component.onCompleted: _init()

/* animation */
SequentialAnimation {
id: leftMovement

PropertyAnimation {
target: root
property: "x"
from: 0
to: (root.width - _text.width - 5)
duration: 5000
}
}

SequentialAnimation {
id: rightMovement

PropertyAnimation {
target: root
property: "x"
from: (root.width - _text.width - 5)
to: 0
duration: 5000
}
}

// To get the 'width' fo 'text'
Text {
id: _text
visible: false
text: parent.text
font.pixelSize: parent.font.pixelSize
}

/* private function */
function _xChanged() {
if (x == (root.width -_text.width - 5)) {
rightMovement.start()
}
else if (x == 0){
leftMovement.start()
}
}

function _textChanged() {
if (_text.width <= root.width) {
rightMovement.stop()
leftMovement.stop()
}
else {
anchors.centerIn = null
leftMovement.start()
}
}

function _init() {
if (_text.width > root.width) {
anchors.centerIn = null
leftMovement.start()
}
}
}

3 注意

  • 使用MyText控件需要设置width;
  • 一般需要使用Rectangle或Item包含并使用clip: true属性。