如何连接键盘和运行 PyQt5?

问题描述 投票:0回答:2

如何连接键盘和功能?我只有这个:

class Ui_cityquestion1(object):

    def setupUi(self, cityquestion1):
    here must be function with the button 

    def retranslateUi(self, cityquestion1):


     def keyPressEvent(self, event):
        if event.key() == Qt.Key_H:

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    cityquestion1 = QtWidgets.QWidget()
    ui = Ui_cityquestion1()
    ui.setupUi(cityquestion1)
    cityquestion1.show()
    sys.exit(app.exec_())
python pyqt pyqt5
2个回答
0
投票

好吧,基本上你的结构是错误的。首先,您的

keyPressEvent
方法未被调用,因为它不是继承自
QtWidgets.QWidget
.

的任何类的一部分

了解这一点,您应该首先创建一个继承自此的类。

class CityQuestionWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        # Set up your UI elements
        self.ui = Ui_cityquestion1()
        self.ui.setupUi(self)

    def keyPressEvent(self, event):
        self.ui.retranslateUi("Hello World")

现在当你拥有这个课程时,你可以创建你已经拥有的课程:

class Ui_cityquestion1(object):
    def setupUi(self, cityquestion1):
        # Lets create a Push button:
        self.myButton = QtWidgets.QPushButton(cityquestion1)
        self.myButton.setText("Click me")

    def retranslateUi(self, cityquestion1):
        # Let's try here to change the text inside the button
        self.myButton.setText(cityquestion1)

最后你调用了继承自

QtWidget.QWidget

的类
if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    cityquestion1 = CityQuestionWidget()
    cityquestion1.show()
    sys.exit(app.exec_())

所以如果你把所有东西放在一起,它应该可以工作。如果您有任何疑问,请告诉我。


0
投票
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class CityQuestionWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        # Set up your UI elements
        self.ui = Ui_cityquestion1()
        self.ui.setupUi(self)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_H:
            self.oncl()

    def oncl(self):
        print('asfas')

class Ui_cityquestion1(object):
    def setupUi(self, cityquestion1):
        # Lets create a Push button:
        self.myButton = QtWidgets.QPushButton(cityquestion1)
        self.myButton.setText("Click me")

    def retranslateUi(self, cityquestion1):
        # Let's try here to change the text inside the button
        self.myButton.setText(cityquestion1)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    cityquestion1 = CityQuestionWidget()
    cityquestion1.show()
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.