如何更改QStringListModel项目的颜色? [英] How to change the color of QStringListModel items?

查看:549
本文介绍了如何更改QStringListModel项目的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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

我用这样的数据填充:

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?

推荐答案

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

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

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

示例:

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

这篇关于如何更改QStringListModel项目的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆