如何自动隐藏ApplicatioWindow menuBar?

时间:2014-12-04 17:03:59

标签: qt qml

我希望ApplicationWindow有一个自动隐藏menuBar,当鼠标光标位于窗口的最上部时显示。这在QML中是否可行?

PS:我使用的是Qt 5.3。

提前致谢。

2 个答案:

答案 0 :(得分:5)

您可以利用内部属性,即以" __"开头的属性。由于它们是内部的,因此即使IMO在这种情况下不太可能,在未来版本中功能也可能会中断。

通过使用内部属性,您可以利用__contentItem MenuBar的图形容器,并为其属性设置动画以获得所需的结果。这是一种可能的方法;它适用于Qt 5.3 / Qt 5.4 / Qt 5.5(我可以测试它的那些):

ApplicationWindow {
    id: app
    visible: true
    width: 400
    height: 300

    property real hideValue: 0
    Behavior on hideValue {
        NumberAnimation {duration: 200}
    }

    menuBar:  MenuBar {
        id: menu
        //__contentItem.scale: value                        // (1)
        //__contentItem.opacity: hideValue                  // (2)
        __contentItem.transform: Scale {yScale: hideValue}  // (3)

        Menu {
            id: m1
            title: "File"
            MenuItem { text: "Open..."
                onTriggered: {
                   hideValue = 0                            // hide the bar
                }
            }
            MenuItem { text: "Close"
                onTriggered: {
                   hideValue = 0                            // hide the bar
                }
            }
        }
    }


    Button{
        id: b1
        anchors.centerIn: parent
        text: "CLICK ME!"
        width: 100
        height: 100
    }

    MouseArea {
        id: ma1
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        height: menu.__contentItem.implicitHeight
        hoverEnabled: true

        onEntered: {
            hideValue = 1                            // show the bar
        }
    }

    MouseArea {
        id: ma2
        anchors.fill: parent
        hoverEnabled: true
        z: -1

        onEntered: {
            m1.__dismissMenu()
            hideValue = 0                            // hide the bar
        }
    }
}

总结代码:

  • 定义了两个MouseAreama1,其中包含填充MenuBar的{​​{1}}和ma2。后者有一个ApplicationWindow否定位于位于窗口的任何其他元素下,包含z:这样它就不会干扰与添加的任何元素相关的事件(例如示例按钮ma1)。
  • b1将名为ma1的属性设置为hideValue,而1将其恢复为ma2。该属性在0的可视属性上使用(请参阅代码中的__contentItem(1)(2))以隐藏/显示(3)。对MenuBar属性的简单Behaviour可确保转换顺利进行。
  • 内部功能hideValue用于确保在__dismissMenu()失去焦点时关闭已打开的Menu
  • 触发MenuBar时,会立即重置MenuItem属性以确保正确隐藏。

答案 1 :(得分:1)

我设法用这段代码获得了一些结果:

ApplicationWindow {
    id: app

    MenuBar {
        id: menu
        Menu {
            title: "Menu 1"
            MenuItem {
                text: "item 1"
            }
            MenuItem {
                action: "item 2"
            }
        }
    }

    MouseArea {
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        height: 20
        hoverEnabled: true

        onEntered: {
            if (app.menuBar === menu)
                app.menuBar = null;
            else
                app.menuBar = menu;
        }
    }
}

然而,当隐藏栏时尝试访问null.__contentItem时,更改突然发生并且QML调试报告错误。当然,代码中的绝对大小可能会导致问题。