前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >QML自定义滚动Text控件

QML自定义滚动Text控件

作者头像
Qt君
发布2019-07-15 15:13:54
1.2K0
发布2019-07-15 15:13:54
举报
文章被收录于专栏:跟Qt君学编程跟Qt君学编程

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

Text滚动效果

使用示例

代码语言:javascript
复制
Rectangle {
  width: 150; height: 30

  color: "red"
  clip: true

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

源码

代码语言:javascript
复制
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()
        }
    }
}

注意

  • 使用MyText控件需要设置width;
  • 一般需要使用Rectangle或Item包含并使用clip: true属性。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-01-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Qt君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用示例
  • 源码
  • 注意
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档