自定义的一个包含 圆角,透明 以及 阴影的 Widget,可以方便地做成MacOS BigSur那种控件样式。
#ifndef BIGSURSTYLEWIDGET_H
#define BIGSURSTYLEWIDGET_H
#include <QWidget>
#define BG_COLOR QColor(31, 181, 231)
#define SHADOW_COLOR QColor("#444444")
class QPainter;
class BigSurStyleWidget : public QWidget
{
public:
BigSurStyleWidget(const QColor& backgroundColor = BG_COLOR, const QColor& shadowColor = SHADOW_COLOR, QWidget* parent = 0);
// The valid range of opacity is from 1.0(completely opaque) to 0.0(completely transparent);
void setOpacity(float opacity);
// Set widget background color;
void setBackgroundColor(const QColor& color);
protected:
void paintEvent(QPaintEvent*);
private:
QColor m_backgroundColor;
float m_opacity = 1.0;
};
#endif // BIGSURSTYLEWIDGET_H
#include "bigsurstylewidget.h"
#include <QPainter>
#include <QGraphicsDropShadowEffect>
BigSurStyleWidget::BigSurStyleWidget(const QColor& bgColor, const QColor& shadowColor, QWidget* parent)
:QWidget(parent), m_backgroundColor(bgColor), m_opacity(1.0)
{
QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect(this);
effect->setOffset(0);
effect->setColor(shadowColor);
effect->setBlurRadius(15);
this->setGraphicsEffect(effect);
this->setAttribute(Qt::WA_TranslucentBackground);
}
void BigSurStyleWidget::paintEvent(QPaintEvent *e)
{
m_backgroundColor.setAlpha(m_opacity * 255);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(m_backgroundColor);
painter.setPen(Qt::transparent);
QRect rect = this->rect();
rect.setWidth(rect.width() - 1);
rect.setHeight(rect.height() - 1);
painter.drawRoundedRect(rect, 10, 10);
QWidget::paintEvent(e);
}
void BigSurStyleWidget::setBackgroundColor(const QColor &color)
{
m_backgroundColor = color;
m_backgroundColor.setAlpha(m_opacity * 255);
update();
}
void BigSurStyleWidget::setOpacity(float o)
{
m_opacity = o;
update();
}
预览图