I give Qt go and want to have a model display in a custom text color based on its value. This is an optional parameter for rendering it in color, so I would like to avoid using Qt :: ForegroundRole in my model and instead implement it in QStyledItemDelegate. In the following example, I call QStyledDelegate::paint , and then continue to draw an extra copy of the same text in red using painter->drawText . My suggestion is that they should overlap nicely, while in fact when using QStyledDelete::paint there seems to be a margin around the text.
Here is a link to a picture that better shows what I'm talking about:

Now for some relevant source code.
mainwindow.cpp contains:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->treeView->setItemDelegate(new TestDelegate()); QStandardItemModel *model = new QStandardItemModel(this); ui->treeView->setModel(model); QList<QStandardItem*> items; items << new QStandardItem("Moose") << new QStandardItem("Goat") << new QStandardItem("Llama"); model->appendRow(items); }
testdelegate.cpp contains:
void TestDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyledItemDelegate::paint(painter, option, index); if (index.data().toString() == "Goat") { painter->save(); painter->setPen(Qt::red); painter->drawText(option.rect, option.displayAlignment, index.data().toString()); painter->restore(); } }
This above behavior is observed in both test boxes of Windows 7 and Linux Mint with Qt 4.8.x. Text fields on both systems look like x + 3, y + 1; but I'm afraid this might be font dependent and not want hard code offsets that could potentially disrupt the work.
Any ideas?
source share