1. 程式人生 > >怎麼在Ubuntu QML應用中偵測到Swipe手勢

怎麼在Ubuntu QML應用中偵測到Swipe手勢

/* This code was written by Sergejs Kovrovs and has been placed in the public domain. */

import QtQuick 2.0

Item {
    id: root
    width: 480
    height: 320

    property var itemData: ["#22eeeeee", "#22bbbbbb", "#22888888", "#22555555", "#22222222"]
    property int currentIndex: 0

    onCurrentIndexChanged: {
        slide_anim.to = - root.width * currentIndex
        slide_anim.start()
    }

    PropertyAnimation {
        id: slide_anim
        target: content
        easing.type: Easing.OutExpo
        properties: "x"
    }

    Image {
        id: img
        anchors.verticalCenter: root.verticalCenter
        source: "images/wallpaper.jpg"
        fillMode: Image.PreserveAspectCrop
    }

    Item {
        id: content
        width: root.width * itemData.length
        property double k: (content.width - root.width) / (img.width - root.width)
        onXChanged: {
            img.x = x / k
//            console.log("img.x: " + img.x );
        }
        Repeater {
            model: itemData.length
            Rectangle {
                x: root.width * index
                width: root.width; height: root.height
                color: itemData[index]
                Text { text: index+1; anchors.centerIn: parent; font.pointSize: 100; color: "#88000000" }
            }
        }
    }

    SwipeArea {
        id: mouse
        anchors.fill: parent
        onMove: {
            content.x = (-root.width * currentIndex) + x
//            console.log("content.x " + content.x);
        }
        onSwipe: {
            switch (direction) {
            case "left":
                if (currentIndex === itemData.length - 1) {
                    currentIndexChanged()
                }
                else {
                    currentIndex++
                }
                break
            case "right":
                if (currentIndex === 0) {
                    currentIndexChanged()
                }
                else {
                    currentIndex--
                }
                break
            }
        }
        onCanceled: {
            currentIndexChanged()
        }
    }

    Row {
        anchors { bottom: parent.bottom; bottomMargin: 16; horizontalCenter: parent.horizontalCenter }
        spacing: 16
        Repeater {
            model: itemData.length
            Rectangle {
                width: 12; height: 12; radius: 6
                color: currentIndex === index ? "#88ffffff" : "#88000000"
                border { width: 2; color: currentIndex === index ? "#33000000" : "#11000000" }
            }
        }
    }
}
就像我們正常情況下使用MouseArea的情況一樣,我們可以在我們需要偵測滑動的地方使用SwipeArea。這樣,我們只需要捕獲SwipeArea中發出的訊號: