修复QTreeWidget上的选定项目荧光笔

时间:2019-07-11 22:35:35

标签: python python-3.x pyqt pyqt5 qtreewidget

我有一个其中包含值的QTreeWidget,我只想显示一定数量的小数,但为了计算目的保留精度。我可以正常使用它,但是所选项目的突出显示被弄乱了,并在绘制的单元格周围显示白色。

如何固定突出显示,以便整行显示为纯蓝色?

class InitialDelegate(QtWidgets.QItemDelegate):
    'Changes number of decimal places in gas analysis self.chosen table'
    def __init__(self, decimals, parent=None):
        super().__init__(parent)
        self.nDecimals = decimals
    def paint(self, painter, option, index):
        if index.column() == 1:
            value = index.model().data(index, QtCore.Qt.DisplayRole)
            try:
                number = float(value)
                painter.drawText(option.rect, QtCore.Qt.AlignCenter , "{:.{}f}".format(number, self.nDecimals))
            except:
                QtWidgets.QItemDelegate.paint(self, painter, option, index)
        else:
            QtWidgets.QItemDelegate.paint(self, painter, option, index)

这是它产生的东西:

enter image description here

1 个答案:

答案 0 :(得分:2)

我在执行它时有2个观察结果:

  • 如果您只想更改文本显示的格式,则不应覆盖paint()方法,因为它不仅可以绘制文本,还可以绘制背景,图标等。 {3}}方法必须被覆盖。

  • 如果仅要将更改应用于列,则最好使用drawDisplay()方法设置委托。

考虑到上述情况,那么解决方法是:

from PyQt5 import QtCore, QtGui, QtWidgets


class InitialDelegate(QtWidgets.QItemDelegate):
    "Changes number of decimal places in gas analysis self.chosen table"

    def __init__(self, decimals, parent=None):
        super().__init__(parent)
        self.nDecimals = decimals

    def drawDisplay(self, painter, option, rect, text):
        option.displayAlignment = QtCore.Qt.AlignCenter
        try:
            number = float(text)
            text = "{:.{}f}".format(number, self.nDecimals)
        except:
            pass
        super().drawDisplay(painter, option, rect, text)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QTreeWidget(columnCount=3)
    delegate = InitialDelegate(2, w)
    w.setItemDelegateForColumn(1, delegate) # <---
    w.setHeaderLabels(["Gas Component", "Molecular Weight", "Mol%"])
    it = QtWidgets.QTreeWidgetItem(["Hexane", "86.1777", ""])
    w.addTopLevelItem(it)
    w.show()
    sys.exit(app.exec_())

加号:

如果您想使用setItemDelegateForColumn()做同样的事情,那么解决方法是覆盖QStyledItemDelegate

class InitialDelegate(QtWidgets.QStyledItemDelegate):
    "Changes number of decimal places in gas analysis self.chosen table"

    def __init__(self, decimals, parent=None):
        super().__init__(parent)
        self.nDecimals = decimals

    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        option.displayAlignment = QtCore.Qt.AlignCenter
        try:
            text = index.model().data(index, QtCore.Qt.DisplayRole)
            number = float(text)
            option.text = "{:.{}f}".format(number, self.nDecimals)
        except:
            pass