Update 事件和信号.md

This commit is contained in:
maicss 2016-10-06 14:14:56 +08:00
parent c6a5cde564
commit 32ef5d826b

View File

@ -137,12 +137,12 @@ def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
```
If we click the Escape button, the application terminates.
此时如果按下ESC键程序就会退出。
Event sender
Sometimes it is convenient to know which widget is the sender of a signal. For this, PyQt5 has the sender() method.
## 事件发送
有时候我们会想知道是哪个组件发出了一个信号PyQt5里的`sender()`方法能搞定这件事。
```
#!/usr/bin/python3
# -*- coding: utf-8 -*-
@ -198,24 +198,29 @@ if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
We have two buttons in our example. In the buttonClicked() method we determine which button we have clicked by calling the sender() method.
```
这个例子里有俩按钮,`buttonClicked()`方法决定了是哪个按钮能调用`sender()`方法。
```
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
Both buttons are connected to the same slot.
```
两个按钮都和同一个slot绑定。
```
def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' was pressed')
We determine the signal source by calling the sender() method. In the statusbar of the application, we show the label of the button being pressed.
```
我们用调用`sender()`方法的方式决定了事件源。状态栏显示了被点击的按钮。
Event sender
Figure: Event sender
Emitting signals
程序展示:
Objects created from a QObject can emit signals. In the following example we will see how we can emit custom signals.
![event sender](./images/4-eventsender.png)
## 信号发送
`QObject`实例能发送事件信号。下面的例子是发送自定义的信号。
```
#!/usr/bin/python3
# -*- coding: utf-8 -*-
@ -268,18 +273,22 @@ if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
We create a new signal called closeApp. This signal is emitted during a mouse press event. The signal is connected to the close() slot of the QMainWindow.
```
我们创建了一个叫closeApp的信号这个信号会在鼠标按下的时候触发事件与`QMainWindow`绑定。
```
class Communicate(QObject):
closeApp = pyqtSignal()
A signal is created with the pyqtSignal() as a class attribute of the external Communicate class.
```
`Communicate`类创建了一个`pyqtSignal()`属性的信号。
```
self.c = Communicate()
self.c.closeApp.connect(self.close)
The custom closeApp signal is connected to the close() slot of the QMainWindow.
```
`closeApp`信号`QMainWindow``close()`方法绑定。
```
def mousePressEvent(self, event):
self.c.closeApp.emit()
When we click on the window with a mouse pointer, the closeApp signal is emitted. The application terminates.
```
当点击窗口的时候closeApp信号发送程序终止。