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

我是研究僧i 提交于 2019-12-19 10:27:07

问题


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!


回答1:


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')


来源:https://stackoverflow.com/questions/9966731/pyside-pyqt-simple-way-to-bind-multiple-buttons-that-shares-the-same-function

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