如何迭代 pyqt5 上的 clicked.connected 按钮?

How to iterate over clicked.connected buttons on pyqt5?

我正在使用 PyQT5 创建一个带有 pandas 数据帧的接口。我希望在单击按钮时更改数据框。我设法手动完成,但我需要遍历按钮,因为数据帧的数量是一个变量。我已经看到其他问题,但无法在我的代码中重现。这是一个片段:

    def createTable(self):
        self.groupBox = QGroupBox('Tabela')
        layout = QGridLayout()
        
        global main_model
        main_model = pandasModel(dir_data)

        global view
        view = QTableView()
        view.setModel(main_model)
        view.show()
        layout.addWidget(view)

        self.groupBox.setLayout(layout)

    def createEntities(self):
        self.entities = QGroupBox("Entidades")
        layout = QHBoxLayout()

        for i in range(len(get_data.list_names)):
            globals()['button_{}'.format(get_data.files[i])] = QPushButton("{}".format(get_data.files[i]))
            
            #button_list.append(globals()['button_{}'.format(get_data.files[i])])
            
            #button_list_name.append('button_{}'.format(get_data.files[i]))
            # ['button_pdf', 'button_pds', ...]

            layout.addWidget(globals()['button_{}'.format(get_data.files[i])])
        ################################################

        # TODO iterate over buttons
        # Part of the code I want to iterate
        
        button_pdf.clicked.connect(lambda: self.change_model('pdf'))
        button_pds.clicked.connect(lambda: self.change_model('pds'))
        button_ppp.clicked.connect(lambda: self.change_model('ppp'))

        ################################################
            
        self.entities.setLayout(layout)
    
    #Function to change the table (works properly)
    def change_model(self, table):
        print(table)
        main_model = pandasModel(good_data(table,directory))
        view.setModel(main_model)
        view.show()

不要使用全局变量或“globals”,因为它会产生难以调试的静默错误,而是将这些变量设为 class 的属性。另一方面,您只需遍历“文件”并建立连接:

def createTable(self):
    self.groupBox = QGroupBox("Tabela")
    layout = QGridLayout()

    self.main_model = pandasModel(dir_data)

    self.view = QTableView()
    self.view.setModel(self.main_model)
    layout.addWidget(self.view)

    self.groupBox.setLayout(layout)


def createEntities(self):
    self.entities = QGroupBox("Entidades")
    layout = QHBoxLayout()

    for text in get_data.files:
        btn = QPushButton(text)
        btn.clicked.connect(lambda *args, table=text: self.change_model(table))

    self.entities.setLayout(layout)


def change_model(self, table):
    print(table)
    self.main_model = pandasModel(good_data(table, directory))
    self.view.setModel(self.main_model)
    self.view.show()