QT开发中文网

qml 实现分页导航

以下是一个简单的 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 的分页导航组件。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=948

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?