如何更改 QStringListModel 项的颜色
How to change the color of QStringListModel items?
我有
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::DisplayRole
和Qt::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;
};
相关文章:
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 如何在内核C++中使用1920x1080x16M图形或类似的16M颜色?(VGA)
- 如何在24位SDL_Surface上设置像素的颜色
- 如何从SDL_Surface获取特定像素的颜色
- 列表视图更改选择颜色
- GtkTreeView 交替行颜色
- dx11 渲染到纹理仅显示透明颜色
- 使用 OpenGL 4.5 更改所选顶点的颜色
- 为什么我的 LEGACY OPENGL 颜色反转了?
- 双击更改 mfc 中列表控件中的行的颜色
- 更改 QT 中按钮的颜色
- 当我使用CHAR_INFO结构时,控制台会无缘无故地改变颜色
- 列表视图项的替代颜色
- GLSL 将 uint 转换为浮点颜色
- std::带有颜色和标题的 clog 包装器无法正确打印整数
- Vec3b:r/g/b 颜色的最大值为 254,而不是 255
- 如何将矢量对象更改为不同的颜色?
- PPM 颜色显示错误
- 如何更改 QGraphicsItem 对象的颜色?
- 如何防止每次 Arduino 启动时颜色数组都是相同的随机数组