qml自定义菜单栏实现自由拖动

在使用qml开发过程中,有时候我们需要自己定制菜单栏并且也能自由拖动,本篇介绍qml定制菜单栏实现自由拖动。下面是代码实现:

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("自定义标题栏实现拖动")

    //color: "transparent"
    flags: Qt.Window | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.FramelessWindowHint

    property int windowX //用来存储主窗口x坐标
    property int windowY //存储窗口y坐标
    property int xMouse //存储鼠标x坐标
    property int yMouse //存储鼠标y坐标
    //标题栏
    Rectangle {
        id: titleBar
        height: 48
        width: parent.width - 96
        color: "#CFD2DC"
        anchors.top: parent.top
        anchors.left: parent.left
        Text {
            id: titleText
            text: qsTr("自定义标题栏实现拖动")
            anchors.centerIn: parent
        }

        MouseArea { //为窗口添加鼠标事件
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton //只处理鼠标左键
            property point clickPos: "0,0"
            onPressed: { //接收鼠标按下事件
                clickPos = Qt.point(mouse.x, mouse.y)
            }
            onPositionChanged: { //鼠标按下后改变位置
                //鼠标偏移量
                var delta = Qt.point(mouse.x-clickPos.x, mouse.y-clickPos.y)

                window.setX(window.x+delta.x)
                window.setY(window.y+delta.y)

            }
        }
    }

    //关闭按钮
    MouseArea{
        id: imgWinClose
        hoverEnabled: true
        cursorShape: Qt.PointingHandCursor
        anchors.top: parent.top
        anchors.right: parent.right
        width: 48
        height: 48

        Rectangle{
            anchors.fill: parent
            color: parent.containsMouse ? "#FF3E3D" : "#00000000"
        }

        Image{
            z: 1
            anchors.centerIn: parent
            sourceSize.width: 48
            sourceSize.height: 48
            source: parent.containsMouse ? "qrc:/image/button_close.svg" : "qrc:/image/button_close.svg"
        }

        onClicked: {
            console.log("close window================")
            close()
        }
    }
    //最小化按钮
    MouseArea{
        id: imgWinMini
        hoverEnabled: true
        cursorShape: Qt.PointingHandCursor
        anchors.top: parent.top
        anchors.right: parent.right
        anchors.rightMargin: 48
        width: 48
        height: 48

        Rectangle{
            anchors.fill: parent
            color: parent.containsMouse ? "#CFD2DC" : "#00000000"
        }

        Image{
            z: 1
            anchors.centerIn: parent
            sourceSize.width: 48
            sourceSize.height: 48
            source: parent.containsMouse ? "qrc:/image/button_minimize.svg" : "qrc:/image/button_minimize.svg"
        }

        onClicked: {
            console.log("max window================")
            showMinimized()
        }
    }
}

运行结果

qml自定义菜单栏实现自由拖动_第1张图片

 

你可能感兴趣的:(qml,qml)