兼容Qt4/Qt5版本Qml控件ScrollBar

小编:啊南 179阅读 2021.01.18

1. ScrollBar演示2. 对外属性
  • 继承于Rectangle;
  • target属性继承于Flickable(默认值父控件);
  • orientation设置控件水平还是垂直方向(默认值垂直方向).

ScrollBar.qml

import QtQuick 2.0

Rectangle {
    id: root

    property Flickable target: parent // parent: Flickable
    property int orientation: Qt.Vertical
/*
    orientation : enumeration
    This property holds the orientation of the scroll bar.
    Possible values:
    |Constant     |Description|
    |Qt.Horizontal|Horizontal|
    |Qt.Vertical  |Vertical(default)|
*/

    width: orientation == Qt.Vertical ? 15 : target.width
    height: orientation == Qt.Vertical ? target.height : 15
    color: "white"
    opacity: 0.3
    radius: 5

    Rectangle {
        y: orientation == Qt.Vertical ? target.visibleArea.yPosition * target.height : 0
        x: orientation == Qt.Vertical ? 0 : target.visibleArea.xPosition * target.width
        width: orientation == Qt.Vertical ? parent.width :
                                            target.visibleArea.widthRatio * target.width
        height: orientation == Qt.Vertical ? target.visibleArea.heightRatio * target.height :
                                             parent.height
        color: "black"
        radius: root.radius
        opacity: 0.7
    }
}
3. 使用示例3.1 图片显示器
import QtQuick 2.0
import "../"

Rectangle {
    anchors.fill: parent

    Flickable {
        id: view
        anchors.fill: parent
        contentWidth: picture.width
        contentHeight: picture.height

        Image {
            id: picture
            source: "Test.png"
            asynchronous: true
        }
    }


    ScrollBar {
        target: view
    }

    ScrollBar {
        target: view
        orientation: Qt.Horizontal
    }
}
3.2 ListView附加滚动条
import QtQuick 2.0
import "../"

ListView {
    anchors.fill: parent

    model: 10
    delegate: Rectangle {
        width: parent.width; height: 100
        color: "lightblue"
        Text {
            anchors.centerIn: parent
            text: index
        }
    }

    ScrollBar { }
}
4. 注意事项
  • 在Qt4下使用需要将QtQuick 2.x改为QtQuick 1.x
关联标签: