Qt Quick Controls 2.14如何设置ScrollView的样式

问题描述

不清楚如何设置QML ScrollView的样式。
我想让ScrollView具有以下样式,但将错误style作为无效属性

import QtQuick 2.0
import QtQuick.Controls 2.14
import QtQuick.Controls.Styles 1.4

ScrollView {
    style: ScrollViewStyle {
        handle: Rectangle {
            implicitWidth: 50
            implicitHeight: 30
            color: "red"
        }
        scrollBarBackground: Rectangle {
            implicitWidth: 50
            implicitHeight: 30
            color: "black"
        }
        decrementControl: Rectangle {
            implicitWidth: 50
            implicitHeight: 30
            color: "green"
        }
        incrementControl: Rectangle {
            implicitWidth: 50
            implicitHeight: 30
            color: "blue"
        }
    }
    //...
}

更新

import QtQuick 2.0
import QtQuick.Controls 2.14

ScrollView {
    id: myScrollView
    width: 700
    height: parent.height
    clip: true

    ScrollBar.vertical: ScrollBar {
        id: scrollBar
        parent: myScrollView.parent
        policy: ScrollBar.AlwaysOn
        anchors.top: myScrollView.top
        anchors.left: myScrollView.right
        anchors.bottom: myScrollView.bottom
        height: myScrollView.availableHeight

        contentItem: Rectangle {
            implicitWidth: 16
            implicitHeight: 10
            anchors.leftMargin: 10

            radius: 16
            color: "blue"
        }
    }

    ListView {
        id: myListView
        anchors.fill: parent

    .... Rest of the code ....

使用上面的代码,我可以获得垂直滚动条的样式,但是使用此代码,我看到了两个滚动条。按照上述样式,一种是浅灰色,尺寸很小,另一种是蓝色。

蓝色滚动条的高度也不符合样式。

解决方法

您正在将Qt Quick Controls 1与Qt Quick Controls 2混淆。QQC2不使用style属性。这是docs。 ScrollView的基本思想是可以更改background以及附加的ScrollBar

ScrollView {
    background: ... // This changes what's drawn in the background

    ScrollBar.vertical: ScrollBar { ... }
    ScrollBar.horizontal: ScrollBar { ... }
}

ScrollBar本身也可以通过更改backgroundcontentItem进行自定义。

ScrollBar {
    background: ... // Change the background of the scrollbar
    contentItem: ... // Change the scroll indicator
}

更新:实际上,我看到的与您尝试时所做的相同。我只是关注文档,所以也许那里有一个Qt错误。好消息是,因为您只是尝试滚动ListView,所以实际上ScrollView是不必要的。您可以这样做:

    ListView {
        id: listView
        width: 200
        height: 200
        model: 100
        clip: true
        delegate: ItemDelegate {
            text: modelData
        }

        ScrollBar.vertical: ScrollBar {
            background: Rectangle { color: "red" }
            contentItem: Rectangle { implicitWidth: 10; implicitHeight: 10; color: "blue" }
        }
    }

这一次我自己尝试过,并且有效。