1
votes

I am learning Qt and I have some difficulty. I was using QTableWidget and when an item receive a double click a change row color:

for (int j = 0; j < ui->tableWidget->horizontalHeader()->count(); j++) {
    ui->tableWidget->item(row, j)->setForeground(color);
}

But now I am using QTableView, I created a QAbstractTableModel to this and work fine. I done some filters with QSortFilterProxyModel and work fine too. But I am not having success to change row color. I already tried things like this:

m_model.setData(m_model.index(1,2) , QColor(Qt::blue), Qt::BackgroundColorRole);

And not work. In model::setData() I wrote some debugs and it joins in function right, but not change color.

bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (data(index, role) != value) {
        qDebug() << index << value << role;
        emit dataChanged(index, index, QVector<int>() << role);
        return true;
    }
    return false;
}

Debug output:

QModelIndex(1,2,0x0,MyModel(0x7fffffffe408)) QVariant(QColor, QColor(ARGB 1, 0, 0, 1)) 8
1
Qabstractitemmodel doesn't store any values on its own. You need to store the choice in your setData() impl and return the color for the corresponding index in your data() impl. - Frank Osterfeld
Thank you @FrankOsterfeld, I made it after your suggestion :) - C. Din

1 Answers

0
votes

You could use own item delegate, in view constructor call function - setItemDelegate

in delegate reimplement paint function:

paint(QPainter *painter, const QStyleOptionViewItem &option, const   QModelIndex &index) const

get info about geometry from QStyleOptionViewItem, about content - QModelIndex

some flags to check state, as example:

if(option.state & QStyle::State_Selected)
{
        painter->save();
        QPen pen(QColor(30, 144, 255, 255), 2, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
        int w = pen.width()/2;
        auto rect = option.rect;
        rect.setX(0);
        painter->setPen(pen);
        painter->drawRect(rect.adjusted(w,w,-w,-w));
        painter->restore();
}

As for double click event - in view re-implement mouseDoubleClickEvent, get index (for example: indexAt(event->pos())) and store some color data, then use that data at delegate's paint function.