Reputation: 3917
I have a basic question about Qt and Mac OS X. If I define a QMainWindow
class and define a keyPressEvent
function as below, is it not supposed to enter this function whenever a key is pressed anywhere in the MyWindow
? I have some problems with it under Linux, where I do not get the keypress events if certain widgets were focused on (list views or edit boxes), but at least I get it if I focus on a button and then press a key. Under Mac OS X I do not get any response at all.
class MyWindow(QMainWindow):
def keyPressEvent(self, event):
key = event.key()
if key == Qt.Key_F:
print("pressed F key")
Any ideas (using Python with PySide)?
Upvotes: 3
Views: 3057
Reputation: 31620
Solution based on Pavel's answer:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class basicWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.edit = QLineEdit("try to type F", self)
self.eF = filterObj(self)
self.installEventFilter(self.eF)
self.edit.installEventFilter(self.eF)
self.show()
def test(self, obj):
print "received event", obj
class filterObj(QObject):
def __init__(self, windowObj):
QObject.__init__(self)
self.windowObj = windowObj
def eventFilter(self, obj, event):
if (event.type() == QEvent.KeyPress):
key = event.key()
if(event.modifiers() == Qt.ControlModifier):
if(key == Qt.Key_S):
print('standard response')
else:
if key == Qt.Key_F:
self.windowObj.test(obj)
return True
else:
return False
if __name__ == "__main__":
app = QApplication(sys.argv)
w = basicWindow()
sys.exit(app.exec_())
This answer was posted as an edit to the question OS X + Qt: How to capture all key-press events in the entire GUI? by the OP P.R. under CC BY-SA 3.0.
Upvotes: 0
Reputation: 40502
When an event is used by a widget (e.g. an edit box), it is usually not propagated to its parent widgets, so you can't get these events from the parent window. You should install an event filter on the main QApplication
object. This way you will receive (and filter if you want) all events.
See Event filters.
Upvotes: 6