QStyledItemDelegate :: paint - Why is my text not aligned correctly?

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:

enter image description here

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?

+4
source share
1 answer

option.rect is the bounding box of the cell representing the item, so it does not contain a field. The required offset can be obtained by querying the rectangle of the subitem from the current QStyle :

 ... QStyle* style = QApplication::style(); QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &option); ... painter->drawText(textRect, option.displayAlignment, index.data().toString()); 

However ... This is fully consistent with the current QStyle , whether it implements it or not. When I tried to use it with Qt v4.8 for my application on Linux / Gnome, it was wrong and not really implemented in the Qt source code. Therefore, I had to hard code the offset, for me it was not as bad as I intended to write my own QStyle - you cannot be “happy”.

+1
source

All Articles