事件和信号

事件

signals and slots 被其他人翻译成信号和槽机制,(⊙o⊙)…我这里还是不翻译好了。

所有的应用都是事件驱动的。事件大部分都是由用户的行为产生的,当然也有其他的事件产生方式,比如网络的连接,窗口管理器或者定时器等。调用应用的exec_()方法时,应用会进入主循环,主循环会监听和分发事件。

在事件模型中,有三个角色:

  • 事件源
  • 事件
  • 事件目标

事件源就是发生了状态改变的对象。事件是这个对象状态改变的内容。事件目标是事件想作用的目标。事件源绑定事件处理函数,然后作用于事件目标身上。

PyQt5处理事件方面有个signal and slot机制。Signals and slots用于对象间的通讯。事件触发的时候,发生一个signal,slot是用来被Python调用的(相当于一个句柄?这个词也好恶心,就是相当于事件的绑定函数)slot只有在事件触发的时候才能调用。

Signals & slots

下面是signal & slot的演示

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we connect a signal
  6. of a QSlider to a slot of a QLCDNumber.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: January 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import Qt
  13. from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider,
  14. QVBoxLayout, QApplication)
  15. class Example(QWidget):
  16. def __init__(self):
  17. super().__init__()
  18. self.initUI()
  19. def initUI(self):
  20. lcd = QLCDNumber(self)
  21. sld = QSlider(Qt.Horizontal, self)
  22. vbox = QVBoxLayout()
  23. vbox.addWidget(lcd)
  24. vbox.addWidget(sld)
  25. self.setLayout(vbox)
  26. sld.valueChanged.connect(lcd.display)
  27. self.setGeometry(300, 300, 250, 150)
  28. self.setWindowTitle('Signal and slot')
  29. self.show()
  30. if __name__ == '__main__':
  31. app = QApplication(sys.argv)
  32. ex = Example()
  33. sys.exit(app.exec_())

上面的例子中,显示了QtGui.QLCDNumberQtGui.QSlider模块,我们能拖动滑块让数字跟着发生改变。

  1. sld.valueChanged.connect(lcd.display)

这里是把滑块的变化和数字的变化绑定在一起。

sender是信号的发送者,receiver是信号的接收者,slot是对这个信号应该做出的反应。

程序展示:

signal & slot

重构事件处理器

在PyQt5中,事件处理器经常被重写(也就是用自己的覆盖库自带的)。

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we reimplement an
  6. event handler.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import Qt
  13. from PyQt5.QtWidgets import QWidget, QApplication
  14. class Example(QWidget):
  15. def __init__(self):
  16. super().__init__()
  17. self.initUI()
  18. def initUI(self):
  19. self.setGeometry(300, 300, 250, 150)
  20. self.setWindowTitle('Event handler')
  21. self.show()
  22. def keyPressEvent(self, e):
  23. if e.key() == Qt.Key_Escape:
  24. self.close()
  25. if __name__ == '__main__':
  26. app = QApplication(sys.argv)
  27. ex = Example()
  28. sys.exit(app.exec_())

这个例子中,我们替换了事件处理器函数keyPressEvent()

  1. def keyPressEvent(self, e):
  2. if e.key() == Qt.Key_Escape:
  3. self.close()

此时如果按下ESC键程序就会退出。

程序展示:

这个就一个框,啥也没,就不展示了。

事件对象

事件对象是用python来描述一系列的事件自身属性的对象。

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we display the x and y
  6. coordinates of a mouse pointer in a label widget.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import Qt
  13. from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabel
  14. class Example(QWidget):
  15. def __init__(self):
  16. super().__init__()
  17. self.initUI()
  18. def initUI(self):
  19. grid = QGridLayout()
  20. grid.setSpacing(10)
  21. x = 0
  22. y = 0
  23. self.text = "x: {0}, y: {1}".format(x, y)
  24. self.label = QLabel(self.text, self)
  25. grid.addWidget(self.label, 0, 0, Qt.AlignTop)
  26. self.setMouseTracking(True)
  27. self.setLayout(grid)
  28. self.setGeometry(300, 300, 350, 200)
  29. self.setWindowTitle('Event object')
  30. self.show()
  31. def mouseMoveEvent(self, e):
  32. x = e.x()
  33. y = e.y()
  34. text = "x: {0}, y: {1}".format(x, y)
  35. self.label.setText(text)
  36. if __name__ == '__main__':
  37. app = QApplication(sys.argv)
  38. ex = Example()
  39. sys.exit(app.exec_())

这个示例中,我们在一个组件里显示鼠标的X和Y坐标。

  1. self.text = "x: {0}, y: {1}".format(x, y)
  2. self.label = QLabel(self.text, self)

X Y坐标显示在QLabel组件里

  1. self.setMouseTracking(True)

事件追踪默认没有开启,当开启后才会追踪鼠标的点击事件。

  1. def mouseMoveEvent(self, e):
  2. x = e.x()
  3. y = e.y()
  4. text = "x: {0}, y: {1}".format(x, y)
  5. self.label.setText(text)

e代表了事件对象。里面有我们触发事件(鼠标移动)的事件对象。x()y()方法得到鼠标的x和y坐标点,然后拼成字符串输出到QLabel组件里。

程序展示:

event object

事件发送

有时候我们会想知道是哪个组件发出了一个信号,PyQt5里的sender()方法能搞定这件事。

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we determine the event sender
  6. object.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
  13. class Example(QMainWindow):
  14. def __init__(self):
  15. super().__init__()
  16. self.initUI()
  17. def initUI(self):
  18. btn1 = QPushButton("Button 1", self)
  19. btn1.move(30, 50)
  20. btn2 = QPushButton("Button 2", self)
  21. btn2.move(150, 50)
  22. btn1.clicked.connect(self.buttonClicked)
  23. btn2.clicked.connect(self.buttonClicked)
  24. self.statusBar()
  25. self.setGeometry(300, 300, 290, 150)
  26. self.setWindowTitle('Event sender')
  27. self.show()
  28. def buttonClicked(self):
  29. sender = self.sender()
  30. self.statusBar().showMessage(sender.text() + ' was pressed')
  31. if __name__ == '__main__':
  32. app = QApplication(sys.argv)
  33. ex = Example()
  34. sys.exit(app.exec_())

这个例子里有俩按钮,buttonClicked()方法决定了是哪个按钮能调用sender()方法。

  1. btn1.clicked.connect(self.buttonClicked)
  2. btn2.clicked.connect(self.buttonClicked)

两个按钮都和同一个slot绑定。

  1. def buttonClicked(self):
  2. sender = self.sender()
  3. self.statusBar().showMessage(sender.text() + ' was pressed')

我们用调用sender()方法的方式决定了事件源。状态栏显示了被点击的按钮。

程序展示:

event sender

信号发送

QObject实例能发送事件信号。下面的例子是发送自定义的信号。

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we show how to
  6. emit a custom signal.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import pyqtSignal, QObject
  13. from PyQt5.QtWidgets import QMainWindow, QApplication
  14. class Communicate(QObject):
  15. closeApp = pyqtSignal()
  16. class Example(QMainWindow):
  17. def __init__(self):
  18. super().__init__()
  19. self.initUI()
  20. def initUI(self):
  21. self.c = Communicate()
  22. self.c.closeApp.connect(self.close)
  23. self.setGeometry(300, 300, 290, 150)
  24. self.setWindowTitle('Emit signal')
  25. self.show()
  26. def mousePressEvent(self, event):
  27. self.c.closeApp.emit()
  28. if __name__ == '__main__':
  29. app = QApplication(sys.argv)
  30. ex = Example()
  31. sys.exit(app.exec_())

我们创建了一个叫closeApp的信号,这个信号会在鼠标按下的时候触发,事件与QMainWindow绑定。

  1. class Communicate(QObject):
  2. closeApp = pyqtSignal()

Communicate类创建了一个pyqtSignal()属性的信号。

  1. self.c = Communicate()
  2. self.c.closeApp.connect(self.close)

closeApp信号QMainWindowclose()方法绑定。

  1. def mousePressEvent(self, event):
  2. self.c.closeApp.emit()

点击窗口的时候,发送closeApp信号,程序终止。

程序展示:

这个也是啥也没。