【问题标题】:pyside / pyqt: simple way to bind multiple buttons that shares the same functionalitypyside / pyqt:绑定共享相同功能的多个按钮的简单方法
【发布时间】:2023-04-07 05:26:02
【问题描述】:

我是 PyQt / PySide 的新手。

我有很多行编辑(用于显示文件位置),并且对于每一行文本我都有一个按钮(用于显示打开文件对话框)。

我有一个方法:

   def selectSelf1(self): 
        """ browse for file dialog """
        myDialog = QtGui.QFileDialog
        self.lineSelf1.setText(myDialog.getOpenFileName())

并且使用以下代码绑定按钮

    self.btnSelf1.clicked.connect(self.selectSelf1)

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

谢谢!

【问题讨论】:

    标签: python qt user-interface pyqt pyside


    【解决方案1】:

    如果你有一个 Buttons 和 LineEdits 列表,你可以使用以下:

    • QSignalMapper, another description

    • 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,但它们都有相同的命名模式,您可以使用一些自省:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多