18:30
:25
2021
Qt Window Background Transparency with Custom paint
- Resume:
Tutorial to make a window with a custom draw transparent per pixel under Windows 7/10.
- Version:
1.0.0
- Size:
100kb
- Download:
[ C++ (sources) ]
- License:
BSD License
- Copyrights:
Renan Lavarec

Tutorial to make a window with a custom draw transparent per pixel under Windows 7/10.

This tutorial will highlight how to make a software running with window background transparency.

This tutorial is made from scratch.

Dependencies

  • Qt

You need Qt5 and Qt Creator to compile it.

What you need to do to make it work on your own app.

Make the window transparent

    // Set opacity to 1 to the window
    setWindowOpacity(1);

    // Set no system background
    setAttribute(Qt::WA_NoSystemBackground);

    // Tell the windows will be transparent
    setAttribute(Qt::WA_TranslucentBackground, true);

Paint event : draw round red rectnagle with transparency

void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    QPainterPath path;
    path.addRoundedRect(QRectF(10, 10, width()-10*2, height()-10*2), 10, 10);

    // Set Antialiasing
    painter.setRenderHint(QPainter::Antialiasing, true);

    // No pen
    painter.setPen(Qt::NoPen);

    // Fill the round rectangle with transparency red
    painter.fillPath(path, QColor(255, 0, 0, 100));

    // Load logo once
    static QPixmap tLogo(":/res/logo_demo_ti-r.png");

    // Draw centered logo
    painter.drawPixmap((width()-tLogo.width())/2.0,(height()-tLogo.height())/2.0,tLogo.width(),tLogo.height(), tLogo);

    // Update font size
    QFont font = painter.font() ;
    font.setPointSize(font.pointSize() * 3);
    painter.setFont(font);

    // Message to close the app
    painter.setPen(QColor(0,0,0));
    painter.drawText(QRect(0, height()-70, width(), 70), Qt::AlignCenter, "Alt+F4 to close");
}

If you draw a pixmap you build yourself, do not forget fill it with transparency first

    QPixmap pixmap(tSize);
    pixmap.fill(Qt::transparent);

That's it, have fun !!

Change log

- Version 1.0.0
    * Release