如何在 Qt/QML 6 的 MenuBar 项中添加快捷方式提示

问题描述 投票:0回答:1

我正在寻找一种方法,将菜单项的快捷方式提示添加到红色方块中,如图所示:

左边应该写着“使用指南”,右边写着“F1”。然而,在 Qt6 中我找不到方法来做到这一点,因为与 Qt5 相比,MenuItem 不再具有

shortcut
属性。

这是我的代码,没有显示快捷方式:

Menu {
    id: helpMenu
    title: "&Help"

    Action {
        text: "Usage guide"
        shortcut: "F1"
    }
}

但是,在菜单上使用委托,我可以强制它显示更多信息:

Menu {
    id: helpMenu
    title: "&Help"
    delegate: MenuItem {
        id: control

        contentItem: Rectangle {
            anchors.centerIn: parent

            Text {
                text: control.text
                anchors.left: parent.left
            }

            Text {
                text: "F1"
                anchors.right: parent.right
            }
        }
    }

    Action {
        text: "Usage guide"
        shortcut: "F1"
    }
}

但在这里我不知道如何将快捷方式从操作传递到委托中。它仅适用于文本。我可以对其中的文本进行硬编码,但这没有用。

qml pyside6 qt6
1个回答
0
投票

这基本上是您的解决方案,但使用 Shortcut标准键盘快捷键 转换为字符串。

import QtQuick
import QtQuick.Controls

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Menu {
        id: contextMenu
        title: "&Help"

        Action {
            text: "Usage guide"
            shortcut: "F1"
        }
        Action {
            text: "Cut"
            shortcut: StandardKey.Copy
        }
        Action {
            text: "Copy"
            shortcut: "Ctrl+E,Ctrl+W"
        }
        Action { text: "Paste" }

        delegate: MenuItem {
            id: control

            contentItem: Item {
                anchors.centerIn: parent

                Text {
                    text: control.text
                    anchors.left: parent.left
                    color: "white"
                }

                Shortcut {
                    id: shortcutHelper
                    sequence: control.action.shortcut
                }

                Text {
                    text: shortcutHelper.nativeText
                    anchors.right: parent.right
                    color: "white"
                }
            }
        }
    }

    Component.onCompleted: contextMenu.open()
}
© www.soinside.com 2019 - 2024. All rights reserved.