解决方案是使用委托并重写负责显示正常状态下的外观的paint方法,我已经基于上面构建了以下类。
self.TableWidget.setItemDelegate(FloatDelegate(3))
例:
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = QTableWidget()
w.setColumnCount(8)
w.setRowCount(8)
for i in range(w.rowCount()):
for j in range(w.columnCount()):
number = (i+1)/(j+1)
w.setItem(i, j, QTableWidgetItem(str(number)))
w.setItemDelegate(FloatDelegate(3, w))
w.show()
sys.exit(app.exec_())
截图:
class FloatDelegate(QItemDelegate):
def __init__(self, decimals, parent=None):
QItemDelegate.__init__(self, parent=parent)
self.nDecimals = decimals
def paint(self, painter, option, index):
value = index.model().data(index, Qt.EditRole)
try:
number = float(value)
painter.drawText(option.rect, Qt.AlignLeft, "{:.{}f}".format(number, self.nDecimals))
except :
QItemDelegate.paint(self, painter, option, index)
在你的情况如下,你应该使用它
加:
按行Ø列:
#only column 2
setItemDelegateForColumn(2, FloatDelegate(3))
#only row 2
setItemDelegateForRow(2, FloatDelegate(3))
如果你想只适用于小区2,3
def paint(self, painter, option, index):
if index.row() == 2 and index.column() == 3:
value = index.model().data(index, Qt.EditRole)
try:
number = float(value)
painter.drawText(option.rect, Qt.AlignLeft, "{:.{}f}".format(number, self.nDecimals))
except :
QItemDelegate.paint(self, painter, option, index)
else:
QItemDelegate.paint(self, painter, option, index)
酷有道理。如果一个单元格是空白的呢?它使程序崩溃。另外,你可以.setItemDelegate在某些单元格上,而不仅仅是整个表格? – dre
它仍然崩溃,当我测试你给的代码时,它是好的,直到我删除单元格中的内容然后它崩溃 – dre
https://drive.google.com/file/d/0BzcHlfStubD3UmJIeUdVT1NwTGs/view?usp=sharing – dre