Подтвердить что ты не робот

Как создать полосу прокрутки в QtQuick 2.0?

Я пытаюсь создать полосу прокрутки в QtQuick 2.0,

Я обнаружил, что компонент Scrollbar доступен в QtQuick 1.0, но я не могу найти такой компонент в QtQuick 2.0. Как создать полосу прокрутки для ListView в QtQuick 2.0?

Любая помощь? Спасибо заранее.

4b9b3361

Ответ 1

ScrollBar/ScrollIndicator легко сделать, и код будет идентичным в QQ1 или QQ2 (кроме импорта):

/////////ScrollBar.qml//////////////

import QtQuick 2.0;

Item {
    id: scrollbar;
    width: (handleSize + 2 * (backScrollbar.border.width +1));
    visible: (flickable.visibleArea.heightRatio < 1.0);
    anchors {
        top: flickable.top;
        right: flickable.right;
        bottom: flickable.bottom;
        margins: 1;
    }

    property Flickable flickable               : null;
    property int       handleSize              : 20;

    function scrollDown () {
        flickable.contentY = Math.min (flickable.contentY + (flickable.height / 4), flickable.contentHeight - flickable.height);
    }
    function scrollUp () {
        flickable.contentY = Math.max (flickable.contentY - (flickable.height / 4), 0);
    }

   Binding {
        target: handle;
        property: "y";
        value: (flickable.contentY * clicker.drag.maximumY / (flickable.contentHeight - flickable.height));
        when: (!clicker.drag.active);
    }
    Binding {
        target: flickable;
        property: "contentY";
        value: (handle.y * (flickable.contentHeight - flickable.height) / clicker.drag.maximumY);
        when: (clicker.drag.active || clicker.pressed);
    }
    Rectangle {
        id: backScrollbar;
        radius: 2;
        antialiasing: true;
        color: Qt.rgba(0.5, 0.5, 0.5, 0.85);
        border {
            width: 1;
            color: "darkgray";
        }
        anchors { fill: parent; }

        MouseArea {
            anchors.fill: parent;
            onClicked: { }
        }
    }
    MouseArea {
        id: btnUp;
        height: width;
        anchors {
            top: parent.top;
            left: parent.left;
            right: parent.right;
            margins: (backScrollbar.border.width +1);
        }
        onClicked: { scrollUp (); }

        Text {
            text: "V";
            color: (btnUp.pressed ? "blue" : "black");
            rotation: -180;
            anchors.centerIn: parent;
        }
    }
    MouseArea {
        id: btnDown;
        height: width;
        anchors {
            left: parent.left;
            right: parent.right;
            bottom: parent.bottom;
            margins: (backScrollbar.border.width +1);
        }
        onClicked: { scrollDown (); }

        Text {
            text: "V";
            color: (btnDown.pressed ? "blue" : "black");
            anchors.centerIn: parent;
        }
    }
    Item {
        id: groove;
        clip: true;
        anchors {
            fill: parent;
            topMargin: (backScrollbar.border.width +1 + btnUp.height +1);
            leftMargin: (backScrollbar.border.width +1);
            rightMargin: (backScrollbar.border.width +1);
            bottomMargin: (backScrollbar.border.width +1 + btnDown.height +1);
        }

        MouseArea {
            id: clicker;
            drag {
                target: handle;
                minimumY: 0;
                maximumY: (groove.height - handle.height);
                axis: Drag.YAxis;
            }
            anchors { fill: parent; }
            onClicked: { flickable.contentY = (mouse.y / groove.height * (flickable.contentHeight - flickable.height)); }
        }
        Item {
            id: handle;
            height: Math.max (20, (flickable.visibleArea.heightRatio * groove.height));
            anchors {
                left: parent.left;
                right: parent.right;
            }

            Rectangle {
                id: backHandle;
                color: (clicker.pressed ? "blue" : "black");
                opacity: (flickable.moving ? 0.65 : 0.35);
                anchors { fill: parent; }

                Behavior on opacity { NumberAnimation { duration: 150; } }
            }
        }
    }
}

Чтобы использовать его:

import QtQuick 2.0;

Rectangle {
    width: 400;
    height: 300;

    ListView {
        id: list;
        anchors.fill: parent;
        model: 100;
        delegate: Rectangle {
            height: 50;
            width: parent.width;
            color: (model.index %2 === 0 ? "darkgray" : "lightgray");
        }
    }
    ScrollBar {
        flickable: list;
    }
}

Наслаждайтесь!

Ответ 2

Любил решение TheBootroo (+1 для него!), Но нашел его решение только несколько дней назад, после комментария к недавнему вопросу. Между тем, я самостоятельно разработал свой проект для проекта, над которым я работал, и я собираюсь поделиться таким решением здесь. Надеюсь, что это может быть полезно. :)

Моя полоса прокрутки имеет (своего рода) "ощущение OS X" (предназначено), например, это не включает прокручивающиеся стрелки на сторонах.

Вот код:

import QtQuick 2.0

Item {
   id: scrollbar

    property Flickable flk : undefined
    property int basicWidth: 10
    property int expandedWidth: 20
    property alias color : scrl.color
    property alias radius : scrl.radius

    width: basicWidth
    anchors.right: flk.right;
    anchors.top: flk.top
    anchors.bottom: flk.bottom

    clip: true
    visible: flk.visible
    z:1

    Binding {
        target: scrollbar
        property: "width"
        value: expandedWidth
        when: ma.drag.active || ma.containsMouse
    }
    Behavior on width {NumberAnimation {duration: 150}}

    Rectangle {
        id: scrl
        clip: true
        anchors.left: parent.left
        anchors.right: parent.right
        height: flk.visibleArea.heightRatio * flk.height
        visible: flk.visibleArea.heightRatio < 1.0
        radius: 10
        color: "gray"

        opacity: ma.pressed ? 1 : ma.containsMouse ? 0.65 : 0.4
        Behavior on opacity {NumberAnimation{duration: 150}}

        Binding {
            target: scrl
            property: "y"
            value: !isNaN(flk.visibleArea.heightRatio) ? (ma.drag.maximumY * flk.contentY) / (flk.contentHeight * (1 - flk.visibleArea.heightRatio)) : 0
            when: !ma.drag.active
        }

        Binding {
            target: flk
            property: "contentY"
            value: ((flk.contentHeight * (1 - flk.visibleArea.heightRatio)) * scrl.y) / ma.drag.maximumY
            when: ma.drag.active && flk !== undefined
        }

        MouseArea {
            id: ma
            anchors.fill: parent
            hoverEnabled: true
            drag.target: parent
            drag.axis: Drag.YAxis
            drag.minimumY: 0
            drag.maximumY: flk.height - scrl.height
            preventStealing: true
        }
    }
}

А вот код для его использования. Все поля являются необязательными, ожидаемо для flickable, очевидно. Установленные значения являются значениями по умолчанию:

ScrollBar {
    flk: privacyFlick
    radius: 10          // Optional
    basicWidth: 10      // Optional
    expandedWidth: 20   // Optional
    color: "grey"       // Optional
}

Ответ 4

Qt 5.6 вводит новые элементы управления в качестве технического предварительного просмотра "Qt Labs Controls". Среди прочего, элементы управления вводят встроенный ScrollBar тип (интерактивный) и ScrollIndicator (не интерактивный).

В Qt 5.7 новые элементы управления вышли из технического предварительного просмотра и теперь переименованы в "Quick Controls 2", чтобы подчеркнуть тот факт, что они превосходят предыдущие элементы управления.

Если вы используете Qt 5.6, который является версией LTS и будет примерно в течение некоторого времени, ScrollBar можно использовать следующим образом:

import QtQuick 2.6
import Qt.labs.controls 1.0
import QtQuick.Window 2.2

ApplicationWindow {
    visible: true
    width: 400
    height: 600

    Flickable {
        anchors.fill: parent
        contentWidth: image.width
        contentHeight: image.height

        //ScrollIndicator.vertical: ScrollIndicator { }  // uncomment to test
        ScrollBar.vertical: ScrollBar { }
        ScrollBar.horizontal: ScrollBar { }

        Image {
            id: image
            source: "http://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg"
        }
    }
}

В то время как в Qt 5.7 и далее вы можете использовать ScrollBar или ScrollIndicator следующим образом:

import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Window 2.2

ApplicationWindow {
    visible: true
    width: 600
    height: 300

    Flickable {
        anchors.fill: parent
        contentWidth: image.width
        contentHeight: image.height

        ScrollIndicator.vertical: ScrollIndicator { }
        //ScrollBar.vertical: ScrollBar { }       // uncomment to test    

        Image {
            id: image
            source: "http://s-media-cache-ak0.pinimg.com/736x/92/9d/3d/929d3d9f76f406b5ac6020323d2d32dc.jpg"
        }
    }
}

Синтаксис использования почти одинаковый, тогда как основной код рефакторинга имеет место в коде стилизации, как это видно из примера. Labs Controls ScrollIndicator страница настройки по сравнению с Quick Controls 2 ScrollIndicator страница настройки.