Nathan
Nathan

Reputation: 858

PyQt Irregularly Shaped Windows (e.g. A circular without a border/decorations)

How do I create an irregularly shaped window in PyQt?

I found this C++ solution, however I am unsure of how to do that in Python.

Upvotes: 7

Views: 2591

Answers (2)

Mirko
Mirko

Reputation: 2466

Here is a PyQT5 example, which creates frameless, movable QWidget, with transparent png mask to generate irregularly shaped Window:

from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import Qt, QPoint


class IrregularWindow(QtWidgets.QWidget):
    def __init__(self):
        super(IrregularWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

    def sizeHint(self):
        return QSize(107, 41) # Set this to the exact image resolution

    def paintEvent(self, event):
        qp = QtGui.QPainter()
        qp.begin(self)    
        pixmap = QtGui.QPixmap()
        pixmap.load('image_with_transparency.png')
        qp.drawPixmap(QPoint(0, 0), pixmap)    
        qp.end()

    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def mouseMoveEvent(self, event):
        delta = QPoint(event.globalPos() - self.oldPos)
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.oldPos = event.globalPos()


a = QtWidgets.QApplication([])
rw = IrregularWindow()
rw.show()
a.exec_()

Upvotes: 2

Fredrick Brennan
Fredrick Brennan

Reputation: 7357

Here you go:

from PyQt4 import QtGui, QtWebKit
from PyQt4.QtCore import Qt, QSize

class RoundWindow(QtWebKit.QWebView):
    def __init__(self):
        super(RoundWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

    def sizeHint(self):
        return QSize(300,300)

    def paintEvent(self, event):
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.setRenderHint(QtGui.QPainter.Antialiasing);
        qp.setPen(Qt.NoPen);
        qp.setBrush(QtGui.QColor(255, 0, 0, 127));
        qp.drawEllipse(0, 0, 300, 300);
        qp.end()

a = QtGui.QApplication([])
rw = RoundWindow()
rw.show()
a.exec_()

Screenshot

I've never written C++ in my life, but reading that code example was not that hard. You'll find that most Qt documentation online is in C++, so it's useful to at least be able to read.

Upvotes: 8

Related Questions