【问题标题】:How to paint RoundedRect border outline the same width all around in PyQt / PySide?如何在 PyQt / PySide 中绘制 RoundedRect 边框轮廓相同的宽度?
【发布时间】:2019-01-12 05:40:37
【问题描述】:

实际上,我一直在寻找这个答案很长一段时间,过去我看到其他帖子问过同样的问题,但我从来没有遇到任何好的答案。
无论如何,如果你运行我的代码,你会看到 4 条边的边框比轮廓的其余部分更厚。是否有可能在周围有一个漂亮的均匀边框?

import sys
from PySide2.QtCore import Qt
from PySide2.QtGui import QPainter, QPen, QColor, QBrush
from PySide2.QtWidgets import QWidget, QApplication

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)

    def paintEvent(self, event):
        painter = QPainter(self)
        fillColor = QColor(255, 165, 0, 180)
        lineColor = QColor(0, 0, 0, 255)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(QBrush(lineColor), 2))
        painter.setBrush(QBrush(fillColor))
        painter.drawRoundedRect(self.rect(), 15, 15)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec_()

谢谢。

【问题讨论】:

    标签: python pyqt pyqt4 pyqt5 pyside


    【解决方案1】:

    试试看:

    import sys
    from PyQt5.QtCore    import Qt,                              QRectF
    from PyQt5.QtGui     import QPainter, QPen, QColor, QBrush,  QPainterPath
    from PyQt5.QtWidgets import QWidget, QApplication
    
    class MainWindow(QWidget):
        BorderColor     = QColor(0, 0, 0, 255)     
        BackgroundColor = QColor(255, 165, 0, 180) 
    
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.setWindowFlags(Qt.FramelessWindowHint)          
            self.setAttribute(Qt.WA_TranslucentBackground, True) 
    
        def paintEvent(self, event):
            super(MainWindow, self).paintEvent(event) 
    
            painter = QPainter(self)
            painter.setRenderHint(QPainter.Antialiasing)   
    
            rectPath = QPainterPath()                      
            height = self.height() - 8                     
            rectPath.addRoundedRect(QRectF(2, 2, self.width()-4, height), 15, 15)
            painter.setPen(QPen(self.BorderColor, 2, Qt.SolidLine,
                                     Qt.RoundCap, Qt.RoundJoin))
            painter.setBrush(self.BackgroundColor)
            painter.drawPath(rectPath)
            painter.setPen(QPen(self.BackgroundColor, 2,
                                     Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = MainWindow()
        w.show()
        app.exec_()
    

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      相关资源
      最近更新 更多