Search code examples
pythonpyqt5qpainterqpixmap

QPixmap / QPainter showing black window background


I am following an example from the PyQt5 book by Martin Fitzpatrick. When I run the following code, the background is black and the line is not drawn:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.label = QtWidgets.QLabel()

        canvas = QtGui.QPixmap(400, 300)

        self.label.setPixmap(canvas)
        self.setCentralWidget(self.label)
        self.draw_something()

    def draw_something(self):
        painter = QtGui.QPainter(self.label.pixmap())
        painter.drawLine(10, 10, 300, 200)
        painter.end()


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

The expected result is on the left: Comparison


Solution

  • By default the memory that a QPixmap uses is not cleaned by efficiency so it has the bytes not altered as indicated by the docs:

    QPixmap::QPixmap(int width, int height)

    Constructs a pixmap with the given width and height. If either width or height is zero, a null pixmap is constructed.

    Warning: This will create a QPixmap with uninitialized data. Call fill() to fill the pixmap with an appropriate color before drawing onto it with QPainter.

    (emphasis mine)

    The solution is to use fill to set the background color:

    canvas = QtGui.QPixmap(400, 300)
    canvas.fill(QtGui.QColor("white"))