Reputation: 109
I'm using PyQT5 to create an interface with pandas dataframes. I wish to change the dataframe when I click a button. I managed to do it manually, but I need to iterate over the buttons since the number of dataframes is a variable. I already seen other questions but I couldn't reproduce in my code. Here's an snippet:
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()
Upvotes: 1
Views: 312
Reputation: 243887
Do not use global variables or "globals" as it can generate silent errors that are difficult to debug, instead make those variables attributes of the class. On the other hand, you just have to iterate over the "files" and make the connection:
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()
Upvotes: 3