pyside / pyqt: simple way to bind multiple buttons that shares the same functionality

一曲冷凌霜 提交于 2019-12-01 09:35:32
reclosedev

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

  • QSignalMapper, another description

  • 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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!