gpt4 book ai didi

c++ - Qt QComboBox 每个项目具有不同的背景颜色?

转载 作者:行者123 更新时间:2023-11-30 02:11:02 25 4
gpt4 key购买 nike

有没有办法为 QComboBox 中的每个项目设置不同的背景颜色?

最佳答案

我想唯一的方法是编写自己的模型,继承QAbstractListModel,重新实现rowCount()data() 您可以在其中设置每个项目的背景颜色(使用 BackgroundRole 角色)。

然后,使用QComboBox::setModel()使QComboBox显示它。

这是一个简单的示例,我在其中创建了自己的列表模型,继承了QAbstractListModel:

class ItemList : public QAbstractListModel
{
Q_OBJECT
public:
ItemList(QObject *parent = 0) : QAbstractListModel(parent) {}

int rowCount(const QModelIndex &parent = QModelIndex()) const { return 5; }
QVariant data(const QModelIndex &index, int role) const {
if (!index.isValid())
return QVariant();

if (role == Qt::BackgroundRole)
return QColor(QColor::colorNames().at(index.row()));

if (role == Qt::DisplayRole)
return QString("Item %1").arg(index.row() + 1);
else
return QVariant();
}
};

现在可以轻松地将这个模型与组合框一起使用:

comboBox->setModel(new ItemList);

关于c++ - Qt QComboBox 每个项目具有不同的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3985176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com