1、信号与槽的两种写法
第一种情况:
from PySide2 import QtWidgets, QtCore
import sys
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QWidget()
btn = QtWidgets.QPushButton(widget)
btn.clicked.connect(widget.close)
widget.show()
sys.exit(app.exec_())
第二种情况:
from PySide2 import QtWidgets, QtCore
import sys
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QWidget()
btn = QtWidgets.QPushButton(widget)
QtCore.QObject.connect(btn,QtCore.SIGNAL("clicked()"),widget,QtCore.SLOT("close()"))
widget.show()
sys.exit(app.exec_())
2、自定义槽函数
from PySide2 import QtWidgets, QtCore
import sys
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QWidget()
btn = QtWidgets.QPushButton(widget)
@QtCore.Slot()
def changeTex():
btn.setText("ok")
btn.clicked.connect(changeTex)
widget.show()
sys.exit(app.exec_())
3、带参数槽函数
(1)lambad写法:
from PySide2 import QtWidgets,QtCore
import sys
class MyForm(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MyForm, self).__init__(parent)
button1 = QtWidgets.QPushButton(self)
button1.clicked.connect(lambda: self.on_button(1))
def on_button(self, n):
print('Button {0} clicked'.format(n))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
form = MyForm()
form.show()
app.exec_()
(2)使用functools里的partial函数。
from functools import partial
from PySide2 import QtWidgets,QtCore
import sys
class MyForm(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MyForm, self).__init__(parent)
button1 = QtWidgets.QPushButton(self)
button1.clicked.connect(partial(self.on_button, 1))
def on_button(self, n):
print('Button {0} clicked'.format(n))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
form = MyForm()
form.show()
app.exec_()