
QStringListModel里只实现了Qt::EditRole和Qt::DisplayRole,不能直接设置背景色和前景色,所以我们要继承QStringListModel,重写其中的data和setData方法,使其支持Qt::ForegroundRole和Qt::BackgroundRole。
QHStringListModel.h
- #ifndef QHSTRINGLISTMODEL_H
- #define QHSTRINGLISTMODEL_H
-
- #include
- #include
-
- class QHStringListModel : public QStringListModel
- {
- public:
- explicit QHStringListModel(QObject *parent = nullptr);
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
-
- void clear();
-
- private:
- QMap<int, QColor> m_foregroundColorMap;
- QMap<int, QColor> m_backgroundColorMap;
- };
-
- #endif