Reputation: 1651
I'm new to PyQt / PySide.
I have a lot of line edit (for displaying file location) and for each line text I have a push button (to display open file dialog).
I have a method:
def selectSelf1(self):
""" browse for file dialog """
myDialog = QtGui.QFileDialog
self.lineSelf1.setText(myDialog.getOpenFileName())
and a push button is binded using the following code
self.btnSelf1.clicked.connect(self.selectSelf1)
I have about 20 of those buttons and 20 of those line edits. Is there an easy way to bind all of those button to their corresponding line edits rather than typing out everything.
Thanks!
Upvotes: 2
Views: 4808
Reputation: 9522
If you have a list of Buttons and LineEdits, you can use following:
functools.partial
, like this:
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
's
for button, line_edit in ...:
button.clicked.connect(lambda : self.show_dialog(line_edit))
If you are using Qt Designer, and don't have list of buttons and lineedits, but they all have the same naming pattern, you can use some introspection:
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')
Upvotes: 6