绘制PyQt小部件背景时出现意外消息

时间:2013-12-27 15:50:20

标签: python pyqt

为什么我在运行此代码时在控制台中收到此消息QPainter::begin: Painter already active

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
import sys


class MyRoundWidget(QWidget):

    def __init__(self, master=None):
        super(MyRoundWidget,self).__init__(master)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle("QLinearGradient Vertical Gradient ")
        self.setAttribute(Qt.WA_TranslucentBackground)        

    def paintEvent(self, ev):
        painter = QPainter(self)
        painter.begin(self)
        gradient = QLinearGradient(QRectF(self.rect()).topLeft(),QRectF(self.rect()).bottomLeft())
        gradient.setColorAt(0.0, Qt.black)
        gradient.setColorAt(0.4, Qt.gray)
        gradient.setColorAt(0.7, Qt.black)
        painter.setBrush(gradient)
        painter.drawRoundedRect(self.rect(), 10.0, 10.0)
        painter.end()


def main():    
    app     = QApplication(sys.argv)
    widget = MyRoundWidget()    
    widget.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

我的代码有问题吗?

1 个答案:

答案 0 :(得分:7)

def paintEvent(self, ev):
    painter = QPainter(self)
    gradient = QLinearGradient(QRectF(self.rect()).topLeft(),QRectF(self.rect()).bottomLeft())
    gradient.setColorAt(0.0, Qt.black)
    gradient.setColorAt(0.4, Qt.gray)
    gradient.setColorAt(0.7, Qt.black)
    painter.setBrush(gradient)
    painter.drawRoundedRect(self.rect(), 10.0, 10.0)

删除painter.begin(self)painter.end()

根据Qt docs

  

请注意,大多数情况下,您可以使用其中一个构造函数   而不是begin(),而end()自动完成   破坏。

     

警告:油漆设备一次只能由一名画家绘画。

因此,如果您使用painter = QPainter(self)构建画家,则无需拨打begin()end()。这将是重复的。