Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected message when painting PyQt widget background

Tags:

python

pyqt

Why I'm getting this message QPainter::begin: Painter already active in the console when I run this code:

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()

Is something wrong in my code?

like image 865
Alvaro Fuentes Avatar asked Sep 16 '25 18:09

Alvaro Fuentes


1 Answers

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)

Remove painter.begin(self) and painter.end().

According to the Qt docs:

Note that most of the time, you can use one of the constructors instead of begin(), and that end() is automatically done at destruction.

Warning: A paint device can only be painted by one painter at a time.

So, if you use painter = QPainter(self) to construct a painter, then it will be unnecessary to call begin() and end(). This will be duplicated.

like image 92
charlie cui Avatar answered Sep 19 '25 09:09

charlie cui