【问题标题】:Qt, How do I change the text color of one item of a QComboBox? (C++)Qt,如何更改 QComboBox 的一项的文本颜色? (C++)
【发布时间】:2011-03-05 11:15:03
【问题描述】:

我不知道如何更改 QComboBox 的一个特定项目的文本颜色。我能够更改项目的背景颜色:

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

Qt::ForegroundRole 完全没有效果,Qt 4.6,Ubuntu 10.04)

我能够使用样式表更改所有项目的文本颜色,但我不知道如何更改一个指定项目的文本颜色。

感谢您的帮助!

【问题讨论】:

    标签: c++ qt colors qcombobox


    【解决方案1】:

    这和你求婚差不多,但你必须将角色更改为Qt::TextColorRole

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

    【讨论】:

    • 看起来这个角色现在使用 PySide2 已经过时并且没有任何效果。文档说要使用ForegroundRole,但这对我也没有任何作用。也许这就是杰罗姆回答的原因
    • 这在 c++ 中对我有用
    【解决方案2】:

    我从未尝试过这样做,但我想唯一的方法是编写自己的模型,继承QAbstractListModel,重新实现rowCount()data(),您可以在其中设置每个项目的颜色(使用TextColorRole 角色)。

    然后,使用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::TextColorRole)
             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);
    

    我试过了,效果很好。

    【讨论】:

      【解决方案3】:

      不要认为这是解决方案,但是,如果方便的话,在某些情况下,您可以将 QPixmap-s 用于组合框。看看 QComboBox::insertItem 方法。

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 2014-02-21
        • 2013-09-25
        • 2022-11-02
        • 1970-01-01
        • 2020-02-14
        • 2018-09-17
        • 2020-12-19
        • 1970-01-01
        相关资源
        最近更新 更多