QTreemodel 多个 QVariant 角色

QTreemodel multiple QVariant role

我正在使用此示例 http://doc.qt.io/qt-5/qtwidgets-itemviews-editabletreemodel-example.html 并且需要将 Color 作为 Forgoundroll 传递给数据,但无法弄清楚。

在 treemodel.cpp 中,我已将数据更改如下..

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());
}

... 有效(项目获得红色,但需要从 mainwindow.cpp 控制颜色并让用户设置它并且每个 column/row 具有不同的颜色。显然我需要更改 Treemodel:setdata 方法,但无法弄清楚。

求setdata方法..

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;
}

来自 mainwindow.cpp 我需要将其设置为 ..

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

...但我得到的是#ffffff 颜色的文本(虽然是红色)。 任何帮助,将不胜感激。谢谢

你必须把颜色保存在某个地方。一种选择是将其添加到 TreeItem:

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

private:
    ...
    QColor color;
};

并且在模型中,如果它是合适的角色,您只需设置颜色,大致如下:

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;
}

同样地,在 getData() 中,你 return 类似于 item->getColor()

此外,您不必使用 QBrush,据我所知,您可以简单地将 return QColor 作为 ForegroundRole.