自定义QStyledItemDelegate:添加粗体项

2024-10-01 05:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

故事是这样的:

我有一个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东西?)。在这里我也可以画出来,但我想尽可能地保持原汁原味。在

现在的问题是:

有没有另一种方法可以创建一个自定义委托,它只在满足某些条件时更改字体粗细,而不影响其余所有条件?在

我也试过:

^{pr2}$

但这似乎一点也不影响外表。没有错误,只有默认行为,没有粗体的项目。在

欢迎所有建议!在


Tags: 项目textindexmodelifvaluerecordqt
1条回答
网友
1楼 · 发布于 2024-10-01 05:01:02

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

class TypeSoortDelegate(QStyledItemDelegate):

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

    QStyledItemDelegate.paint(self, painter, option, index)

相关问题 更多 >