How to change the color of QStringListModel items?

让人想犯罪 __ 提交于 2019-12-19 02:29:11

问题


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. What am I missing?


回答1:


QStringListModel supports only Qt::DisplayRole and Qt::EditRole roles.

You have to reimplement the QStringListModel::data() and QStringListModel::setData() methods to support other roles.

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


来源:https://stackoverflow.com/questions/37781426/how-to-change-the-color-of-qstringlistmodel-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!