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

Ash*_*iya 2 c++ qt qt4

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

Jér*_*ôme 6

我想唯一的方法是编写自己的模型,继承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();
   }
};
Run Code Online (Sandbox Code Playgroud)

现在可以很容易地将这个模型与组合框一起使用:

comboBox->setModel(new ItemList);
Run Code Online (Sandbox Code Playgroud)