事件和信號
事件
signals and slots 被其他人翻譯成信號和槽機制,(⊙o⊙)…我這里還是不翻譯好了。
所有的應(yīng)用都是事件驅(qū)動的。事件大部分都是由用戶的行為產(chǎn)生的,當然也有其他的事件產(chǎn)生方式,比如網(wǎng)絡(luò)的連接,窗口管理器或者定時器等。調(diào)用應(yīng)用的exec_()方法時,應(yīng)用會進入主循環(huán),主循環(huán)會監(jiān)聽和分發(fā)事件。
在事件模型中,有三個角色:
- 事件源
- 事件
- 事件目標
事件源就是發(fā)生了狀態(tài)改變的對象。事件是這個對象狀態(tài)改變的內(nèi)容。事件目標是事件想作用的目標。事件源綁定事件處理函數(shù),然后作用于事件目標身上。
PyQt5處理事件方面有個signal and slot機制。Signals and slots用于對象間的通訊。事件觸發(fā)的時候,發(fā)生一個signal,slot是用來被Python調(diào)用的(相當于一個句柄?這個詞也好惡心,就是相當于事件的綁定函數(shù))slot只有在事件觸發(fā)的時候才能調(diào)用。
Signals & slots
下面是signal & slot的演示
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we connect a signal
of a QSlider to a slot of a QLCDNumber.
Author: Jan Bodnar
Website: zetcode.com
Last edited: January 2017
"""
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider,
QVBoxLayout, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lcd = QLCDNumber(self)
sld = QSlider(Qt.Horizontal, self)
vbox = QVBoxLayout()
vbox.addWidget(lcd)
vbox.addWidget(sld)
self.setLayout(vbox)
sld.valueChanged.connect(lcd.display)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Signal and slot')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
上面的例子中,顯示了QtGui.QLCDNumber和QtGui.QSlider模塊,我們能拖動滑塊讓數(shù)字跟著發(fā)生改變。
sld.valueChanged.connect(lcd.display)
這里是把滑塊的變化和數(shù)字的變化綁定在一起。
sender是信號的發(fā)送者,receiver是信號的接收者,slot是對這個信號應(yīng)該做出的反應(yīng)。
程序展示:

重構(gòu)事件處理器
在PyQt5中,事件處理器經(jīng)常被重寫(也就是用自己的覆蓋庫自帶的)。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we reimplement an
event handler.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Event handler')
self.show()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
這個例子中,我們替換了事件處理器函數(shù)keyPressEvent()。
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
此時如果按下ESC鍵程序就會退出。
程序展示:
這個就一個框,啥也沒,就不展示了。
事件對象
事件對象是用python來描述一系列的事件自身屬性的對象。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we display the x and y
coordinates of a mouse pointer in a label widget.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabel
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
grid.setSpacing(10)
x = 0
y = 0
self.text = "x: {0}, y: {1}".format(x, y)
self.label = QLabel(self.text, self)
grid.addWidget(self.label, 0, 0, Qt.AlignTop)
self.setMouseTracking(True)
self.setLayout(grid)
self.setGeometry(300, 300, 350, 200)
self.setWindowTitle('Event object')
self.show()
def mouseMoveEvent(self, e):
x = e.x()
y = e.y()
text = "x: {0}, y: {1}".format(x, y)
self.label.setText(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
這個示例中,我們在一個組件里顯示鼠標的X和Y坐標。
self.text = "x: {0}, y: {1}".format(x, y)
self.label = QLabel(self.text, self)
X Y坐標顯示在QLabel組件里
self.setMouseTracking(True)
鼠標追蹤默認沒有開啟,當有鼠標點擊事件發(fā)生后才會開啟。
def mouseMoveEvent(self, e):
x = e.x()
y = e.y()
text = "x: {0}, y: {1}".format(x, y)
self.label.setText(text)
e代表了事件對象。里面有我們觸發(fā)事件(鼠標移動)的事件對象。x()和y()方法得到鼠標的x和y坐標點,然后拼成字符串輸出到QLabel組件里。
程序展示:

事件發(fā)送
有時候我們會想知道是哪個組件發(fā)出了一個信號,PyQt5里的sender()方法能搞定這件事。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we determine the event sender
object.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn1 = QPushButton("Button 1", self)
btn1.move(30, 50)
btn2 = QPushButton("Button 2", self)
btn2.move(150, 50)
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
self.statusBar()
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Event sender')
self.show()
def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' was pressed')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
這個例子里有倆按鈕,buttonClicked()方法決定了是哪個按鈕能調(diào)用sender()方法。
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
兩個按鈕都和同一個slot綁定。
def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' was pressed')
我們用調(diào)用sender()方法的方式?jīng)Q定了事件源。狀態(tài)欄顯示了被點擊的按鈕。
程序展示:

信號發(fā)送
QObject實例能發(fā)送事件信號。下面的例子是發(fā)送自定義的信號。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we show how to
emit a custom signal.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication
class Communicate(QObject):
closeApp = pyqtSignal()
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.c = Communicate()
self.c.closeApp.connect(self.close)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Emit signal')
self.show()
def mousePressEvent(self, event):
self.c.closeApp.emit()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
我們創(chuàng)建了一個叫closeApp的信號,這個信號會在鼠標按下的時候觸發(fā),事件與QMainWindow綁定。
class Communicate(QObject):
closeApp = pyqtSignal()
Communicate類創(chuàng)建了一個pyqtSignal()屬性的信號。
self.c = Communicate()
self.c.closeApp.connect(self.close)
closeApp信號QMainWindow的close()方法綁定。
def mousePressEvent(self, event):
self.c.closeApp.emit()
點擊窗口的時候,發(fā)送closeApp信號,程序終止。
程序展示:
這個也是啥也沒。