我一直在尝试创建一个使用Qt Quick Controls 2以编程方式滚动到ScrollView底部的函数。我尝试了各种选项,但是我在网上找到的很多支持都涉及Qt Quick Controls 1,而不是2。这就是我试过了:
import QtQuick 2.8
import QtQuick.Controls 2.4
ScrollView {
id: chatView
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: inputTextAreaContainer.top
function scrollToBottom() {
// Try #1
// chatView.contentItem.contentY = chatBox.height - chatView.contentItem.height
// console.log(chatView.contentItem.contentY)
// Try #2
// flickableItem.contentY = flickableItem.contentHeight / 2 - height / 2
// flickableItem.contentX = flickableItem.contentWidth / 2 - width / 2
// Try #3
chatView.ScrollBar.position = 0.0 // Tried also with 1.0
}
TextArea {
id: chatBox
anchors.fill: parent
textFormat: TextArea.RichText
onTextChanged: {
// Here I need to scroll
chatView.scrollToBottom()
}
}
}
有谁知道如何使用Qt Quick Controls 2实现此目的?如果没有,那么有人可以替代这种方法吗?
您正在尝试将ScrollBar
的位置设置为1.0
:
chatView.ScrollBar.position = 0.0 // Tried also with 1.0
但是,您不考虑其大小。
ScrollBar
像这样设置位置时,请考虑其大小:
chatView.ScrollBar.vertical.position = 1.0 - chatView.ScrollBar.vertical.size
我很好奇Qt本身是如何解决这个问题的,所以我看了看它是如何QQuickScrollBar::increase()
实现的,我看到了这条线:
setPosition(qMin<qreal>(1.0 - d->size, d->position + step));
然后,我接受的第一个参数qMin
,即1.0 - d->size
,解决方案很明确。
由于您未提供MCE,因此我自己写了一封信。我希望您可以针对您的特殊情况进行调整。这里是:
import QtQuick 2.8
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.12
ApplicationWindow {
width: 480
height: 640
visible: true
title: qsTr("Scroll To Bottom")
ColumnLayout {
anchors.fill: parent
ScrollView {
id: scrollView
Layout.fillWidth: true
Layout.fillHeight: true
function scrollToBottom() {
ScrollBar.vertical.position = 1.0 - ScrollBar.vertical.size
}
contentWidth: children.implicitWidth
contentHeight: children.implicitHeight
ScrollBar.vertical.policy: ScrollBar.AlwaysOn
clip: true
ColumnLayout {
Layout.fillWidth: true
Layout.fillHeight: true
Repeater {
model: 50
Label {
text: "Message: " + index
}
}
}
}
TextField {
Layout.fillWidth: true
}
}
Component.onCompleted: {
scrollView.scrollToBottom()
}
}
该示例产生以下结果:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句