如何在 QML 中为 TableView 创建自定义滚动条?

Bib*_*bin 5 qt qt-creator tableview qml

我想在 TableView 中自定义 ScrollBar。
我可以在 ListView 和 GridView 中自定义 ScrollBar,但无法对 TableView 执行相同操作。

我发现这是因为GridView和ListView继承自Flickable而TableView继承自ScrollView。有什么替代方案吗?

TableView {
    id:songGrid
    TableViewColumn {
        role: "title"
        title: "Title"
        width: 100
    }
    TableViewColumn {
        role: "author"
        title: "Author"
        width: 200
    }


    ScrollBar.horizontal:  ScrollBar {
        id: scrollBar2
        anchors.bottom:  songGrid.bottom
        //            anchors.bottomMargin: 70*downscaleFactor
        width: 5
        active: true
        visible:songGrid.moving?true:false

        contentItem: Rectangle {
            id:contentItem_rect2
            width:100
            implicitHeight:4
            radius: implicitHeight/2
            color: "Red"
        }
    }

    model: libraryModel1
}


ListModel {
    id: libraryModel1
    ListElement {
        title: "A Masterpiece"
        author: "Gabriel"
    }
    ListElement {
        title: "Brilliance"
        author: "Jens"
    }
    ListElement {
        title: "Outstanding"
        author: "Frederik"
    }
}
Run Code Online (Sandbox Code Playgroud)

der*_*erM 3

您可以创建一个ScrollBar,将其放在您想要的任何位置。然后您以正确的方式将 绑定songGrid.flickableItem.contentX/Y到。ScrollBar.position如果TableView可以通过其他方式移动,那么在这种情况下ScrollBar您需要使用第二次Binding来更新position

这是一个简短的草图,其中我只说明了方向:(ScrollBar -> TableView将其添加到您的问题的代码中)。

Binding {
    target: songGrid.flickableItem
    property: "contentY"
    value: (songGrid.flickableItem.contentHeight + 16) * vbar.position - (16 * (1 - vbar.position))
}

ScrollBar {
    id: vbar
    z: 100
    orientation: Qt.Vertical
    anchors.top: songGrid.top
    anchors.left: songGrid.right
    anchors.bottom: songGrid.bottom
    active: true
    contentItem: Rectangle {
        id:contentItem_rect2
        radius: implicitHeight/2
        color: "Red"
        width: 10 // This will be overridden by the width of the scrollbar
        height: 10 // This will be overridden based on the size of the scrollbar
    }
    size: (songGrid.height) / (songGrid.flickableItem.contentItem.height)
    width: 10
}
Run Code Online (Sandbox Code Playgroud)

你可以看到那些神秘的 16东西Binding。这是需要的一些偏移量,可能是为了考虑水平滚动条。对于不同的样式/平台,这可能会有所不同。

如果您还有其他问题,请提出新问题。如果您只需要更多说明,请发表评论。