PyQT5信号与槽的连接
方法一:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class AutoSignalSlot(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("信号与槽自动连接")
self.resize(300, 100)
self.okButton = QPushButton("OK", self) # 将btn绑定到窗口
self.okButton.setObjectName('okButton')
layout = QHBoxLayout()
layout.addWidget(self.okButton)
self.setLayout(layout)
# 方法一
self.okButton.clicked.connect(self.on_okButton_clicked)
def on_okButton_clicked(self):
print("点击了OK按钮!")
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = AutoSignalSlot()
main_win.show()
sys.exit(app.exec_())
方法二:
信号与槽自动连接
on_objectname_signalname
例如:on_okButton_clicked
from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
import sys
class AutoSignalSlot(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("信号与槽自动连接")
self.resize(300, 100)
self.okButton = QPushButton("OK", self) # 将btn绑定到窗口
self.okButton.setObjectName('okButton')
self.cancelButton = QPushButton("Cancel", self) # 将btn绑定到窗口
self.cancelButton.setObjectName('cancelButton')
layout = QHBoxLayout()
layout.addWidget(self.okButton)
self.setLayout(layout)
# 方法一
# self.okButton.clicked.connect(self.on_okButton_clicked)
# 方法二
QMetaObject.connectSlotsByName(self)
@QtCore.pyqtSlot()
def on_okButton_clicked(self):
print("点击了OK按钮!")
@QtCore.pyqtSlot()
def on_cancelButton_clicked(self):
print("点击了cancel按钮!")
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = AutoSignalSlot()
main_win.show()
sys.exit(app.exec_())