user6226614
user6226614

Reputation:

How to change the page to the next or previous item of a SwipeView by clicking on the right and left arrow respectively?

I have a SwipeView that loads its internal elements through a Repeater and a Loader.

enter image description here

I would like to swipe between the items forward and backward by just clicking the arrows on the right and left of the SwipeView. How can I implement this behavior in QML?

SwipeView {
            id: __swipeView
            Layout.fillHeight: true
            Layout.fillWidth: true
            Repeater {
                model: 3
                Loader {
                    source: "qrc:/../SwipeDelegate.qml"
                }
            }
        }

Upvotes: 1

Views: 4162

Answers (1)

Mitch
Mitch

Reputation: 24406

Within your delegate, you can access the SwipeView via the SwipeView attached property, and then increment or decrement the current index as necessary:

import QtQuick 2.6
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    SwipeView {
        anchors.fill: parent

        Repeater {
            model: 3

            Item {
                id: delegate

                Button {
                    text: "<"
                    enabled: index > 0
                    onClicked: delegate.SwipeView.view.decrementCurrentIndex()
                    anchors.left: parent.left
                    anchors.verticalCenter: parent.verticalCenter
                }

                Label {
                    text: "Page " + (index + 1)
                    anchors.centerIn: parent
                }

                Button {
                    text: ">"
                    enabled: index < delegate.SwipeView.view.count - 1
                    onClicked: delegate.SwipeView.view.incrementCurrentIndex()
                    anchors.right: parent.right
                    anchors.verticalCenter: parent.verticalCenter
                }
            }
        }
    }
}

It's important to use the functions as opposed to setting currentIndex directly, for the reasons described here.

Upvotes: 1

Related Questions