所以这里的故事:
我有一个使用 QSqlQueryModel 填充它的 QListview。因为根据模型隐藏列的值,某些项目应该以粗体显示,所以我决定制作自己的自定义委托。我正在使用 PyQT 4.5.4,因此从 QStyledItemDelegate 继承是根据文档的方法。我让它工作了,但它有一些问题。
这是我的解决方案:
class TypeSoortDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
model = index.model()
record = model.record(index.row())
value= record.value(2).toPyObject()
if value:
painter.save()
# change the back- and foreground colors
# if the item is selected
if option.state & QStyle.State_Selected:
painter.setPen(QPen(Qt.NoPen))
painter.setBrush(QApplication.palette().highlight())
painter.drawRect(option.rect)
painter.restore()
painter.save()
font = painter.font
pen = painter.pen()
pen.setColor(QApplication.palette().color(QPalette.HighlightedText))
painter.setPen(pen)
else:
painter.setPen(QPen(Qt.black))
# set text bold
font = painter.font()
font.setWeight(QFont.Bold)
painter.setFont(font)
text = record.value(1).toPyObject()
painter.drawText(option.rect, Qt.AlignLeft, text)
painter.restore()
else:
QStyledItemDelegate.paint(self, painter, option, index)
我现在面临的问题:
- 正常(非粗体)项目略微缩进(几个像素)。这可能是一些默认行为。我也可以用粗体缩进我的项目,但是在不同的平台下会发生什么?
- 通常,当我选择项目时,会有一个带有虚线的小边框(默认的 Windows 东西?)。在这里我也可以画它,但我想尽可能地保持原生状态。
现在的问题:
是否有另一种创建自定义委托的方法,该委托仅在满足某些条件时才更改字体粗细,而其余所有内容都保持不变?
我也试过:
if value:
font = painter.font()
font.setWeight(QFont.Bold)
painter.setFont(font)
QStyledItemDelegate.paint(self, painter, option, index)
但这似乎根本不影响外观。没有错误,只是默认行为,没有粗体项目。
欢迎所有建议!