0

Environment:

  • Python 3.7
  • PyQT5

I am trying to make a GUI for software that has a lot of tasks. These tasks are stored in a database and can change in time. A user could add or remove some tasks from our website.

Then the user starts our software which loads a dashboard UI where the user can see a list of buttons with all the tasks. Each button executes one task. This task is a method which has the parameter "task_id" : Click_pushButtonComputerOrSmartphone(task_id)

This is a sample of the main code. I loop in a tuple which contains dictionaries. Each row contains details of each task. It has the task_id which is different for each task.

self.tasks_buttons = []
# WE LOOP ALL THE TAKS
for task in tuple_all_tasks_user:
# DESIGN OF BUTTON
    self.btn.setText(_translate("MainWindow", label))
    font = QtGui.QFont()
    font.setPointSize(9)
    self.btn.setFont(font)
    self.btn.setStyleSheet("background-color: rgb(199, 199, 199);text-align:left;padding-left:30px;")
    self.btn.setIcon(icon)
    self.btn.setObjectName(f"pushButton_{task['platform_name']}_{task['task_id']}")
    print(f"pushButton_{task['platform_name']}_{task['task_id']}")
    self.tasks_buttons.append(self.btn)
    self.btn.clicked.connect(lambda: 
    self.Click_pushButtonComputerOrSmartphone(task['task_id']))
    self.gridLayout.addWidget(self.btn, row, col)

THE PROBLEM:

When I click on any button, it always runs the method with the same ['task_id'] = 52; which is the ['task_id'] of the last task of the tuple_all_tasks_user.

SO it succeeds to display many different buttons (one for each task) in a grid. But when I click the button, it doesn't execute the correct task.

You can see in the code I save all the buttons in a list self.tasks_buttons. When I debug with Pycharm, I can see all my buttons are different objects. enter image description here

So I have the confirmation all the buttons are created as different objects. I printed the ['task_id'] in the console to confirm it changes on each loop.

So I don't know how to "connect" the method "Click_pushButtonComputerOrSmartphone" with the appropriate task_id number.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Gauthier Buttez
  • 1,005
  • 1
  • 16
  • 40
  • use `self.btn.clicked.connect(lambda *args , t=task['task_id']: self.Click_pushButtonComputerOrSmartphone(t))` – eyllanesc Jun 30 '21 at 19:03
  • Using lambdas might be the most concise way. But you might investigate using [QButtonGroup](https://doc.qt.io/qt-5/qbuttongroup.html). It adds a little more overhead, but is often worth the extra hassle. It has a buttonClicked signal when *any* button in the group is clicked. If the task_id is part of the button objectName, you can extract it from there. – bfris Jun 30 '21 at 19:10

0 Answers0