如何更改 QStringListModel 项的颜色

How to change the color of QStringListModel items?

本文关键字:颜色 QStringListModel 何更改      更新时间:2023-10-16

我有

QListView *myListView;
QStringList *myStringList;
QStringListModel *myListModel;

我用这样的数据填充:

myStringList->append(QString::fromStdString(...));
myListModel->setStringList(*myStringList);
myListView->setModel(myListModel);

我想更改某些列表条目的字体颜色,所以我尝试了:

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

数据已正确打印到 cerr,但颜色不会改变。我错过了什么?

QStringListModel仅支持Qt::DisplayRoleQt::EditRole角色。

您必须重新实现QStringListModel::data()QStringListModel::setData()方法以支持其他角色。

例:

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