解決方案是使用委託並重寫負責顯示正常狀態下的外觀的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