qt - QML:当它的高度改变时,将 ScrollView 移动到底部?
问题描述
我正在尝试制作一个消息编辑器小部件。我想在其高度更改时滚动到底部,ScrollView
以便用户可以跟上他们正在写的内容。我怎样才能实现这种功能?
这是我ScrollView
正在使用的代码:
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"
}
}
}
解决方案
尝试这个 :
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
}
推荐阅读
- typescript - Testing TypeScript with Jest: "no overload matches this call"
- php - 如何在 WordPress 中使用 update_user_meta 更新元值?
- php - xDebug 无法使用 docker、vscode 和 WSL 2
- node.js - 如何排序/排序来自 Firebase 的传入数据
- matplotlib - 堆栈的热图 seaborn
- javascript - 如何确保随机创建一个独特的标识符?
- c# - IdentityServer ClaimsIdentity to Impersonated WindowsIdentity
- bioinformatics - 带有注释名称和类别的热图聚类
- php - 列名必须是字符串或数组。yii
- linux - 根据行的一部分查找存在于一个文件中而不存在于另一个文件中的行