简体   繁体   English

PyQt5动态添加带有循环的小部件

[英]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. 我正在尝试编写一个简单的程序,该程序将显示PC驱动器信息,例如分配的字母,以GB为单位的总内存等。由于每个人的驱动器数量不同,因此它必须是动态的。 I am using PyQt5 for GUI. 我将PyQt5用于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:). 使用上面的代码,我所显示的只是最后一个驱动器的字母(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? 我想我知道我不应该将所有名称都命名为DRIVELETTERSPACE,但是如何使名称动态化呢? Also, is this how I can dynamically add widgets in pyqt5? 另外,这是我如何在pyqt5中动态添加小部件吗? Or should I make the grid dynamic as well? 还是应该使网格动态化? Thanks. 谢谢。

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; 在您的代码中,您有2个错误,第一种情况是您要将小部件添加到同一位置,因此必须创建某种方法来改变索引; the other error is to create a member of the class as iterator, for this you just delete self, for example: 另一个错误是将类的成员创建为迭代器,为此,您只需删除self,例如:

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. 如果要保存小部件,建议将它们保存在列表或字典中,因为稍后我们可以分别通过索引或键来获取它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM