Qt's form is transparent

Briefly

Regarding the transparency of the form, it is often encountered. Here we explain the commonly used transparency effects:

  1. Fully transparent (both main form and subform are transparent)
  2. Main form is transparent (subform is not transparent)
  3. Subform is transparent (main form is not transparent)

normal status

Under normal conditions, the effect is as follows:

write picture description here

fully transparent

Here, we can see the background of the desktop through the entire form.

Effect

write picture description here

source code

Set the transparency of the window as follows:

setWindowOpacity(0.5);
  • 1

Transparency value range: 0.0 (full transparency) - 1.0 (opaque), the default value is 1.0.

main form transparent

Here, we can see the background of the desktop through part of the form.

Effect

write picture description here

source code

Background painting with paintEvent

The main form takes the background color:

void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);

    // QColor最后一个参数80代表alpha通道,一般用作透明度
    painter.fillRect(rect(), QColor(50, 50, 50, 80));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

The main form uses a background image:

First, set the background transparent:

setAttribute(Qt::WA_TranslucentBackground, true);
  • 1

Then, draw the form background:

void QZXingWidget::paintEvent(QPaintEvent *event)
{
    QPixmap covertPixmap(":/Images/background");
    QPixmap pixmap(covertPixmap.width(), covertPixmap.height());
    pixmap.fill(Qt::transparent); 
    QPainter painter(&pixmap);
    QPoint start_point(0, 0);
    QPoint end_point(0, pixmap.height());

    //QLinearGradient进行渐变色设置
    QLinearGradient gradient(start_point, end_point);
    gradient.setColorAt(0, QColor(255, 255, 255, 100));
    gradient.setColorAt(0.5, QColor(255, 255, 255, 150));
    gradient.setColorAt(1, QColor(255, 255, 255, 255));
    painter.fillRect(rect(), QBrush(gradient));
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn); 
    painter.drawPixmap(0, 0, covertPixmap);
    painter.end();

    QPainter painter2(this);
    painter2.drawPixmap(0, 0, pixmap);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Subform transparent

This part has been shared in the blog, so I won't elaborate too much here, please refer to: Qt's transparent prompt box

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324737717&siteId=291194637