1

I am using PyQt to create a GUI and need to create a periodic table made of buttons. Bellow is part of the code. Each button will require the following code in the method mainLayout(self).

class App(QMainWindow):

    def __init___(self):
        ...

    def mainLayout(self):
        Element1 = QPushButton('shortname', self)
        Element1.setToolTip('longname')
        Element1.setCheckable(True)
        Element1.resize(50, 50)
        Element1.move(x, y)
        Element1.clicked.connect(self.Element1_click)

This is a lot of repetitive code for one button when there will be 118 buttons. I made a GUI in the past which had this same problem and I remember I solved the issue with creating another class which I passed the argument for the unique attributes of each button.

I had something like this in mind where LayoutElm is a class.

LayoutElm(Element1 ,'shortname', 'longname', x, y, Element1_click)

Any ideas would be greatly appreciated.

1 Answers1

0

You just have to create a function that creates the item:

class App(QMainWindow):
    def __init___(self):
        ...

    def mainLayout(self):
        createLayoutElm('shortname', 'longname', (x, y), self.Element1_click)
        createLayoutElm('shortname1', 'longname1', (100, 100), self.Element1_click2)
        ...

    def createLayoutElm(self, name, tooltip, pos, callback):
        btn = QPushButton(name, self)
        btn.setToolTip(tooltip)
        btn.setCheckable(True)
        btn.resize(50, 50)
        btn.move(*pos)
        btn.clicked.connect(callback)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • This is awesome. To make it work I had to put def createLayoutElm(self, name, tooltip, pos, callback): btn = QPushButton(name, self) btn.setToolTip(tooltip) btn.setCheckable(True) btn.resize(50, 50) btn.move(*pos) btn.clicked.connect(callback) Into the def mainLayout(self): method. Because of this I had to take out the self argument. But thank you so much! It works perfectly now! – Harrison Reisinger Apr 26 '18 at 02:51
  • Would you mind explaining what the *pos means? Is it something special to classes? – Harrison Reisinger Apr 26 '18 at 02:58
  • @HarrisonReisinger read https://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean – eyllanesc Apr 26 '18 at 02:59
  • Oh this is very interesting I will definitely use this in the future. Thank you. – Harrison Reisinger Apr 26 '18 at 03:02