Qml输入文本并自动滚动

一、介绍

   手机微信聊天的时候,当我们在消息输入框输入很长一段文本时,输入超过一行时输入框会自动增大高度,当输入框达到最高高度时,文本自动向上滚动,如图:
这里写图片描述

  右侧出现滚动条,当我们再输入满一行的时候文本会自动向上滚动。用qml实现这个功能非常简单,只需要用到 ScrollView 和 TextArea 这两个控件就能实现。

二、源码

  
环境 Qt5.9 + win10

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480

    ScrollView {
        id: scView
        anchors.centerIn: parent
        width: 200; height: 24 // 初始高度就是一行
        background: Rectangle {
            anchors.fill: parent
            border.color: "gray"
            radius: 5
        }

        TextArea {
            id: contentText
            property int preContentHeight: 0
            wrapMode: TextArea.Wrap; selectByMouse: true;
            onContentHeightChanged: {
                //每一行为高度为14, 当输入大于3行的时候自动滚动
                if(contentHeight > 14 && contentHeight < 56) {
                    if(contentHeight != preContentHeight) {
                        preContentHeight = contentHeight;
                        scView.height += 14;
                    }
                }
            }
        }
    }
}

效果图:
这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/a844651990/article/details/78774094