Python 自定义QStyledItemDelegate:添加粗体项

Python 自定义QStyledItemDelegate:添加粗体项,python,user-interface,pyqt,Python,User Interface,Pyqt,故事是这样的: 我有一个QListview,它使用QSqlQueryModel来填充它。因为一些项目应该根据模型的隐藏列的值以粗体显示,所以我决定创建自己的自定义委托。我使用的是PyQT 4.5.4,因此根据文档,从QStyledItemDelegate继承是一种方式。我让它工作,但有一些问题 以下是我的解决方案: class TypeSoortDelegate(QStyledItemDelegate): def paint(self, painter, option, index):

故事是这样的:

我有一个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)
    
    但这似乎根本不会影响外观。没有错误,只有默认行为,没有粗体项目


    欢迎大家提出建议

    我还没有测试过,但我认为您可以:

    class TypeSoortDelegate(QStyledItemDelegate):
    
    def paint(self, painter, option, index):
        get value...
        if value:
            option.font.setWeight(QFont.Bold)
    
        QStyledItemDelegate.paint(self, painter, option, index)