c++qtbackgroundtransparentqtstylesheets

Semi-transparent background on QMainWindow using stylesheet


I would like to set a semi-transparent background for my QMainWindow using QMainWindow::setStyleSheet.

I do something like:

QMainWindow window;
window.setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
window.setStyleSheet("background-color: rgba(255, 0, 0, 128)");
window.setAttribute(Qt::WA_TranslucentBackground, true);
window.setFixedSize(800, 600);
window.show();

and I get a fully transparent window, which is pretty much nothing I can see, and if I do it without:

window.setAttribute(Qt::WA_TranslucentBackground, true);

I get a fully red window.

I found out that, inheriting QMainWindow, overloading paintEvent() and using QPainter::fillRect() with QColor with alpha, does what I want, but it's not using stylesheets.

How do I achieve this using 'setStyleSheet()'?


Solution

  • Create a QWidget, set is as central widget on QMainWindow, and set stylesheet on this widget, not the main window.

    QMainWindow window;
    window.setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
    window.setAttribute(Qt::WA_TranslucentBackground, true);
    window.setFixedSize(800, 600);
    
    QWidget widget(&window);
    widget.setStyleSheet("background-color: rgba(255, 0, 0, 128)");
    
    window.setCentralWidget(&widget);
    window.show();