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

Im trying to learn about graphics in Qt5 following the tutorials I came across this code why does it produce a black canvas ,im using ubuntu with a window manager i3 enter image description here

hacker man
  • 183
  • 1
  • 1
  • 8
  • As explained in the [documentation](//doc.qt.io/qt-5/qpixmap.html#QPixmap): "his will create a QPixmap with uninitialized data. Call fill() to fill the pixmap with an appropriate color before drawing onto it with QPainter.". Add `canvas.fill(Qt.transparent)` (or any background you want). Then, be aware that it's better to keep a reference of the pixmap while painting instead of directly draw into it (in Qt6 your code would even crash), so, change to `pixmap = self.label.pixmap()` `painter = QtGui.QPainter(pixmap)`, do the drawing, then `painter.end()` and then `self.label.setPixmap(pixmap)`. – musicamante Oct 21 '22 at 14:02

0 Answers0