最近在做项目中遇到需求,在下拉框中,文本需要设置不同的颜色,遂网上了解了一番后,得出以下代码,可以完美实现效果,现分享出来!
1.实现效果
2.自定义类
colorcombobox.h
#ifndef COLORCOMBOBOX_H
#define COLORCOMBOBOX_H#include <QComboBox>
#include <QWidget>// 自定义ComboBox类,用于控制当前项颜色
class ColorComboBox : public QComboBox {Q_OBJECT
public:explicit ColorComboBox(QWidget *parent = nullptr);/// 添加带颜色的项void addColorItem(const QString &text, const QColor &color = Qt::black);private slots:/// 更新当前项颜色void updateCurrentItemColor(int index);protected:// 重写paintEvent以绘制当前项void paintEvent(QPaintEvent *e) override;
};#endif // COLORCOMBOBOX_H
colorcombobox.cpp
#include "colorcombobox.h"
#include "config/appinfo.h"// 自定义委托类
class CustomColorDelegate : public QStyledItemDelegate {
public:CustomColorDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) { }~CustomColorDelegate() override { }void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {QStyleOptionViewItem opt = option;initStyleOption(&opt, index);// 获取该项的颜色QVariant colorVar = index.data(Qt::UserRole + 1); // 使用UserRole+1存储颜色QColor textColor = colorVar.isValid() ? colorVar.value<QColor>() : Qt::black;// 检查是否选中if (opt.state & QStyle::State_Selected) {painter->fillRect(opt.rect, opt.palette.highlight().color()); // 使用高亮颜色填充背景painter->setPen(opt.palette.highlightedText().color()); // 设置高亮文本颜色} else {painter->fillRect(opt.rect, Qt::white); // 使用白色填充背景painter->setPen(textColor); // 设置自定义文本颜色}// 绘制文本painter->drawText(opt.rect.adjusted(5, 0, 0, 0),Qt::AlignVCenter | Qt::AlignLeft,opt.text);}
};ColorComboBox::ColorComboBox(QWidget *parent) : QComboBox(parent) {// 设置自定义委托setItemDelegate(new CustomColorDelegate(this));// 连接信号,当选择变化时更新当前项颜色connect(this, QOverload<int>::of(&QComboBox::currentIndexChanged),this, &ColorComboBox::updateCurrentItemColor);
}void ColorComboBox::addColorItem(const QString &text, const QColor &color) {addItem(text);setItemData(count() - 1, color, Qt::UserRole + 1); // 存储颜色setItemData(count() - 1, color, Qt::ForegroundRole); // 兼容旧代码// 如果这是第一项,设置当前颜色if (count() == 1) {setCurrentIndex(0);}
}void ColorComboBox::updateCurrentItemColor(int index) {if (index < 0) return;// 获取当前项的颜色QVariant colorVar = itemData(index, Qt::UserRole + 1);if (colorVar.isValid()) {QColor color = colorVar.value<QColor>();// 设置当前项的颜色(通过样式表)setStyleSheet(QString("QComboBox {"" color: %1;"" background-color: white;"" border: 1px solid #ccc;"" border-radius: 4px;"" padding: 5px;""}""QComboBox::drop-down {"" border: none;""}").arg(color.name()));}
}void ColorComboBox::paintEvent(QPaintEvent *e) {QComboBox::paintEvent(e);// 如果需要,可以在这里添加自定义绘制代码
}
3.使用
// 创建颜色ComboBox
ColorComboBox *colorCombo = new ColorComboBox(this);
colorCombo->addColorItem("", Qt::black);
colorCombo->addColorItem("合格", QColor("#32CD32")); // 石灰绿色
colorCombo->addColorItem("不合格", Qt::red); // 红色// 设置初始选择
colorCombo->setCurrentIndex(0);