所以这就是故事:

我有一个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)

我现在面临的问题:

  1. 正常(非粗体)项目 略微缩进(几个像素)。 这可能是一些默认值 行为。我可以缩进我的项目了 也很大胆,但那会发生什么 在不同的平台下?
  2. 通常情况下,当我选择项目时,会有一个带有虚线的小边框(默认的Windows东西?)。在这里我也可以画它,但我想尽可能保持原生。
  3. 现在的问题是:

    是否有另一种方法可以创建一个自定义委托,只有在满足某些条件时才更改字体粗细并保持其余部分不受影响?

    我也尝试过:

    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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top