2

I am using this Example http://doc.qt.io/qt-5/qtwidgets-itemviews-editabletreemodel-example.html and need to pass a Color as Forgoundroll to the data, but cant figure it out.

In the treemodel.cpp i have altered the data as following..

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

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

    TreeItem *item = getItem(index);

    if(role==Qt::ForegroundRole) {

        QBrush redBackground(QColor(Qt::red));
                    return redBackground;
    } else
        return item->data(index.column());
}

... which works (items get the red color, but need to control the color from the mainwindow.cpp and let user set it and have different colors per column/row. Apparently i need to alter the Treemodel:setdata method, but cant figure it out.

So seeking for the setdata method..

bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::EditRole && role != Qt::ForegroundRole )
        return false;

    TreeItem *item = getItem(index);
    bool result;
    if(role==Qt::ForegroundRole ) {
        //do what ???????
    } else {
        result= item->setData(index.column(), value);
    }
    if (result)  emit dataChanged(index, index);

    return result;
}

From mainwindow.cpp i need to set it like ..

model->setData(child, QVariant(rowdata.at(column)), Qt::EditRole); // this provides the text of the inserted row
model->setData(child, QVariant(QBrush(Qt::red)), Qt::ForegroundRole); // this to provide its color

... but i get the text of the color #ffffff instead (in red color though). Any help would be appreciated. Thanks

BobR
  • 85
  • 6

1 Answers1

1

You have to save the color somewhere. One option is to add it to the TreeItem:

class TreeItem
{
public:
    ...
    void setColor(const QColor& color) { this->color = color; }
    const QColor& getColor() const { return color; }

private:
    ...
    QColor color;
};

And in the model, you simply set the color if it's the appropriate role, something along these lines:

bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    TreeItem *item = getItem(index);
    bool result = false;

    switch (role)
    {
        case Qt::EditRole:
            result = item->setData(index.column(), value);
            break;
        case Qt::ForegroundRole:
            item->setColor(value.value<QColor>());
            result = true;
            break;
        default:
            break;
    }

    if (result)
        emit dataChanged(index, index);

    return result;
}

And similarly in getData(), you return something like item->getColor().

Also, you don't have to use QBrush, AFAIK you can simply return QColor as a ForegroundRole.

Jaa-c
  • 5,017
  • 4
  • 34
  • 64