在 pyQT Designer 生成的代码中生成 keyPressEvent [英] Generating keyPressEvent in a code generated by pyQT Designer

查看:40
本文介绍了在 pyQT Designer 生成的代码中生成 keyPressEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ui 中使用 pyQt Designer 创建了一个代码,并将其更改为 py 代码.

I Created a code using pyQt Designer in ui and changed it to py code.

现在我想向我的这个添加一些按键事件,即如果我点击带有数字 3 的键盘键,我的标签上应该有文本 3 或者它只是打印嗨"

Now i want to add some Keypress events to my this i.e. say if i click on keyboard key with numeric 3 , my label should have text 3 on it or it just print "Hi"

我已经通过互联网检查了很多论坛,发现最好重新实现 keyPressEvent 以使用键盘事件.我尝试过,但是不知何故我无法使其在 pyQT 设计器生成的代码中工作.

I have already checked a lot of forums over internet and found that its best to reimplement keyPressEvent to use keyboard events . I tried that however somehow i am not able to make it work in the code generated by pyQT designer .

下面是pyQT设计器生成的代码.我也将 keyPressEvent 重新实现的代码放入其中,但是它不起作用:

Below is the code generated by pyQT designer . I have put the code of keyPressEvent re implementation in it as well , however it dosent work :

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):


        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)

        MainWindow.setFocus()

        def keyPressEvent(self, qKeyEvent):
            print "hi"
            print(qKeyEvent.key())
            if qKeyEvent.key() == QtCore.Qt.Key_Return:
                print('Enter pressed')
            else:
                super(Ui_MainWindow).keyPressEvent(qKeyEvent)

        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayoutWidget = QtGui.QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 10, 721, 80))
        self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.textEdit = QtGui.QLabel(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(50, 110, 81, 41))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))

        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(130, 260, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.textEdit.setText("I am a label")
        self.pushButton.setText(_translate("MainWindow", "PushButton", None))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

我是这个论坛的新手,如果有人可以提供帮助会很有帮助.我知道这可以通过创建另一个继承 QMainWindow 的类来实现,但我想在相同的代码中执行此操作,即在 pyQT Designer 生成的代码块中.

I am new to this forum , it will be helpful if someone can help . I know this can be achieved by creating another class who inherits QMainWindow but i want to do this in the same code i.e in the code block generated by pyQT Designer .

还请建议如果有任何方法可以在不重新实现 keypressEvent 的情况下做到这一点

Also please suggest If there is any way to do this without reimplementing keypressEvent

谢谢

推荐答案

您的代码不起作用的原因有两个.

There are two reasons why your code doesn't work.

首先是您在 setupUi 方法中定义了 keyPressEvent,因此它对类完全不可见.

The first is that you are defining keyPressEvent inside the setupUi method, hence it is completely invisible to the class.

其次是因为在代码中:

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

您正在创建 QMainWindow 的一个实例,它使用自己的 keyPressEvent 实现.您应该创建 QMainWindow 的子类并在那里重新实现该方法.

You are creating an instance of QMainWindow, which uses its own implementation of keyPressEvent. You should create a subclass of QMainWindow and reimplement the method there.

  • 打开设计器并创建主窗口.

  • Open the designer and create your mainwindow.

使用pyuic编译.ui文件:

$pyuic4 mainwindow.ui -o ui_mainwindow.py

  • 创建一个文件,您将在其中编写QMainWindow的子类,mymainwindow.py.不要修改ui_mainwindow.py.文件开头有个大警告:

  • Create a new file where you'll write the subclass of the QMainWindow, mymainwindow.py. Do no modify ui_mainwindow.py. There is a big warning at the start of the file:

    # 警告!在此文件中所做的所有更改都将丢失!

    # WARNING! All changes made in this file will be lost!

    如果您不想在更改 UI 时丢失所有代码,请不要修改文件.

    If you don't want to lose all your code when changing the UI then do not modify the file.

    在子类中实现keyPressEvent:

    from PyQt4 import QtGui
    
    # import the UI from the generated file
    from ui_mainwindow import Ui_MainWindow
    
    
    # it's not stricly necessary to subclass Ui_MainWindow.
    class MyMainWindow(QtGui.QMainWindow, Ui_MainWindow):
        def __init__(self, parent=None):
            super(MyMainWindow, self).__init__(parent)
            self.setupUi(self)
            # if you didn't subclass Ui_MainWindow simply do:
            # Ui_MainWindow().setupUi(self)
    
        def keyPressEvent(self, event):
            # implement the method here
            self.label.setText(self.label.text() + 'a')
    
    if __name__ == '__main__':
        app = QtGui.QApplication([])
        win = MyMainWindow()
        win.show()
        app.exec_()
    

    • 最后运行代码并注意,每次按下一个键时,文本中都会添加一个 a.
    • 这篇关于在 pyQT Designer 生成的代码中生成 keyPressEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆