簡體   English   中英

修復QTreeWidget上的選定項目熒光筆

[英]Fix selected item highlighter on 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)

它是這樣產生的:

在此處輸入圖片說明

在實施過程中,我有2點意見:

  • 如果只想更改文本顯示的格式,則不應覆蓋paint()方法,因為它不僅可以繪制文本,還可以繪制背景,圖標等。必須重寫drawDisplay()方法。

  • 如果僅要將更改應用於列,則最好使用setItemDelegateForColumn()方法設置委托

考慮到上述情況,解決方案是:

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

加:

如果要執行相同的操作但使用QStyledItemDelegate則解決方案是覆蓋initStyleOption()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM