pyqt / python-qt5

Unofficial PyQt5 via PyPI for Python 2.7 64-bit on Windows
GNU General Public License v3.0
280 stars 77 forks source link

Can not create window win transparent background #58

Open roipoussiere opened 4 years ago

roipoussiere commented 4 years ago

I can not create a window with transparent background with PyQt.

On my other other computer which runs Manjaro it works well, but not on my current, which runs Kubuntu 20.04. I tried both with PyQt 5.15 and 5.12 (the version used by KDE).

Here is a minimal example that displays a circle:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
from PyQt5.QtWidgets import QDialog, QApplication

WIDTH=400
HEIGHT=400

class MyWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.setModal(True)

        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        # self.setWindowOpacity(0.5)
        # self.setStyleSheet('background: transparent; background-color: none; opacity: 0.5;')
        # self.setAttribute(Qt.WA_NoSystemBackground, True)
        # self.setAttribute(Qt.WA_OpaquePaintEvent, False)
        # self.setAttribute(Qt.WA_PaintOnScreen)

        self.setMinimumWidth(WIDTH)
        self.setMinimumHeight(HEIGHT)
        self.setMaximumWidth(WIDTH)
        self.setMaximumHeight(HEIGHT)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(QBrush(Qt.gray, Qt.SolidPattern))
        painter.drawEllipse(0, 0, WIDTH, HEIGHT)

def main():
    app = QApplication(sys.argv)
    win = MyWindow()
    win.show()
    sys.exit(app.exec_())

All the commented lines are different solutions I have tested without success.

And here is the c++ equivalent, that works well:

#include <stdlib.h>
#include <QApplication>
#include <QDialog>
#include <QDialog>
#include <Qt>
#include <QPainter>

#define WIDTH 400
#define HEIGHT 400

class Dialog: public QDialog {
  public:
    Dialog() {
      this->setModal(true);
      this->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
      this->setAttribute(Qt::WA_TranslucentBackground, 1);

      this->setMinimumWidth(WIDTH);
      this->setMinimumHeight(HEIGHT);
      this->setMaximumWidth(WIDTH);
      this->setMaximumHeight(HEIGHT);
    }

    void paintEvent(QPaintEvent *event) {
      QPainter painter(this);
      painter.setRenderHint(QPainter::Antialiasing);
      painter.setBrush(QBrush(Qt::gray, Qt::SolidPattern));
      painter.drawEllipse(0, 0, WIDTH, HEIGHT);
    }

    void show() {
      QDialog::show();
    }
};

int main( int argc, char **argv ) {
  QApplication app( argc, argv );

  Dialog* dialog = new Dialog();
  dialog->show();
  return app.exec();
}