I am trying to make a message composer widget. I want to scroll to the bottom of the ScrollView
when its height is changed so that the user can keep up with what they are writing. How can I achieve this sort of functionality?
Here is my code for the ScrollView
I am using:
ScrollView {
id: scrollView
anchors.left: parent.left
anchors.right: clearTextBtn.left
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.bottomMargin: 0
anchors.leftMargin: 0
anchors.rightMargin: 10
clip: true
ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
hoverEnabled: true
onHoveredChanged: {
if (hovered) {
borderWidth = 2
cursorShape = Qt.IBeamCursor
} else {
borderWidth = focus ? 2 : 0
cursorShape = Qt.ArrowCursor
}
}
onFocusChanged: {
if (focus) {
borderWidth = 2
} else {
borderWidth = 0
}
}
TextEdit {
id: textEdit
width: scrollView.width
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignTop
anchors.bottomMargin: 0
anchors.topMargin: 0
clip: true
color: textColor
anchors.left: parent.left
wrapMode: Text.WordWrap
anchors.leftMargin: 0
padding: 10
selectByMouse: true
Label {
id: placeholderTxt
text: qsTr("Compose Message...")
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
verticalAlignment: Text.AlignTop
anchors.topMargin: 10
anchors.rightMargin: 223
anchors.leftMargin: 10
visible: textEdit.length == 0 && !textEdit.activeFocus
color: "#a3a3a3"
}
}
}
CodePudding user response:
Try this :
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window {
id: box
width: 640
height: 180
visible: true
title: qsTr("ScrollBar")
Flickable {
id: inputWrapper
anchors.fill: parent
contentHeight: input.implicitHeight
contentWidth: input.implicitWidth
ScrollBar.vertical: ScrollBar {
id: scrollBar
policy: ScrollBar.AlwaysOn
anchors.left: box.right
}
Keys.onUpPressed: scrollBar.decrease()
Keys.onDownPressed: scrollBar.increase()
clip: true
flickableDirection: Flickable.VerticalFlick
function ensureVisible(r)
{
if (contentX >= r.x)
contentX = r.x;
else if (contentX width <= r.x r.width)
contentX = r.x r.width-width;
if (contentY >= r.y)
contentY = r.y;
else if (contentY height <= r.y r.height)
contentY = r.y r.height-height;
}
TextEdit {
id: input
anchors.fill: parent
text: ""
focus: true
wrapMode: TextEdit.Wrap
onCursorRectangleChanged: inputWrapper.ensureVisible(cursorRectangle)
} // TextEdit
} // Flickable
}