[英]Displaying QTableWidgetItem's text with different colors via a QStyledItemDelegate
我想用不同的顏色顯示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
嗎?
我認為在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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.