1、自动添加日志消息到底部并滚动至最底部
2、向上滑动查看之前消息时停止滚动
3、勾选开始自动滚动或者滑动至底部开始自动滚动
import QtQuick 2.15
import QtQuick.Controls 2.4
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Log Viewer"
CheckBox {
id: autoScrollCheckBox
text: "Auto Scroll"
checked: logView.autoScroll
anchors.bottom: logItem.top
anchors.right: logItem.right
onCheckedChanged: {
logView.autoScroll = checked;
}
}
Rectangle {
id: logItem
height: 200
width: 300
color: "#f0f0f0"
anchors.centerIn: parent
ListView {
id: logView
anchors.fill: parent
clip: true
flickableDirection: Flickable.VerticalFlick // 确保只能垂直滚动
boundsBehavior: Flickable.StopAtBounds // 在边界处停止滚动
property bool autoScroll: true // 自定义属性,用于控制是否自动滚动
ScrollBar.vertical: ScrollBar {
// 竖向滚动条的配置
active: true // 设置为激活状态,或根据需要进行显示或隐藏
}
model: ListModel {
id: logModel
ListElement { text: "Log entry 1" }
ListElement { text: "Log entry 2" }
ListElement { text: "Log entry 3" }
// Initial log entries
}
delegate: Text {
text: model.text
padding: 10
}
onContentYChanged: {
if (logView.flicking || logView.moving) {
logView.autoScroll = false;
}
// 检查是否滚动到了底部
if (logView.contentY >= logView.contentHeight - logView.height) {
logView.autoScroll = true;
}
}
Timer {
interval: 1000 // 设置定时器的间隔为1000毫秒,即1秒
repeat: true // 设置定时器重复运行
running: true // 定时器开始运行
onTriggered: {
// 定时器触发时执行的操作
logModel.append({ text: "Automatic log entry at " + new Date().toLocaleTimeString() });
if (logView.autoScroll) {
// 确保滚动发生在项目被添加后
logView.positionViewAtIndex(logModel.count - 1, ListView.End)
}
}
}
}
}
}