How to change the color of QStringListModel items?

后端 未结 1 1644
不知归路
不知归路 2021-01-05 10:51

I have

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

which I fill with data like this:

         


        
1条回答
  •  -上瘾入骨i
    2021-01-05 11:21

    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(); 
                return true;
            }
    
            return QStringListModel::setData(index, value, role);
        }
    private:
        std::map m_rowColors;
    };
    

    0 讨论(0)
提交回复
热议问题