我的UI的QGridLayout出现问题。在这里,我尝试创建响应用户加载的文件的UI。第一次加载时,QGridLayout会更新,反映文件的内容,一切都很好。但是,下次加载文件时,应该删除网格中的小部件(调用deleteLater()来执行此操作)。发生的事情是他们只是被覆盖了。
图片可能会有所帮助 - 这是您在重复加载两个不同文件后看到的内容。您可以看到“传输消息”'和' Field'文字很好。
我使用的代码如下。如果有人觉得这里没有找到错误,而是代码中的其他地方,我可以发布更多内容。但似乎在这里发现了令人讨厌的逻辑。特别是,每次调用创建一个新的QLabel是否有问题?
def populateTxField(self):
# First delete the old contents
rowcount = self.txGrid.rowCount()
for i in range(1, rowcount):
try:
# Note that these widgets are QLabel type
self.txGrid.itemAtPosition(i, 4).widget().deleteLater()
self.txGrid.itemAtPosition(i, 3).widget().deleteLater()
except AttributeError:
# If widget has already been deleted, ignore the error
pass
key = self.firstTxMessageInfo.currentText()
self.txQLabel_LineContainer = [] # store QLineEdits here
# Now add all of the widgets to the transmission QGridLayout
row = 1 # counter for adding to txGrid row
for field in self.dataBack.messages[key].fields.keys():
newLabel = QtWidgets.QLabel() # Creating a new widget here...
newLabel.setText(field) # Is this problematic?
newLineEdit = QtWidgets.QLineEdit()
# Append to the following list to access from txActivateHandler.
self.txQLabel_LineContainer.append((newLabel, newLineEdit))
# Now update the grid with the new widgets
self.txGrid.addWidget(newLabel, row, 3)
self.txGrid.addWidget(newLineEdit, row, 4)
row += 1
答案 0 :(得分:1)
在删除之前尝试删除小部件:
myWidget = self.txGrid.itemAtPosition(i, 4).widget()
self.txGrid.removeWidget(myWidget);
myWidget.deleteLater()