我正在寻找一种方法,将菜单项的快捷方式提示添加到红色方块中,如图所示:
左边应该写着“使用指南”,右边写着“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"
}
}
但在这里我不知道如何将快捷方式从操作传递到委托中。它仅适用于文本。我可以对其中的文本进行硬编码,但这没有用。
这基本上是您的解决方案,但使用 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()
}