KeyEvent in MainWindow (PyQt4)

[亡魂溺海] 提交于 2021-02-16 11:40:15

问题


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_())

回答1:


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



回答2:


I had a similar problem, but I had the need of not changing the structure of the generated python script from the .ui file.

So a simple approach for this was adding the following in the def setupUI

MainWindow.keyPressEvent = self.newOnkeyPressEvent

And then create your own keypress function in the Ui_MainWindow class

def newOnkeyPressEvent(self,e):
if e.key() == QtCore.Qt.Key_Escape:
    print "User has pushed escape"


来源:https://stackoverflow.com/questions/14278735/keyevent-in-mainwindow-pyqt4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!