为何QTableWidget代码中Item被重复赋值?删除后显示异常
QTableWidgetItem Matters in Your Pyuic-Generated Code Let's break down exactly what's happening here—this is a common gotcha with Qt's QTableWidget that trips up a lot of developers when they first work with pyuic output.
The Core Issue: QTableWidgetItem Instances Are Not Reusable
Here's the key rule you need to remember: each cell in a QTableWidget requires its own unique QTableWidgetItem instance. You can't create one item and assign it to multiple cells—Qt's widget system doesn't support sharing item instances like that, and doing so causes internal state conflicts that break your display.
Why That "Duplicate" Assignment Isn't Redundant
When pyuic generates code with two lines of item = QtWidgets.QTableWidgetItem(), it's not wasting code. Each line creates a brand new, independent item object. The item variable is just a temporary placeholder to hold the new instance while you configure it (set text, alignment, etc.) and then pass it to the table.
Your generated code is probably doing something like this under the hood:
# First item for cell (0,0) item = QtWidgets.QTableWidgetItem() item.setText("First Column") self.tableWidget.setItem(0, 0, item) # Second item for cell (0,1) item = QtWidgets.QTableWidgetItem() # Creates a NEW object, overwriting the variable item.setText("Short") self.tableWidget.setItem(0, 1, item)
The variable reuse is just a convenience—pyuic doesn't need a new variable name each time, it just reuses item to hold the latest new instance before handing it off to the table.
What Happens When You Delete the Second Assignment?
If you remove that second item = QtWidgets.QTableWidgetItem() line, you're reusing the same item instance for both cells. Your code becomes:
item = QtWidgets.QTableWidgetItem() item.setText("First Column") self.tableWidget.setItem(0, 0, item) # No new item created—reusing the same object! item.setText("Short") self.tableWidget.setItem(0, 1, item)
When you call setText("Short") the second time, you're modifying the same item that's already attached to the first cell. Then when you assign it to the second cell, Qt's internal management gets confused: the same item is registered in two places, so it ends up displaying the last-set text ("Short") in both cells. That's why you see 'Short | Short' instead of your intended values.
Quick Recap
- Never reuse a single
QTableWidgetItemacross multiple cells—each cell needs its own instance. - The "duplicate"
item = ...lines in pyuic code are creating new objects, not repeating assignments to the same object. - Reusing the same item causes state conflicts, leading to unexpected display behavior.
内容的提问来源于stack exchange,提问作者iSwimInTheC

