gpt4 book ai didi

qt - 如何以编程方式将 ScrollView 滚动到底部?

转载 作者:行者123 更新时间:2023-12-04 13:11:43 24 4
gpt4 key购买 nike

我一直在尝试创建一个以编程方式滚动到底部的函数 ScrollView使用 Qt Quick Controls 2。我尝试了各种选择,但我在网上找到的大部分支持都是指 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()
}
}

结果

该示例产生以下结果:

Window with a list, scrolled to the bottom

关于qt - 如何以编程方式将 ScrollView 滚动到底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64447162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com