I am trying to add a series of buttons and their actions to a QGridLayout using python. The relevant section of code is shown below.
It checks to see if a list named "popupList" exists and, if so, runs the code. popupList contains one or more lists within it - each containing a string, a path to an image and a function name. An example is given below.
The idea is that, because in this case there are two lists, two buttons will added to the grid. The text on the buttons will be "button1" and "button2". The actions associated with each button will be determined by the "popupPage" function seen in the 6th line of the code.
popupPage creates a new central widget containing (among other things) the image from the file 'image1' for button1 and 'image2' for button 2. It also contains a button which, when clicked, will call function1 or function2 depending on whether button1 or button2 is clicked respectively.
If I use popupPage one line at at time rather than in the loop presented below everything works perfectly. However, if I use the loop the buttons get created in the correct grid position and with the correct text and hotkeys.
However, when clicked the action is always that of the final entry in popupList. So in the example given I would have two buttons named "button1" and "button2" but when clicked the action is always that of "button2". If I popupList contains more than two lists all the buttons get created but the action when clicked is always that of the final entry.
I've seen similar problems solved using classes in object orientated programming but, unfortunately, I have no real knowledge in that area so I'm trying to keep it simple. It seems to me the problem is somehow related to the fact that the buttons get created with each iteration of the loop but the action is only triggered when a button is clicked at runtime and the code is only remembering the last function passed to popupPage.
I hope this post is clear enough and that someone can help me.
Thanks, Tom
popupList example:
[['&button1', ./image1, function1], ['b&utton2', ./image2, function2]]
Section of code being used to create the buttons, their actions and add them to the grid (which has been given the name "contentsGrid":
if popupList:
#Create a dictionary to contain details of each button
buttonsDict = {}
#Create the first button at postion (1, 1) and increment the row by one for each extra button
z = 1
for detail in popupList:
buttonsDict[detail[0]] = QPushButton(text=detail[0])
buttonsDict[detail[0]].clicked.connect(lambda: popupPage(detail[1], detail[2]))
contentsGrid.addWidget(buttonsDict[detail[0]], z, 1)
z = z + 1