PYQT5 自定义QWidget并重写paintEvent

参考
http://www.cnblogs.com/findum...
https://blog.csdn.net/goforwa...关键词
PYQT5
QWidget
paintEvent
QSS

个人没有C的基础, 鉴于网上教程全是c类的, 特写下次文, 能帮到和我有相同困惑的人就好.

from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QWidget, \
    QHBoxLayout, QStyleOption, QStyle

class MyWidget(QWidget):
    def __init__(self, parent=None):
        super(MyWidget,self).__init__(parent)
        self.setObjectName('myWidget')
        self.setMinimumSize(100,60)

    # 重写paintEvent 否则不能使用样式表定义外观
    def paintEvent(self, evt):
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        # 反锯齿
        painter.setRenderHint(QPainter.Antialiasing)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

class MyWindow(QWidget):
    def __init__(self, parent=None):
        super(MyWindow,self).__init__(parent)
        self.resize(400,300)
        layout = QHBoxLayout()

        # 添加自定义部件(MyWidget)
        self.widget = MyWidget() # 这里可以不要self

        # 放入布局内
        layout.addWidget(self.widget)
        self.setLayout(layout)

        self.setWindowTitle('使用QSS自定义QWidget样式')

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    app.setStyleSheet(open("./Style.qss").read())
    window = MyWindow()
    window.show();
    sys.exit(app.exec_())

Style.qss

#myWidget{
    background: gold;
    border-radius: 8px ;
    border: 1px solid red; /* 顺序不能变 */
}

相关推荐