测试环境: win10 + Qt5.9.6 MinGw
简述
关于窗体透明我们平常用到的大概有三种:
- 主窗体和子窗体都透明。
- 主窗体透明,子窗体不透明。
- 主窗体不透明,子窗体透明。
下面进行一一介绍。
实现
一、主窗体和子窗体都透明。
全透明很简单只需要该方法即可:
// 原型
// void setWindowOpacity(qreal level);
setWindowOpacity(0.8);
透明度level取值范围:0.0(全透明) - 1.0(不透明),默认值为1.0。
代码:
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
resize(400, 300);
setWindowOpacity(0.8);
QPushButton *pButton = new QPushButton(tr("按钮"), this);
pButton->setFixedSize(80, 30);
QWidget *pWidget = new QWidget(this);
pWidget->setStyleSheet("background-color: green;");
QLabel *pLabel = new QLabel(tr("子窗体"), pWidget);
pLabel->move(150, 70);
pLabel->setStyleSheet("font-size: 18pt; font-family: 'Microsoft Yahei';");
QVBoxLayout *pLayout = new QVBoxLayout(this);
pLayout->addWidget(pButton, 0, Qt::AlignHCenter);
pLayout->addWidget(pWidget);
pLayout->setContentsMargins(20, 20, 20, 100);
}
效果:
主窗体和子窗体都是透明。
二、主窗体透明,子窗体不透明。
需要下面两个方法配合使用:
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
关于Qt自定义无边框,参考:Qt自定义无边框Widget、Dialog、MessageBox
然后重写paintEvent事件:
void Widget::paintEvent(QPaintEvent *e)
{
Q_UNUSED(e);
QPainter painter(this);
// QColor最后一个参数代表alpha通道,一般用作透明度
painter.fillRect(rect(), QColor(50, 50, 50, 55));
}
效果图:
三、主窗体不透明,子窗体透明。
可以直接通过设置样式表进行设置:
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
resize(400, 300);
QLabel *pLabelMaster = new QLabel(tr("主窗体"), this);
pLabelMaster->setStyleSheet("font-size: 18pt; font-family: 'Microsoft Yahei';");
pLabelMaster->move(100, 80);
QPushButton *pButton = new QPushButton(tr("按钮"), this);
pButton->setFixedSize(80, 30);
BaseWidget *pWidget = new BaseWidget(this);
pWidget->setStyleSheet("background-color: rgba(67, 148, 16, 150);");
QLabel *pLabel = new QLabel(tr("子窗体"), pWidget);
pLabel->setStyleSheet("background-color: rgba(0, 0, 0, 0); \
font-size: 18pt; \
font-family: 'Microsoft Yahei'");
pLabel->setScaledContents(true);
pLabel->move(150, 70);
QVBoxLayout *pLayout = new QVBoxLayout(this);
pLayout->addWidget(pButton, 0, Qt::AlignHCenter);
pLayout->addWidget(pWidget);
pLayout->setContentsMargins(20, 20, 20, 100);
}
效果图: