您走在正确的轨道上。您的代码无效,因为您没有调用
QTableWidgetItem的
setData()功能,而是试图为其分配一个值。你有
item.setData = (Qt.DisplayRole,intValue)
代替
item.setData(Qt.DisplayRole,intValue)
另外,在读回数据时,不仅显示了位置,还显示了数据本身(作为QVariant)。您应该发现可以
item.data(Qt.DisplayRole).toString()通过转换
QVariant(通过其
.toString()方法)将数据作为字符串返回。
这是一个快速的工作示例,仅用于演示:
import sysfrom PyQt4.QtGui import QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayoutfrom PyQt4.QtCore import Qtclass Widget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.widget_layout = QVBoxLayout() self.table_widget = QTableWidget(101, 1) self.table_widget.setSortingEnabled(True) self.widget_layout.addWidget(self.table_widget) self.setLayout(self.widget_layout) for num in xrange(101): item = QTableWidgetItem() item.setData(Qt.EditRole, num) self.table_widget.setItem(num, 0, item)if __name__ == '__main__': app = QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_())



