QTableWidget
2 つの文字列の違いを示す内に 2 つの列を表示したいと考えています(以前はいくつかのレーベンシュタイン距離アルゴリズムによって計算されていました)。パーツは、各 のデータ内に として格納されQTableWidgetItem
ますQStringList
。最初の部分を黒で表示し、次の部分を赤で表示し、次に黒、赤などと交互に表示する必要があります。
この目的のために、最終的にメソッドを呼び出すQStyledItemDelegate
カスタム関数を実装しました。paint()
drawText()
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
これは、テキスト全体ではなく、ディスプレイの各部分に適用されていることが原因であることは間違いありません。
唯一の問題は、これを修正する方法がわからないことです;-)どんな助けも大歓迎です! 前もって感謝します!