5

如何在 PyQt 中创建一个不规则形状的窗口?

我找到了这个 C++ 解决方案,但是我不确定如何在 Python 中做到这一点。

4

2 回答 2

8

干得好:

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_()

截屏

我一生中从未编写过 C++,但阅读该代码示例并不难。您会发现大多数在线 Qt 文档都是用 C++ 编写的,因此至少能够阅读是很有用的。

于 2013-01-15T22:42:42.720 回答
0

这是一个 PyQT5 示例,它创建无框、可移动的 QWidget,使用透明 png 掩码生成不规则形状的 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_()
于 2020-08-23T03:16:59.817 回答