我想在一个中显示两列QTableWidget
显示两次刺痛之间的差异(通过之前的一些编辑距离算法计算)。这些部分存储在每个部分的数据中QTableWidgetItem
, as a QStringList
。第一部分必须显示为黑色,接下来的部分必须显示为红色,然后再次交替显示黑色、红色等。
为此我实施了一个QStyledItemDelegate
与定制paint()
最终调用的函数drawText()
method:
void DifferencesDelegate::drawText(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
painter->save();
const QPen defaultPen = painter->pen();
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);
opt.rect.moveRight(opt.rect.right() + 3);
int color = 1;
for (const QString &part : index.data(Qt::UserRole).toStringList()) {
color++;
color = color % 2;
if (color) {
painter->setPen(Qt::red);
} else {
painter->setPen(defaultPen);
}
style->drawItemText(painter, opt.rect, opt.displayAlignment, opt.palette, true, part);
opt.rect.moveRight(opt.rect.right() + painter->fontMetrics().width(part));
}
painter->restore();
}
只要列的宽度足够,就会产生正确的绘制:
但一旦列变小,我就会得到混乱的溢出:
这肯定是由于opt.rect
应用于显示的每个部分,但不适用于整个文本。
唯一的问题是我不知道如何解决这个问题;-) 任何帮助将不胜感激!提前致谢!