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

发布于 2024-09-28 02:43:53 字数 40 浏览 0 评论 0原文

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

Is there a way to set a different background color for each item in a QComboBox ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎盛开的樱花 2024-10-05 02:43:53

我想唯一的方法是编写自己的模型,继承 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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文