Try removing the widget before deleting it:
myWidget = self.txGrid.itemAtPosition(i, 4).widget()
self.txGrid.removeWidget(myWidget);
myWidget.deleteLater()
Pregunta
I'm having trouble with a QGridLayout for my UI. Here I'm trying to create UI that responds to a file that the user loads. The first time it loads, a QGridLayout is updated reflecting the contents of the file, and everything is fine. However, the next time a file is loaded, what should happen is that the widgets inside the grid should be deleted (Calling deleteLater() to do this). What is happening is that they are just getting overwritten.
A picture might help - this is what you see after repeatedly loading two different files. You can see the 'Transmit Messages' and 'Field' text is fine.
The code I am using is as follows. If someone feels like the error is not found here but elsewhere in the code, I can post more of it. But it seems like the offending logic is found here. In particular, is there a problem with creating a new QLabel with each call?
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
Solución
Try removing the widget before deleting it:
myWidget = self.txGrid.itemAtPosition(i, 4).widget()
self.txGrid.removeWidget(myWidget);
myWidget.deleteLater()