首页 > 解决方案 > QML SplitView 在把手鼠标释放时自动折叠

问题描述

我有一个 QML Controls 2 SplitView 和一个重新定义的句柄,效果很好,但我想检测处理程序上的鼠标释放事件,所以我可以在某个宽度阈值下折叠 SplitView。在现有手柄上添加 MouseArea 将吸收拖动事件,因此我无法移动手柄。知道如何收集鼠标释放事件或解决此问题的任何其他解决方案吗?

好的,我已经创建了一个示例应用程序。正如您在此示例中所看到的,我的 MouseArea 标记为黄色,并在双击时以编程方式折叠右视图,这很好,但我还想拖动把手,并且在某个宽度阈值下释放鼠标时,我想折叠视图为好。我的 MouseArea 没有覆盖车把的车把的黑色部分响应拖动,但由于我无法从中收集到信号,因此宽度阈值已经设置了 shouldCollapse 布尔属性,因此视图不会更新。也许我可以用计时器解决这个问题,但我需要一个更复杂的解决方案。

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
    width: 800
    height: 400
    visible: true

    SplitView {
        id: splitView
        anchors.fill: parent
        orientation: Qt.Horizontal

        function toggleCollapse() { collapsibleRect.shouldCollapse = !collapsibleRect.shouldCollapse }

        handle: Rectangle {
            implicitWidth: 20
            implicitHeight: 20
            color: "black"

            MouseArea {
                anchors.centerIn: parent
                width: parent.width
                height: parent.height / 2
                onDoubleClicked: splitView.toggleCollapse()
                Rectangle {
                    anchors.fill: parent
                    color: "yellow"
                    Text {
                        anchors.centerIn: parent
                        text: "Double click to collapse"
                        rotation: 90
                    }
                }
            }
        }

        Rectangle {
            id: mainRect
            color: "green"
            SplitView.fillWidth: true
            Text {
                anchors.centerIn: parent
                font.pixelSize: 24
                text: "Main scene"
            }
        }

        Rectangle {
            id: collapsibleRect
            property bool shouldCollapse: false
            SplitView.preferredWidth: shouldCollapse ? 0 : 300
            color: "purple"
            clip: true
            onWidthChanged: {
                if(width < 200) shouldCollapse = true
                else shouldCollapse = false
            }
            Text {
                anchors.centerIn: parent
                rotation: parent.shouldCollapse ? 90 : 0
                font.pixelSize: 24
                text: parent.shouldCollapse ? "SHOULD BE COLLAPSED" : "NOT COLLAPSED"
                Behavior on rotation { NumberAnimation { duration: 100 } }
            }
        }
    }
}

示例应用程序折叠状态

标签: qtqml

解决方案


将此添加到 MouseArea:

onPressed: {
    mouse.accepted = (mouse.flags & Qt.MouseEventCreatedDoubleClick);
}
propagateComposedEvents: true
cursorShape: Qt.SplitHCursor

推荐阅读