0

I have a custom widget called GraphCanvas which inherits from QWidget, it is functional but when I try to use it in a window object and set a background color to it, it does not work. The main issue is I'm making a frameless transparent window, and when I do this the actual GraphCanvas becomes transparent as well and I can't find out why.

Minimal reproducible example:

from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import Qt
from Custom_Widgets.CanvasWidget.GraphCanvas import GraphCanvas
import sys

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.setGeometry(100, 100, 500, 500)

        flags = Qt.WindowFlags(Qt.FramelessWindowHint)  
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(flags)

        self.canvas = GraphCanvas(self)
        self.canvas.setGeometry(0, 0, 500, 500)
        self.canvas.setStyleSheet('background-color: grey;')

app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
class GraphCanvas(QWidget):
    def __init__(self, parent):
        super().__init__(parent)

In the Window __init__ if I change GraphCanvas(self) to QWidget(self) it works correctly, otherwise the GraphCanvas for some reason inherits the transparent background and nothing shows up.

Ahmed
  • 43
  • 7
  • Is the geometry (position and size) being applied to the canvas successfully? – akaAbdullahMateen May 05 '22 at 15:25
  • @akaAbdullahMateen I tried adding a mousePressEvent method to GraphCanvas and have it print to the cmd when its clicked, and yes it seems like the geometry is applied successfully. Again if you simply replace GraphCanvas with QWidget in the Window constructor, it works. – Ahmed May 05 '22 at 15:28
  • In the stylsheet add QWidget selector. Something like this: `self.canvas.setStyleSheet("QWidget{background-color: #efefef;}")` – akaAbdullahMateen May 05 '22 at 15:31
  • Still doesn't work. I even tried giving the canvas an object name and using that as a selector, still nothing. – Ahmed May 05 '22 at 15:33
  • Does settings other properties like border-color, border radius work in this stylesheet? – akaAbdullahMateen May 05 '22 at 15:37
  • Also no, I think the style sheet is completely ignored for some reason. – Ahmed May 05 '22 at 15:40
  • As explained in the [documentation](https://doc.qt.io/qt-5/stylesheet-reference.html#qwidget-widget), "If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget". – musicamante May 05 '22 at 17:38

0 Answers0