在下一部分,我将展示一个如何使用QSignalMapper的示例:
from PySide2 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
fruit_list = ["apples","oranges","pears"]
mapper = QtCore.QSignalMapper(self)
mapper.mapped[str].connect(self.fruit_button_event)
for fruit in fruit_list:
btn = QtWidgets.QPushButton(fruit)
btn.clicked.connect(mapper.map)
mapper.setMapping(btn, fruit)
lay.addWidget(btn)
@QtCore.Slot(str)
def fruit_button_event(self, text):
print("this is the pressed button's label", text)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
请记住,从 Qt 5.10 QSignalMapper 开始已被弃用:
该类已过时。它仅提供旧源代码的支持。我们强烈建议不要在新代码中使用它。
在Python中,可以使用 functools.partial(...) 来获得相同的功能:
from PySide2 import QtCore, QtWidgets
from functools import partial
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
fruit_list = ["apples","oranges","pears"]
for fruit in fruit_list:
btn = QtWidgets.QPushButton(fruit)
btn.clicked.connect(partial(self.fruit_button_event, fruit))
lay.addWidget(btn)
@QtCore.Slot(str)
def fruit_button_event(self, text):
print("this is the pressed button's label", text)
或者使用 lambda:
btn.clicked.connect(lambda text=fruit: self.fruit_button_event(text))
或者 QButtonGroup:
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
fruit_list = ["apples","oranges","pears"]
group = QtWidgets.QButtonGroup(self)
group.buttonClicked.connect(self.OnButtonClicked)
for fruit in fruit_list:
btn = QtWidgets.QPushButton(fruit)
group.addButton(btn)
lay.addWidget(btn)
@QtCore.Slot(QtWidgets.QAbstractButton)
def OnButtonClicked(self, btn):
print("this is the pressed button's label", btn.text())
QSignalMapper
:请使用 QButtonGroup。 - ekhumoro