基本概念:信号和槽是Qt的核心机制,也是进行PyQt5编程时对象之间通信的基础;每一个QObject对象(包括各种窗口和控件)都支持信号和槽机制,通过信号和槽的关联就可以实现对象之间的通信。当信号发射时,连接的槽函数就会自动执行
信号与槽的主要特点:
编辑信号与槽
保存文件,关闭Qt Designer,将untitled.ui转换为py文件,添加函数
# 导入库
import sys
from PyQt5.QtWidgets import QMessageBox
# 添加程序入口
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
# 在Ui_MainWindow类中添加方法
def show_message(self):
QMessageBox.information(MainWindow,"提示框","弹出对话框成功!",QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)
# 修改setupUi方法
self.pushButton.clicked.connect(self.show_message)
代码全览
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(336, 147)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(50, 60, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(200, 60, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 336, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.pushButton_2.clicked.connect(MainWindow.close)
self.pushButton.clicked.connect(self.show_message)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "信号与槽"))
self.pushButton.setText(_translate("MainWindow", "弹出对话框"))
self.pushButton_2.setText(_translate("MainWindow", "关闭窗口"))
def show_message(self):
QMessageBox.information(MainWindow,"提示框","弹出对话框成功!",QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())