为什么我在运行此代码时在控制台中收到此消息 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()

我的代码有问题吗?

最佳答案

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 :



所以,如果你使用 painter = QPainter(self) 来构造一个画家,那么就没有必要调用 begin()end() 了。这将被复制。

关于python - 绘制 PyQt 小部件背景时出现意外消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20803560/

10-13 05:10