// ExtendedComboBox.h
#ifndef EXTENDEDCOMBOBOX_H
#define EXTENDEDCOMBOBOX_H
#include <QComboBox>
#include <QColor>
class ExtendedComboBox : public QComboBox{
Q_OBJECT
public:
explicit ExtendedComboBox(QWidget *parent = nullptr) : QComboBox(parent), borderRadius(4), backgroundColor(Qt::gray) {}
// 设置圆角半径
void setBorderRadius(int radius) {
borderRadius = radius;
update(); // 触发重绘
}
// 设置背景颜色
void setBackgroundColor(const QColor &color) {
backgroundColor = color;
update(); // 触发重绘
}
protected:
void paintEvent(QPaintEvent *event) override {
Q_UNUSED(event);
QStyleOptionComboBox option;
initStyleOption(&option);
QStylePainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addRoundedRect(option.rect, borderRadius, borderRadius);
// 使用成员变量设置背景颜色
painter.fillPath(path, backgroundColor);
painter.setPen(option.palette.color(QPalette::ButtonText));
painter.drawText(option.rect, Qt::AlignLeft | Qt::AlignVCenter, option.currentText);
option.rect = QRect(option.rect.right() - 30, option.rect.top(), 20, option.rect.height());
painter.drawPrimitive(QStyle::PE_IndicatorArrowDown, option);
}
private:
int borderRadius;
QColor backgroundColor;
};
#endif // EXTENDEDCOMBOBOX_H
ExtendedComboBox *comboBox = new ExtendedComboBox(this);
comboBox->setBorderRadius(10); // 设置圆角半径为10
comboBox->setBackgroundColor(QColor("#34495e")); // 设置背景颜色为深蓝灰色
// 高亮的方式
comboBox->setBackgroundColor(palette().color(QPalette::Highlight));
comboBox->addItem("选项 1");
comboBox->addItem("选项 2");
comboBox->setGeometry(10, 10, 180, 30);
如果绘制文本缩略显示可以把代码修改为下面的样子
void ExtendedRComboBox::paintEvent(QPaintEvent *event)
{
// ... 其他代码 ...
// 设置画笔颜色
painter.setPen(option.palette.color(QPalette::ButtonText));
// 法定文本矩形和边距
const int textMargin = 5; // 文本左右的边距,可根据需要调整
QRect textRect = option.rect.adjusted(textMargin, 0, -textMargin, 0); // 调整矩形以添加边距
// 设置文本选项,包括省略模式
QFontMetrics fontMetrics(option.fontMetrics);
QString elidedText = fontMetrics.elidedText(option.currentText, Qt::ElideRight, textRect.width());
// 绘制文本
painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, elidedText);
// ... 其他代码 ...
}
上面绘制的箭头,因为使用了自带的箭头,会有窗口失焦变化颜色的问题,可以通过监听鼠标事件进行再paintevent中进行绘制,但是我不想再其中有太多的判断,故使用drawline进行自己绘制
void YourWidget::paintEvent(QPaintEvent *event) {
// 调用父类的 paintEvent 方法
QWidget::paintEvent(event);
// 创建绘图对象
QPainter painter(this);
// 设置箭头的矩形区域
QRect arrowRect = QRect(width() - 50, 0, 50, height());
// 设置箭头的颜色
QColor arrowColor = Qt::black; // 或者您可以设置为您想要的颜色
// 绘制箭头
painter.setPen(QPen(arrowColor, 2)); // 设置画笔颜色和线宽
painter.drawLine(arrowRect.left() + 10, arrowRect.center().y(), arrowRect.right() - 10, arrowRect.center().y()); // 绘制横线
painter.drawLine(arrowRect.right() - 15, arrowRect.center().y() - 5, arrowRect.right() - 5, arrowRect.center().y()); // 绘制右侧斜线
painter.drawLine(arrowRect.right() - 15, arrowRect.center().y() + 5, arrowRect.right() - 5, arrowRect.center().y()); // 绘制右侧斜线
}