![](/img/trans.png)
[英]Matplotlib inline in Jupyter - how to contol when the plot is shown?
[英]How to contol KeyEvent in Qt
使用以CustomWidget作為超類聲明的窗口: class App(CustomWidget)
按下Alt + A會正確打印“ keyPressEvent:Alt + a”消息。
但是,當使用setCentralWidget()將CustomWidget分配到窗口或使用layer.addWidget(widget)設置CustomKey時,KeyEvent功能將被破壞。 代碼中缺少什么?
from PyQt4 import QtCore, QtGui
class CustomWidget(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent=parent)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.AltModifier:
if event.key() == QtCore.Qt.Key_A:
print 'keyPressEvent: Alt + a'
# super(CustomWidget, self).keyPressEvent(event)
class App(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent=parent)
centralWidget = CustomWidget(self)
self.setCentralWidget(centralWidget)
mainLayout=QtGui.QVBoxLayout()
centralWidget.setLayout(mainLayout)
widget = CustomWidget(self)
mainLayout.addWidget(widget)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = App()
w.show()
sys.exit(app.exec_())
小部件必須具有焦點才能接收事件。 確保在創建窗口后調用setFocusPolicy()以使CustomWidget接受並保持焦點。
重要提示:在GroupBox的keyPressEvent()方法末尾,我們必須將Event傳遞給上級。 否則事件將不會傳播到父窗口小部件: super(QtGui.QGroupBox, self).keyPressEvent(event)
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent):
QtGui.QMainWindow.__init__(self, parent=parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.ControlModifier:
if event.key() == QtCore.Qt.Key_T:
print 'MainWindow: Control + t'
if event.key() == QtCore.Qt.Key_M:
print 'MainWindow: Control + m'
class GroupBox(QtGui.QGroupBox):
def __init__(self, parent=None):
QtGui.QGroupBox.__init__(self, parent=parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.ControlModifier:
if event.key() == QtCore.Qt.Key_T:
print 'GroupBox: Control + t'
if event.key() == QtCore.Qt.Key_S:
print 'GroupBox: Control + s'
super(QtGui.QGroupBox, self).keyPressEvent(event)
class App(MainWindow):
def __init__(self, parent=None):
MainWindow.__init__(self, parent=parent)
centralWidget = QtGui.QWidget(self)
self.setCentralWidget(centralWidget)
mainLayout=QtGui.QVBoxLayout()
centralWidget.setLayout(mainLayout)
groupBox = GroupBox(self)
mainLayout.addWidget(groupBox)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = App()
w.show()
sys.exit(app.exec_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.