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

标签 c++ qt qt4

有没有办法为 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/

相关文章:

c++ - 为什么此方法在未标记为虚拟时表现得像虚拟?

c++ - 在 VS C++ 6.0 中,什么调试工具可以很好地查找内存泄漏的位置?

c++ - QtConcurrent 为多核提供更长的运行时间

python - PySide/Qt : Too many arguments to connect a signal to a slot?

c++ - 抛出导致调用析构函数的异常会使程序崩溃

c++ - 将 C 对象数组包装到 C++ 类中

opencv - libopencv_calib3d : undefined reference to `std::__throw_out_of_range_fmt(char const*, …)@GLIBCXX_3.4.20'

c++ - 如何在 Windows 中从命令行运行 Qt

qt - 如何在隐藏小部件后调整窗口大小同时仍允许调整窗口大小?

python - 如何消除 QTableWidget 中的空白?