在PyQt5中为圆角遮罩窗口时进行抗锯齿(添加平滑度)

2024-07-04 07:39:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个窗口,我想有圆角,我知道它可以很容易地设置

        self.mainframe=QFrame(self)
        self.mainframe.setStyleSheet("background:blue;border-radius:25px")
        self.setCentralWidget(self.mainframe)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

This is the result

它有很好的圆角,我的意思是角平滑(抗锯齿)。
但是我不想这样做是有原因的。我还有第二个选择,我可以使用resizeEvent中的QPainterPath设置掩码

这是密码

def resizeEvent(self, event):
        path = QPainterPath()
        print(self.rect())
        path.addRoundedRect(QRectF(self.rect()),25, 25,Qt.AbsoluteSize)
        reg = QRegion(path.toFillPolygon().toPolygon())
        self.setMask(reg)  

enter image description here

但其角点不平滑意味着抗锯齿

这是我的完整代码:

import sys
from PyQt5.QtCore import Qt,  QRectF
from PyQt5.QtGui import QPainterPath, QRegion
from PyQt5.QtWidgets import QApplication, QMainWindow, QFrame

class Example(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(600,400)
        self.mainframe=QFrame(self)
        self.mainframe.setStyleSheet("background:blue;border-radius:25px")
        self.setCentralWidget(self.mainframe)
        # self.setWindowFlags(Qt.FramelessWindowHint)
        # self.setAttribute(Qt.WA_TranslucentBackground)
    def resizeEvent(self, event):
        path = QPainterPath()
        print(self.rect())
        path.addRoundedRect(QRectF(self.rect()),25, 25,Qt.AbsoluteSize)
        reg = QRegion(path.toFillPolygon().toPolygon())
        self.setMask(reg)     

   
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Example()
    window.show()
    sys.exit(app.exec_())    

有没有办法做到这一点。我的意思是看起来像第一个


Tags: pathfromrectimportselfdefsysreg

热门问题