由于我当前正在将gui应用程序从Python 2.7.14 / PySide 1.2.4移植到Python 3.7.1 / PySide2 5.11.2,因此我遇到了快捷方式问题。基本上:
QShortcuts
上使用Qt.ApplicationShortcut
上下文设置QDesktopWidget
在PySide2中似乎无法正常工作,而在PySide中则很好。好像其他人encountered the same issue too。
# -*- coding: utf-8 -*-
"""Test application wide shortcut on desktop widget fails in PySide2."""
import logging
from datetime import datetime
from PySide2.QtCore import Qt
from PySide2.QtGui import QKeySequence
from PySide2.QtWidgets import QShortcut, QWidget, QApplication
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class Widget(QWidget):
"""Widget with application wide shortcut."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
shortcut = QShortcut(QKeySequence(Qt.Key_H), QApplication.desktop())
shortcut.setContext(Qt.ApplicationShortcut)
shortcut.activated.connect(self.handler)
def handler(self):
"""Shortcut does not trigger."""
msg = f"{datetime.now()}"
logger.info(msg)
# run
app = QApplication()
widget = Widget()
widget.show()
app.exec_()
# -*- coding: utf-8 -*-
"""Test application wide shortcut on desktop widget succeeds in PySide."""
import logging
from datetime import datetime
from PySide.QtCore import Qt
from PySide.QtGui import QKeySequence, QShortcut, QWidget, QApplication
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class Widget(QWidget):
"""Widget with application wide shortcut."""
def __init__(self, *args, **kwargs):
super(Widget, self).__init__(*args, **kwargs)
shortcut = QShortcut(QKeySequence(Qt.Key_H), QApplication.desktop())
shortcut.setContext(Qt.ApplicationShortcut)
shortcut.activated.connect(self.handler)
def handler(self):
"""Shortcut does trigger."""
msg = "{}".format(datetime.now())
logger.info(msg)
# run
app = QApplication(tuple())
widget = Widget()
widget.show()
app.exec_()
ApplicationHotkeyHandler
,它是一个QObject
,它定义了应用程序范围内的所有快捷方式。QDesktopWidget
上注册为应用程序范围的快捷方式,它是Qt基础结构的一部分,似乎是一种仅出于此目的而创建无形,人工小部件的优雅安全的方法保留应用程序快捷方式的方法。以下是应用程序外观的要点:
class ApplicationHotkeyHandler(QObject):
"""Define application wide hotkeys and their handlers here. Shortcuts are
placed on QDesktopWidget which is an always available part of the Qt
infrastructure.
Notes:
This is a QObject for signals and parenting but not a QWidget
as we don't have to display anything, so the handler instance cannot
serve as parent for QShortcuts.
"""
@hotkey(QKeySequence(Qt.CTRL + Qt.Key_Q), context=Qt.ApplicationShortcut,)
def quit(self):
QApplication.instance().quit()
...