Greetings all,
Is there a way to set a different background color for each item in a QComboBox
?
Thank in advance
Greetings all,
Is there a way to set a different background color for each item in a QComboBox
?
Thank in advance
I guess the only way to do it would be to write your own model, inheriting QAbstractListModel
, reimplementing rowCount()
and data()
where you can set the background color for each item (using the BackgroundRole
role).
Then, use QComboBox::setModel()
to make the QComboBox
display it.
Here is a simple example, where I created my own list model, inheriting 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();
}
};
It is now easy to use this model with the combo box :
comboBox->setModel(new ItemList);