QTreemodel множественная роль QVariant
Я использую этот пример http://doc.qt.io/qt-5/qtwidgets-itemviews-editabletreemodel-example.html и мне нужно передать цвет как 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 и позволять пользователю устанавливать его и иметь разные цвета для столбца / строки. Очевидно, мне нужно изменить метод 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 (в красном цвете). Любая помощь будет оценена. Спасибо
1 ответ
Вы должны сохранить цвет где-нибудь. Один из вариантов - добавить его в 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()
возвращаешь что-то вроде item->getColor()
,
Кроме того, вам не нужно использовать QBrush
AFAIK можно просто вернуть QColor
как ForegroundRole
,