从零开始学Pyqt5之【信号与槽函数定义与使用方法:包含自定义信号与自定义槽函数】
在Pyqt5中控件是通过信号与相应槽函数连接来进行相应动作的响应,本文主要介绍内置信号、自定义信号与内置槽函数、自定义槽函数之间的使用方法。
1.内置信号与内置槽函数使用
from PyQt5.QtWidgets import *
import sys
class Winform(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle('内置的信号/槽示例')
self.resize(330, 50 )
btn = QPushButton('关闭', self)
btn.clicked.connect(self.close)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Winform()
win.show()
sys.exit(app.exec_())
2.内置信号与自定义槽函数使用
from PyQt5.QtWidgets import *
import sys
class Winform(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle('内置的信号和自定义槽函数示例')
self.resize(330, 50 )
btn = QPushButton('关闭', self)
btn.clicked.connect(self.btn_close)
def btn_close(self):
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Winform()
win.show()
sys.exit(app.exec_())
3.自定义信号与内置槽函数使用
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal
import sys
class Winform(QWidget):
button_clicked_signal = pyqtSignal()
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle('自定义信号和内置槽函数示例')
self.resize(330, 50 )
btn = QPushButton('关闭', self)
btn.clicked.connect(self.btn_clicked)
self.button_clicked_signal.connect(self.close)
def btn_clicked(self):
self.button_clicked_signal.emit()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Winform()
win.show()
sys.exit(app.exec_())
4.自定义信号与自定义槽函数使用
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal
import sys
class Winform(QWidget):
button_clicked_signal = pyqtSignal()
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle('自定义信号和槽函数示例')
self.resize(330, 50 )
btn = QPushButton('关闭', self)
btn.clicked.connect(self.btn_clicked)
self.button_clicked_signal.connect(self.btn_close)
def btn_clicked(self):
self.button_clicked_signal.emit()
def btn_close(self):
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Winform()
win.show()
sys.exit(app.exec_())
|