自定义 QStyledItemDelegate:添加粗体项
这是一个故事:
我有一个QListview,它使用QSqlQueryModel来填充内容。因为有些项目需要根据模型中一个隐藏列的值显示为粗体,所以我决定自己做一个自定义的代理。由于我使用的是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)
但这似乎对外观没有任何影响。没有错误,只是默认行为,粗体的项目也没有。
欢迎所有建议!
1 个回答
3
我没有测试过这个,但我觉得你可以这样做:
class TypeSoortDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
get value...
if value:
option.font.setWeight(QFont.Bold)
QStyledItemDelegate.paint(self, painter, option, index)