Search code examples
pythonpyqtpyqt5qwidget

PyQt5 add widgets with a loop dynamically


I'm trying to write a simple program that will display pc drives information like letter assigned, total memory in GB etc. Since everyone has a different number of drives this must be dynamic. I am using PyQt5 for GUI. I am trying to display letters of my drives but I can't seem to be able to dynamically add new widgets, I always get the last letter only. Here's how it looks like now. First I setup a grid:

self.gridLayoutWidget_3 = QtWidgets.QWidget(self.centralwidget)
self.gridLayoutWidget_3.setGeometry(QtCore.QRect(10, 210, 741, 71))
self.gridLayoutWidget_3.setObjectName("gridLayoutWidget_3")
self.DrivesData = QtWidgets.QGridLayout(self.gridLayoutWidget_3)
self.DrivesData.setContentsMargins(0, 0, 0, 0)
self.DrivesData.setObjectName("DrivesData")

Then I try to add new label widgets depending on the number of drives:

for disk in disksInfo:
    self.DRIVELETTERSPACE = QtWidgets.QLabel(self.gridLayoutWidget_3)
    self.DRIVELETTERSPACE.setObjectName("DRIVELETTERSPACE")
    self.DrivesData.addWidget(self.DRIVELETTERSPACE, 1, 0, 1, 1)

With the above code all I get displayed is the last drive's letter(E:). I think I understand that I shouldn't name all of them DRIVELETTERSPACE but then how can I make the names dynamic as well? Also, is this how I can dynamically add widgets in pyqt5? Or should I make the grid dynamic as well? Thanks.


Solution

  • In your code you have 2 errors, the first case is that you are adding the widget to the same position for it you must create some method to be able to vary the indices; the other error is to create a member of the class as iterator, for this you just delete self, for example:

    key = 0 
    for disk in disksInfo: 
        DRIVELETTERSPACE = QtWidgets.QLabel(self.gridLayoutWidget_3) 
        DRIVELETTERSPACE.setObjectName("DRIVELETTERSPACE") 
        DrivesData.addWidget(DRIVELETTERSPACE, key, 0) 
        key += 1
    

    If you want to save the widget it is advisable to save them in a list or dictionary since later we can obtain them through an index or key, respectively.