pyside/pyqt:绑定共享相同功能的多个按钮的简单方法 [英] pyside / pyqt: simple way to bind multiple buttons that shares the same functionality

查看:99
本文介绍了pyside/pyqt:绑定共享相同功能的多个按钮的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PyQt/PySide 的新手.

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

我有一个方法:

   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)

我有大约 20 个这样的按钮和 20 个这样的行编辑.有没有一种简单的方法可以将所有这些按钮绑定到相应的行编辑,而不是输入所有内容.

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.

谢谢!

推荐答案

如果您有按钮和 LineEdits 的列表,您可以使用以下内容:

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

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,并且没有按钮和 lineedits 列表,但它们都有相同的命名模式,您可以使用一些自省:

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

    这篇关于pyside/pyqt:绑定共享相同功能的多个按钮的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆