Python 在PyQt QAction菜单中右对齐QKeySequence
如何正确证明PyQt5中的QKeySequencePython 在PyQt QAction菜单中右对齐QKeySequence,python,pyqt,pyqt5,qmenu,qkeysequence,Python,Pyqt,Pyqt5,Qmenu,Qkeysequence,如何正确证明PyQt5中的QKeySequence copy_absolute_path_action = ( create_action(self, _("Copy Absolute Path"), QKeySequence( get_shortcut('explorer', 'copy absolute path')), triggered=self.copy_absolute_path)) copy_relative_path_a
copy_absolute_path_action = (
create_action(self, _("Copy Absolute Path"), QKeySequence(
get_shortcut('explorer', 'copy absolute path')),
triggered=self.copy_absolute_path))
copy_relative_path_action = (
create_action(self, _("Copy Relative Path"), QKeySequence(
get_shortcut('explorer', 'copy relative path')),
triggered=self.copy_relative_path))
copy_file_clipboard_action = (
create_action(self, _("Copy File to Clipboard"),
QKeySequence(get_shortcut('explorer', 'copy file')),
icon=ima.icon('editcopy'),
triggered=self.copy_file_clipboard))
save_file_clipboard_action = (
create_action(self, _("Paste File from Clipboard"),
QKeySequence(get_shortcut('explorer', 'paste file')),
icon=ima.icon('editpaste'),
triggered=self.save_file_clipboard))
我希望快捷键右对齐,其余的保持不变
提前感谢在这种情况下,解决方案是实施QProxyStyle:
from PyQt5 import QtCore, QtGui, QtWidgets
class MenuProxyStyle(QtWidgets.QProxyStyle):
def drawControl(self, element, option, painter, widget=None):
shortcut = ""
if element == QtWidgets.QStyle.CE_MenuItem:
vals = option.text.split("\t")
if len(vals) == 2:
text, shortcut = vals
option.text = text
super(MenuProxyStyle, self).drawControl(element, option, painter, widget)
if shortcut:
margin = 10 # QStyleHelper::dpiScaled(5)
self.proxy().drawItemText(painter, option.rect.adjusted(margin, 0, -margin, 0),
QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter,
option.palette, option.state & QtWidgets.QStyle.State_Enabled,
shortcut, QtGui.QPalette.Text)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
menu = QtWidgets.QMenu("File", self)
self._proxy = MenuProxyStyle(menu.style())
menu.setStyle(self._proxy)
self.menuBar().addMenu(menu)
# create icons
data = [("Copy Absolute Path", "Ctrl+Alt+C"),
("Copy Relative Path", "Ctrl+Shift+C"),
("Copy File to Clipboard", "Ctrl+C")]
for text, shortcut in data:
action = QtWidgets.QAction(self,
text=text,
shortcut=QtGui.QKeySequence(shortcut))
menu.addAction(action)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
请不要使用pyqt4标记,因为pyqt4和PyQt5之间不完全兼容(我怀疑pyqt4没有解决方案,但PyQt5可能有解决方案)。太棒了,Genius,非常感谢。非常感谢您的帮助。这可以应用于上下文菜单吗??我不能让它在上下文菜单上工作@KhalilAlHooti我看到,在上下文菜单和shorcuts不再显示的情况下,您的建议非常有效。你知道我怎样才能保持原貌吗。建议的方法会更改颜色menus@KhalilAlHooti尝试将
self.\u proxy=MenuProxyStyle(menu.style())
更改为self.\u proxy=MenuProxyStyle(qtwidts.QApplication.style())
,如果它不起作用,那么您必须提供一个分析问题所在的方法,在我的情况下,我没有观察到问题