Objects created from a QObject can emit signals. The following example shows how we to emit custom signals.
使用QObject创建的对象可以发出信号.下面你这个例子向我们展示了如何发出信号.
下面是源码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/24 下午2:33
# @Author : Aries
# @Site :
# @File : 1024-01-Emitting signals.py
# @Software: PyCharm
import sys
from PyQt5.QtCore import pyqtSignal,QObject,Qt
from PyQt5.QtWidgets import QMainWindow,QApplication,QLabel
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)
title = QLabel('点击鼠标即可关闭程序')
title.move(300,100)
self.setCentralWidget(title)
#title设置居中
title.setAlignment(Qt.AlignCenter)
self.setGeometry(300,300,290,150)
self.setWindowTitle('Emitting signals')
self.show()
def mousePressEvent(self, QMouseEvent):
self.c.closeApp.emit()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
重点代码解读:
- 我们创建了一个closeApp的信号.当鼠标被点击的时候,这个信号会被发出.这个信号和QMainWindow的close()方法相关联.
class Communicate(QObject):
closeApp = pyqtSignal()
#通过 Communicate()类创建一个信号,并且将这个信号与close()方法相关联
self.c = Communicate()
self.c.closeApp.connect(self.close)
2.当鼠标被点击的时候,发出这个信号.我们重写了鼠标点击的方法,closeApp这个方法就会执行,程序就会关闭.
def mousePressEvent(self, event):
self.c.closeApp.emit()