Search code examples
pythonpyqtpyqt5qpainter

QPainter point size is 1 pixel and can not be changed


I am trying to draw points with a costumed size, but changing the pen does nothing. Every point I draw is one pixel size. Here is my code:

class Diedrico(QWidget):
    def __init__(self, parent):
        super().__init__(parent)

    def paintEvent(self, event):
        painter = QPainter()
        pen = QPen(Qt.black)
        pen.setWidth(30)
        painter.setPen(pen)
        painter.begin(self)
        painter.drawPoint(10, 10)
        painter.end()

Solution

  • If you run your script in the console/CMD you will get the following warning:

    QPainter::setPen: Painter not active
    QPainter::setPen: Painter not active
    

    It clearly indicates that you are modifying properties without the QPainter having a device, so the solution is to initialize the device using begin() before setPen(), or pass the device in the constructor, in addition the end() method is unnecessary in this case since when QPainter is destroyed then end() will be called.

    from PyQt5.QtCore import Qt
    from PyQt5.QtGui import QPainter, QPen
    from PyQt5.QtWidgets import QApplication, QWidget
    
    
    class Diedrico(QWidget):
        def paintEvent(self, event):
            painter = QPainter(self)
            # or
            # painter = QPainter()
            # painter.begin(self)
            pen = QPen(Qt.black)
            pen.setWidth(30)
            painter.setPen(pen)
            painter.drawPoint(10, 10)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QApplication(sys.argv)
        w = Diedrico()
        w.show()
        sys.exit(app.exec_())