PDA

View Full Version : QAbstractModel - BackgroundRole returning brush with pattern has inconsistent results



alketi
9th December 2014, 21:57
I want to populate cells on a QTableView with a brush pattern + color. (Qt 5.2.1)

In my QAbstractItemModel subclass my data method is as follows:


QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();

if (role == Qt::TextAlignmentRole)
return Qt::AlignCenter;

if (role == Qt::BackgroundRole)
{
QBrush brush(Qt::BDiagPattern);
brush.setColor(QColor(Qt::red));
return brush;
}

if (role != Qt::DisplayRole && role != Qt::EditRole)
return QVariant();

return (m_data.getValueText());
}

The result of this is that each cell has a different variant of the "BDiagPattern" pattern, as seen in the attached picture!

And, if I manually resize the tableview cells, picture 1 --> picture 2, the pattern variant continues to change from cell to cell.

Am I missing something, or is this a bug??

10797 10798

alketi
10th December 2014, 19:30
Any ideas why this may be behaving as shown?

wysota
10th December 2014, 20:30
Could you state what is the expected behaviour and how does it differ from what you actually get?

Edit:

Using this code:

#include <QtWidgets>

int main(int argc, char **argv) {
QApplication app(argc, argv);
QStandardItemModel model(4,4);
QBrush b(Qt::BDiagPattern);
b.setColor(Qt::red);
for(int r = 0; r<4; ++r) {
for(int c = 0; c<4; ++c) {
QStandardItem *item = new QStandardItem;
item->setBackground(b);
model.setItem(r, c, item);
}
}
QTableView view;
view.setModel(&model);
view.show();
return app.exec();
}

... I get this:

10799

The result is the same with Qt4, by the way.

alketi
10th December 2014, 21:08
wysota, your image is exactly the behavior I expect.

But, as you can see from my pictures, I'm getting a different pattern density in each square.

Note that I'm using the data() callback to provide the background pattern. Can you try again with that approach?

Perhaps the cells are being redrawn multiple times -- which is why the pattern is more dense on some cells?? How can I prevent this?

wysota
10th December 2014, 22:16
Note that I'm using the data() callback to provide the background pattern. Can you try again with that approach?
My approach uses data() as well.


Perhaps the cells are being redrawn multiple times -- which is why the pattern is more dense on some cells??

No, if you did not provide a custom delegate, the standard one wouldn't do that.

alketi
11th December 2014, 18:18
wysota, your answer pointed me to the problem!

I had a custom delegate to provide used to provide an outline on a selected cell, and didn't have all the necessary code inside of the "if (option.state & QStyle::StateSelected)" block. Upon fixing that, the pattern is now correctly displayed.

Thank you for the help!