pyside / pyqt:绑定具有相同功能的多个按钮的简单方法
问题内容:
我是PyQt / PySide的新手。
我有很多行编辑(用于显示文件位置),每行文本都有一个按钮(用于显示打开的文件对话框)。
我有一个方法:
def selectSelf1(self):
""" browse for file dialog """
myDialog = QtGui.QFileDialog
self.lineSelf1.setText(myDialog.getOpenFileName())
使用以下代码绑定一个按钮
self.btnSelf1.clicked.connect(self.selectSelf1)
我大约有20个这些按钮和20个行编辑。有没有一种简单的方法可以将所有这些按钮绑定到其相应的行编辑,而不是键入所有内容。
谢谢!
问题答案:
如果您有一个Buttons和LineEdits列表,则可以使用以下命令:
-
functools.partial
, 像这样:def show_dialog(self, line_edit): ... line_edit.setText(...)
for button, line_edit in zip(buttons, line_edits):
button.clicked.connect(functools.partial(self.show_dialog, line_edit)) -
lambda
的for button, line_edit in ...: button.clicked.connect(lambda : self.show_dialog(line_edit))
如果您使用的是Qt Designer,并且没有按钮和lineedit的列表,但是它们都具有相同的命名模式,则可以使用一些自省:
class Foo(object):
def __init__(self):
self.edit1 = 1
self.edit2 = 2
self.edit3 = 3
self.button1 = 1
self.button2 = 2
self.button3 = 3
def find_attributes(self, name_start):
return [value for name, value in sorted(self.__dict__.items())
if name.startswith(name_start)]
foo = Foo()
print foo.find_attributes('edit')
print foo.find_attributes('button')