【问题标题】:Displaying QTableWidgetItem's text with different colors via a QStyledItemDelegate通过 QStyledItemDelegate 以不同颜色显示 QTableWidgetItem 的文本
【发布时间】:2019-04-05 10:40:02
【问题描述】:

我想以不同的颜色显示QTableWidgetItem 的部分文本(其中一部分应该显示为红色)。

我发现使用QStyledItemDelegate,重新实现paint 函数并显示使用项目文本并添加HTML 的QTextDocument

这将为文本启用 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();
}

但是,与“正常”显示相比,结果有一些像素偏移(很可能以一致的方式修复),但我想知道是否有更简单的方法。我根本不需要 HTML,我只想改变部分文本的颜色。

那么是否可以绘制项目的文本(逐个字母)并为每个字母设置颜色而无需使用QTextDocument

【问题讨论】:

    标签: c++ qt qt5 qstyleditemdelegate qtextdocument


    【解决方案1】:

    我认为在 Qt 中没有标准的方式来绘制这些东西。看看下面的代码。您可以绘制文本的每个特定字符。在这种情况下,您应该手动计算字符绘制位置opt.rect。但它有效。在示例中,字符有红色和绿色。

    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();
    }
    

    【讨论】:

    • 顺便说一句。使用“opt.rect.moveRight(opt.rect.right() +painter->fontMetrics().width(text[i]));”可以获得正确的位置。在循环结束时
    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多