在上一章节中创建一个PushButton的视窗,但是点击之后没有触发任何效果,显然在用户交互的时候需要触发事件。这里就要提到两个概念Signals(信号)和Slots(插槽)。在某些编程语言中称为冒泡监听。

Signal除了可以通知之外,还可以发送数据,类似于某些编程语言中的冒泡。而Slot则是用于接收Signal, 它类似于某些编程语言中的事件监听,但是与监听不同的是Slots可以有很多个并行。

  1. from PyQt5.QtWidgets import QApplication,QMainWindow,QPushButton
  2. import sys
  3. class MainWindow(QMainWindow):
  4. def __init__(self):
  5. super().__init__()
  6. self.setWindowTitle("教学应用")
  7. button = QPushButton("提交")
  8. self.setCentralWidget(button)
  9. self.setFixedSize(600,300)
  10. self.setMaximumSize(800,400)
  11. self.setMinimumSize(200,100)
  12. # button在默认情况下没有勾选功能。如果设置为True则启动
  13. button.setCheckable(True)
  14. # click事件监听1
  15. button.clicked.connect(self.the_button_was_clicked)
  16. # click事件监听2
  17. button.clicked.connect(self.the_button_was_toggled)
  18. # 自定义click事件
  19. def the_button_was_clicked(self):
  20. print("点击")
  21. def the_button_was_toggled(self,data):
  22. # 在默认情况下输出False
  23. print(data)
  24. app =QApplication(sys.argv)
  25. window = MainWindow()
  26. window.show()
  27. app.exec()

前端数据的存储

PyQt5 通过class的私有变量进行前端变量数据的存储。但是与前端编程使用state存储输入框内容不同,PyQt5有自己的机制:

  1. from PyQt5.QtWidgets import QApplication,QMainWindow,QWidget,QPushButton,QLabel,QLineEdit,QVBoxLayout
  2. import sys
  3. class MainWindow(QMainWindow):
  4. def __init__(self):
  5. super().__init__()
  6. self.setWindowTitle("教学应用")
  7. self.label = QLabel()
  8. self.input = QLineEdit()
  9. # 监听输入框,self.lable.setText可直接修改label文本内容
  10. self.input.textChanged.connect(self.label.setText)
  11. layout = QVBoxLayout()
  12. layout.addWidget(self.input)
  13. layout.addWidget(self.label)
  14. container = QWidget()
  15. container.setLayout(layout)
  16. self.setCentralWidget(container)
  17. app =QApplication(sys.argv)
  18. window = MainWindow()
  19. window.show()
  20. app.exec()

图3-1 可以看到label的直接修改

由于前端的组件存在嵌套性,所以在某些情况下需要考虑到事件的接受和忽略:

  1. class CustomButton(QPushButton)
  2. def mousePressEvent(self, e):
  3. e.accept()
  4. e.ignore()

pyqtSlot用法

  1. from PyQt5.QtCore import pyqtSlot