QML之侧滑抽屉(菜单)

可以用两种方式实现抽屉效果,一种是使用动画,一种是直接使用抽屉控件(Drawer)。

效果

这里写图片描述

区别

1、使用动画更加灵活,更方便自定义动画效果
2、使用动画实现的抽屉需要依靠其Z属性确定其所在哪一层,Drawer弹出时在最上层
3、Drawer继承自Popup,可以设置为模态和非模态,可以方便设置其关闭方式
4、动画使用start()和stop()打开关闭,Drawer使用open()和close()打开关闭

代码

动画抽屉

Button {
        x: 270
        y: 133
        text: qsTr("动画抽屉")
        onClicked: {
            if(menuRect.x === 640)
            {
                menuStartAnim.start()
            }
            else
            {
                menuStopAnim.start()
            }
        }
    }
    //组合动画
    ParallelAnimation{
        id: menuStartAnim
        //属性动画
        NumberAnimation{
            target: menuRect
            properties: "x"
            from: 640
            to: 440
            //动画持续时间,毫秒
            duration: 500
            //动画渐变曲线
            easing.type: Easing.OutQuad
        }
        NumberAnimation{
            target: menuRect
            properties: "opacity"
            from: 0.2
            to: 0.8
            duration: 500;
            easing.type: Easing.OutQuad
        }
    }
    ParallelAnimation{
        id: menuStopAnim
        NumberAnimation{
            target: menuRect
            properties: "x"
            from: 440
            to: 640
            duration: 500;
            easing.type: Easing.Linear
        }
        NumberAnimation{
            target: menuRect
            properties: "opacity"
            from: 0.8
            to: 0.2
            duration: 500;
            easing.type: Easing.Linear
        }
    }

    Rectangle {
        id: menuRect
        x: 640
        y: 0
        width: 200
        height: 480
        color: "lightblue"
        radius: 5
    }

Drawer

Button {
        id: button
        x: 270
        y: 209
        text: qsTr("LeftDrawer")
        onClicked: {
            if(drawer.visible)
            {
                drawer.close()
            }
            else
            {
                drawer.open()
            }
        }
    }

    Drawer {
        id: drawer
        width: 200
        height: 640
        modal: true
        clip: true
        //抽屉起始方向
        edge: Qt.LeftEdge
        closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside

        background: Rectangle{
            anchors.fill: parent
            color: "#616161"
            opacity: 0.8
        }
    }

猜你喜欢

转载自blog.csdn.net/zbw1185/article/details/81087875