How can I apply blur effect only on the background of my mainwindow?

Question:

what i want to achieve
I am learning how to use pyqt5 with this project of mine.

I tried downloading something called BlurWindow but it kept giving me a parameter error so switched back to trying to use QGraphicBlurEffect but it blurs everything inside my MainWindow

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
from PyQt5.uic import loadUi
from BlurWindow.blurWindow import blur

class MainWindow(QMainWindow):
  def __init__(self):
    super(MainWindow, self).__init__()
    loadUi(r'D:WorkspaceQt Designerblur bgblurtest.ui',self)
    self.setAttribute(Qt.WA_TranslucentBackground)
    hWnd = self.winId()
    print(hWnd)
    blur(hWnd)

    self.setStyleSheet("background-color: rgba(0, 0, 0, 0)")


app=QApplication(sys.argv)
mainwindow=MainWindow()
widget=QtWidgets.QStackedWidget()
widget.setWindowOpacity(0.5)
widget.addWidget(mainwindow)
widget.setFixedHeight(600)
widget.setFixedWidth(800)
widget.show()
sys.exit(app.exec_())

this is what i got

Asked By: jj4giya

||

Answers:

BlurWindow uses system features to set the background of a top level window.

Your problem is that you’re applying it to the wrong widget, which is a child widget, not a top level one. The top level has no "glass effect" set, so the result is that it won’t have any effect applied on it.

The solution is simple: apply the effect to the top level window.

import sys
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
from BlurWindow.blurWindow import blur

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        loadUi(r'D:WorkspaceQt Designerblur bgblurtest.ui', self)
        self.setStyleSheet("""
            MainWindow {
                background-color: rgba(0, 0, 0, 0);
            }
        """)


app = QApplication(sys.argv)
mainwindow = MainWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(mainwindow)
widget.setFixedHeight(600)
widget.setFixedWidth(800)

blur(widget.winId()) # <---
widget.show()

sys.exit(app.exec_())

Note that:

  • QMainWindow is not supposed to be used as a child widget. You should switch to a basic QWidget (or other container widgets like QFrame), meaning that you should create a new "widget" in Designer and copy/paste the content of your previous window to it, otherwise loadUi() will throw an exception;
  • you should never apply generic style sheet properties to parent widgets, as you would get unexpected results (especially with complex widgets, like scroll areas); you should always use proper selectors (as I did above);
Answered By: musicamante
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.