I'm trying to to build a GUI with PyQt4 and control some actions with the arrow keys. Nevertheless I fail to get the keystrokes.
It have to be a simple issue, but I newbie to this. So any help will be appreciated. Thanks!
import sys
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(910, 500)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 240, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
def keyPressEvent(self, event):
key = event.key()
print(key)
if key == QtCore.Qt.Key_Left:
print('Left Arrow Pressed')
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
keyPressEvent
should be reimplemented in QWidget
. In this case, a subclass of QWidget
.
You shouldn't put it in a ui class.
class MyWindow(QtGui.QMainWindow):
def keyPressEvent(...
...
if __name__=='__main__':
...
window=MyWindow()
...
sys.exit(app.exec_()) # and don't forget to run the mainloop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With