以下是一个简单的 QML 分页导航实现示例:
import QtQuick 2.0
Rectangle {
id: root
width: 200
height: 50
color: "#f5f5f5"
border.color: "black"
border.width: 1
property int pageCount: 10 // 总页数
property int currentPage: 1 // 当前页码
property int visiblePages: 5 // 可见页码数量
function setPage(page) { // 跳转到指定页码
if (page < 1 || page > pageCount) return
currentPage = page
updatePageButtons()
}
function updatePageButtons() { // 更新所有按钮状态
var middleIndex = Math.floor(visiblePages / 2)
var firstIndex = currentPage - middleIndex
if (firstIndex < 1) firstIndex = 1
var lastIndex = firstIndex + visiblePages - 1
if (lastIndex > pageCount) lastIndex = pageCount
var emptyCount = visiblePages - (lastIndex - firstIndex + 1)
if (emptyCount % 2 != 0) {
if (firstIndex == 1) lastIndex += emptyCount
else firstIndex -= emptyCount
}
var buttons = []
for (var i = firstIndex; i <= lastIndex; i++) {
buttons.push(i)
}
pagesGrid.children = buttons.map(function(pageNumber) {
return PageButton {
text: pageNumber
active: pageNumber == currentPage
onClicked: setPage(pageNumber)
}
})
}
GridLayout {
id: pagesGrid
rows: 1
columns: visiblePages
anchors.centerIn: parent
spacing: 5
}
Component.onCompleted: updatePageButtons()
}
Component {
id: PageButton
property bool active: false
property int fontSize: 14
Text {
text: parent.text
font.pixelSize: parent.fontSize
color: parent.active ? "white" : "black"
background: Rectangle {
color: parent.active ? "#0078d7" : "transparent"
radius: 2
border.color: "#c8c8c8"
border.width: 1
}
padding: 5
onClicked: parent.onClicked()
}
}
使用示例:
PageNavigation {
pageCount: 10
currentPage: 3
visiblePages: 5
}
这将创建一个总页数为 10,当前页码为 3,可见页码数量为 5 的分页导航组件。