[英]How to change the color of QStringListModel items?
I have 我有
QListView *myListView;
QStringList *myStringList;
QStringListModel *myListModel;
which I fill with data like this: 我用这样的数据填写:
myStringList->append(QString::fromStdString(...));
myListModel->setStringList(*myStringList);
myListView->setModel(myListModel);
I want to change the font-color of some list entries, so I tried: 我想更改一些列表条目的字体颜色,所以我试过:
for (int i = 0; i < myListModel->rowCount(); ++i) {
std::cerr << myListModel->index(i).data().toString().toStdString() << std::endl;
myListModel->setData(myListModel->index(i), QBrush(Qt::green), Qt::ForegroundRole);
}
The data is print out to cerr correctly, but the color does not change. 数据正确打印到cerr,但颜色不会改变。 What am I missing?
我错过了什么?
QStringListModel
supports only Qt::DisplayRole
and Qt::EditRole
roles. QStringListModel
仅支持Qt::DisplayRole
和Qt::EditRole
角色。
You have to reimplement the QStringListModel::data()
and QStringListModel::setData()
methods to support other roles. 您必须重新实现
QStringListModel::data()
和QStringListModel::setData()
方法以支持其他角色。
Example: 例:
class CMyListModel : public QStringListModel
{
public:
CMyListModel(QObject* parent = nullptr)
: QStringListModel(parent)
{}
QVariant data(const QModelIndex & index, int role) const override
{
if (role == Qt::ForegroundRole)
{
auto itr = m_rowColors.find(index.row());
if (itr != m_rowColors.end());
return itr->second;
}
return QStringListModel::data(index, role);
}
bool setData(const QModelIndex & index, const QVariant & value, int role) override
{
if (role == Qt::ForegroundRole)
{
m_rowColors[index.row()] = value.value<QColor>();
return true;
}
return QStringListModel::setData(index, value, role);
}
private:
std::map<int, QColor> m_rowColors;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.