QTableWidget显示某些小数,如ex

2024-09-29 21:55:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是QTableWidget显示单元格值的方式。在

我希望单元格在未被编辑时只显示三位小数,当您双击进行编辑时显示完整的值。在


我在后台进行计算,然后设置单元格值。在

V_D = 3/0.7
self.TableWidget.setItem(0, 0, QTableWidgetItem(str(V_D)))

类似于excel格式化单元格以显示特定数字的方式。在

全值:

enter image description here

显示值:

enter image description here

我该怎么做呢?在


Tags: self编辑方式数字excel后台小数str
1条回答
网友
1楼 · 发布于 2024-09-29 21:55:06

解决方案是使用委托并重写paint方法,该方法负责显示正常状态下的外观,我基于上述内容构建了以下类。在

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)

在您的情况下,您应按如下方式使用:

^{pr2}$

示例:

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_())

截图:

enter image description here

enter image description here

加上:

按o行列:

#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)

相关问题 更多 >

    热门问题