本文介绍了主窗口中的 KeyEvent (PyQt4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PyQt4 构建 GUI 并使用箭头键控制一些操作.尽管如此,我还是无法获得按键.

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 应该在 QWidget 中重新实现.在本例中,QWidget 的子类.

keyPressEvent should be reimplemented in QWidget. In this case, a subclass of QWidget.

你不应该把它放在 ui 类中.

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

这篇关于主窗口中的 KeyEvent (PyQt4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:58