setWindowOpacity(x); x(0-1)可以为小数 0.1 0.2 0.3等
- x=0 时完全透明
- k=1时不透明
setWindowOpacity(0.5);

当有控件时,控件也变透明,在ui界面中添加两个按钮

setWindowFlag(Qt::FramelessWindowHint);去除边框
setAttribute(Qt::WA_translucentBackground);使窗口透明
但这种方式窗口是全透明
注意:setAttribute需要配合setWindowFlag一起使用
- setWindowFlag(Qt::FramelessWindowHint);
- setAttribute(Qt::WA_TranslucentBackground);

使用重绘事件对窗口进行绘制
在widget.h中添加事件:
void paintEvent(QPaintEvent *event);//绘图事件
构造函数中添加:
- setWindowFlag(Qt::FramelessWindowHint);
- setAttribute(Qt::WA_TranslucentBackground);
在widget.cpp中实现绘图事件
- fillRect()指定区域设置属性
- rect()获取内部矩形
- void Widget::paintEvent(QPaintEvent *event)//绘图事件
- {
- QPainter painter(this);
- painter.fillRect(rect(),QColor(255,255,255,200));
- }

创建一个新项目
添加绘画事件;
- protected:
- void paintEvent(QPaintEvent *event);//绘图事件
实现绘画事件:
- void Widget::paintEvent(QPaintEvent *event)//绘图事件
- {
- QPainter painter(this);//创建一个画家
- QPixmap pix(":/image/img.jpg");
- painter.drawPixmap(0,0,pix);//绘制图片
- this->resize(pix.size());//设置窗口大小
- setWindowOpacity(0.5);
- }

background-color:rgba(255,255,255,x)x代表透明度 0为完全透明 255为不透明
通过函数setStyleSheet()设置样式表
ui->pushButton->setStyleSheet("background-color:rgba(103,182,255,50)");

- #pushButton
- {
- background-color: rgba(103, 182, 255,50);
- }

注意对主窗口使用 background-color:rgba(255,255,255,x)
窗口的底色为黑色,数值越小越趋近黑色,所有不会去使用 background-color:rgba(255,255,255,x)设置主窗口的透明度。
- QWidget
- {
- background-color: rgba(24, 174, 255,0);
- }
