简体   繁体   English

通过QStyledItemDelegate以不同的颜色显示QTableWidgetItem的文本

[英]Displaying QTableWidgetItem's text with different colors via a QStyledItemDelegate

I want to display parts of the text of a QTableWidgetItem in different colors (a part of it should be displayed red). 我想用不同的颜色显示QTableWidgetItem的文本的一部分(它的一部分应该显示为红色)。

What I found is using a QStyledItemDelegate , reimplementing the paint function and display a QTextDocument that uses the the item text and added HTML. 我发现使用QStyledItemDelegate ,重新实现paint功能并显示使用项目文本和添加的HTML的QTextDocument

This enables HTML for the text: 这将为文本启用HTML:

void DifferencesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    painter->save();

    QTextDocument document;
    document.setHtml(index.data().toString());
    document.setPageSize(option.rect.size());

    QAbstractTextDocumentLayout::PaintContext context;
    painter->translate(option.rect.x(), option.rect.y());
    document.documentLayout()->draw(painter, context);

    painter->restore();
}

However, the result has some pixels offset compared to the "normal" display (which could most probably fixed somehow in a consistent way), but I wonder if there's a simpler method. 但是,与“正常”显示相比,结果有一些像素偏移(它很可能以一致的方式固定),但是我想知道是否有更简单的方法。 I do not need HTML at all, I just want to change the color of some part of the text. 我根本不需要HTML,我只想更改文本某些部分的颜色。

So is it possible to draw the item's text (letter by letter) and to set the color for each letter without having to use a QTextDocument ? 因此,可以绘制项目的文本(逐个字母)并为每个字母设置颜色,而不必使用QTextDocument吗?

I think there is no standard way to paint such things in Qt. 我认为在Qt中没有标准的方法可以绘制此类内容。 Look at the code below. 看下面的代码。 You can draw each particular character of the text. 您可以绘制文本的每个特定字符。 In this case you should calculate the character paint place opt.rect manually. 在这种情况下,您应该手动计算字符绘制位置opt.rect But it works. 但这有效。 In the example characters have red and green colors. 在示例中,字符具有红色和绿色。

void DifferencesDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, 
                                 const QModelIndex& index ) const
{
  painter->save();

  QColor colors[2] = {Qt::red, Qt::green};
  QStyleOptionViewItem opt = option;
  initStyleOption(&opt, index);
  opt.text.clear();

  QStyle* style = opt.widget ? opt.widget->style() : QApplication::style();
  style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);

  QString text = index.data().toString();

  for (int i = 0, t = text.count(); i < t; ++i)
  {
    opt.text = text[i];
    painter->setPen(QColor(colors[i % 2]));
    opt.rect.moveRight(opt.rect.right() + 10); // <-- calculate the character paint place
    style->drawItemText(painter, opt.rect, opt.displayAlignment, opt.palette, true, 
                        opt.text);
  }

  painter->restore();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM