python - 修复 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
推荐阅读
- mongodb - 输入'文件
' 不可分配给类型 'Pick - java - 在 docker 上运行 java fie 返回错误
- javascript - 使用 split() 仅删除字符串中的最后一个 _?
- api - 循环 Power BI API 调用以提取未知数量的记录以避免速率限制?
- html - laravel dompdf 不能正确渲染带有 rowspan 和 colspan 的复杂 html
- python - send_keys 的 selenium 错误:str' 对象没有属性 'send_keys'
- elasticsearch - 更新 Elasticsearch _mapping 中的字符串参数
- swift - 如何使 user_target_xconfig pod install 警告静音
- python - Python:将图像发送到 Flask API 以存储在服务器上以供进一步使用
- javascript - 尝试通过 discord.js 中的消息 ID 对消息做出反应