Skip to content Skip to sidebar Skip to footer

Pyside / Pyqt: Simple Way To Bind Multiple Buttons That Shares The Same Functionality

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: d

Solution 1:

If you have a list of Buttons and LineEdits, you can use following:

  • QSignalMapper, another description

  • functools.partial, like this:

    defshow_dialog(self, line_edit):
        ...
        line_edit.setText(...)
    
    for button, line_edit inzip(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:

classFoo(object):
    def__init__(self):
        self.edit1 = 1
        self.edit2 = 2
        self.edit3 = 3
        self.button1 = 1
        self.button2 = 2
        self.button3 = 3deffind_attributes(self, name_start):
        return [value for name, value insorted(self.__dict__.items())
                          if name.startswith(name_start)]

foo = Foo()
print foo.find_attributes('edit')
print foo.find_attributes('button')

Post a Comment for "Pyside / Pyqt: Simple Way To Bind Multiple Buttons That Shares The Same Functionality"