2

I have a problem solving an issue for my program. When I create a transparent Widget that holds some other widgets, they become transparent too and I don't understand why.

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt

class MainFrame(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(MainFrame, self).__init__(parent)

        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setFixedSize(860, 560)

        # Set the opacity
        self.setWindowOpacity(1 - 50 / 100)

        layout = QtWidgets.QHBoxLayout(self)

        layout.addWidget(QtWidgets.QPushButton("TEST"))

In this sample code, the widget QPushButton will appear transparent, it's the same with labels, and other widgets. How do I apply transparency ONLY to my class MainFrame.

Edit :

here is what I have (transparent button and transparent QWidget) : enter image description here here is what I need (NO transparent button and transparent QWidget) : enter image description here Thank you very much.

syedelec
  • 1,285
  • 2
  • 19
  • 30

1 Answers1

4

I believe you are looking for this:

self.setAttribute(Qt.WA_TranslucentBackground)

The full code adapted from your example is this:

import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt

class MainFrame(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(MainFrame, self).__init__(parent)

        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setFixedSize(860, 560)

        # Set the opacity
        #self.setWindowOpacity(1 - 50 / 100)

        layout = QtWidgets.QHBoxLayout(self)

        layout.addWidget(QtWidgets.QPushButton("TEST"))

        self.setAttribute(Qt.WA_TranslucentBackground)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    Frame = MainFrame(None)
    Frame.show()
    app.exec_()

, and the result is this:

transparent QWidget

If you want to have only some transparency you might need to rewrite the paintEvent like in this example.

armatita
  • 12,825
  • 8
  • 48
  • 49
  • Hi, thanks but this is not exactly what I need, I still need the transparent widget (not totally transparent). I edited my question. – syedelec May 31 '16 at 18:12
  • @Darkos As I said at the end of my answer: If you need partial transparency than you need to re-implement the paintEvent. The way you have to do it is in the link at the bottom. – armatita May 31 '16 at 18:15
  • You are perfectly right ! I didn't try, Thank you very much. – syedelec May 31 '16 at 18:21