Qt, How do I change the text color of one item of a QComboBox? (C++)

穿精又带淫゛_ 提交于 2019-12-06 19:43:30

问题


I cannot figure out how to change the text color of one particular item of a QComboBox. I was able to change the Background color of an item:

comboBox->setItemData(i, Qt::green, Qt::BackgroundRole);

(Qt::ForegroundRole had no effect at all, Qt 4.6, Ubuntu 10.04)

and I was able to change the text color of all items with a stylesheet but I cannot figure out how to change the text color of one specified item.

Thanks for your Help!


回答1:


It's almost like you propose, but you have to change the role to Qt::TextColorRole.

comboBox->setItemData(0, QBrush(Qt::red), Qt::TextColorRole);  



回答2:


I never tried to do it, but 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 color for each item (using the TextColorRole role).

Then, use QComboBox::setModel() to make the QComboBox display it.

UPDATE

I was able to do what you want using the above solution. Here is a simple example.

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::TextColorRole)
         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);

I tried it and it's working fine.




回答3:


Don't think that this is the solution, but, if it is handy, in some cases you could use QPixmap-s for your combo box. Take a look at QComboBox::insertItem methods.



来源:https://stackoverflow.com/questions/3070450/qt-how-do-i-change-the-text-color-of-one-item-of-a-qcombobox-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!