import QtQuick 2.15 Item { id: root property alias text: textMetrics.text property alias elide: textMetrics.elide property alias font: textMetrics.font property alias color: marqueeText.color clip: true height: marqueeText.height TextMetrics { id: textMetrics elide: Text.ElideRight elideWidth: root.width } Text { id: marqueeText text: textMetrics.elidedText font: textMetrics.font PropertyAnimation on x { id: marqueeAnimator running: false from: marqueeText.width to: -(textMetrics.width + 2) loops: Animation.Infinite } function startMarqueeAnimator() { if (marqueeAnimator.running) { return } if (textMetrics.width > textMetrics.elideWidth) { marqueeAnimator.duration = textMetrics.text.length * 300 marqueeText.text = textMetrics.text marqueeAnimator.start() } } function stopMarqueeAnimator() { marqueeAnimator.stop() marqueeText.x = 0 marqueeText.text = textMetrics.elidedText } } MouseArea { id: mouseArea anchors.fill: parent hoverEnabled: true propagateComposedEvents: true onEntered: { marqueeText.startMarqueeAnimator() } onExited: { marqueeText.stopMarqueeAnimator() } onClicked: { mouse.accepted = false } } }
参考:
QML实现跑马灯_不爱debug的BugMaker的博客-CSDN博客