我已经准备了很多关于如何在 python 和 pyqt 中将多个信号连接到同一个事件处理程序的帖子。例如,将多个按钮或组合框连接到同一功能。
许多示例展示了如何使用 QSignalMapper 执行此操作,但是当信号携带参数时不适用,例如 combobox.currentIndexChanged
许多人建议它可以用 lambda 来制作。这是一个干净漂亮的解决方案,我同意,但没有人提到 lambda 创建了一个闭包,其中包含一个引用 - 因此无法删除被引用的对象。你好内存泄漏!
证明:
from PyQt4 import QtGui, QtCore
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
# create and set the layout
lay_main = QtGui.QHBoxLayout()
self.setLayout(lay_main)
# create two comboboxes and connect them to a single handler with lambda
combobox = QtGui.QComboBox()
combobox.addItems('Nol Adyn Dwa Tri'.split())
combobox.currentIndexChanged.connect(lambda ind: self.on_selected('1', ind))
lay_main.addWidget(combobox)
combobox = QtGui.QComboBox()
combobox.addItems('Nol Adyn Dwa Tri'.split())
combobox.currentIndexChanged.connect(lambda ind: self.on_selected('2', ind))
lay_main.addWidget(combobox)
# let the handler show …Run Code Online (Sandbox Code Playgroud)