Python Qt bindings: how to increase line width with 0 width

With the following simple example (which works well with PySide or PyQt4 on my computer):

import sys
import random
import numpy
from PySide import QtGui, QtCore

class Window(QtGui.QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.resize(800, 500)
        self.view = QtGui.QGraphicsView()
        self.scene = QtGui.QGraphicsScene()

        # Layout
        layout = QtGui.QGridLayout()
        layout.addWidget(self.view, 0, 0)

        # Styles
        self.pen = QtGui.QPen(, 0, QtCore.Qt.SolidLine)
        self.brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 255))

    def addLine(self, x0, y0, x1, y1):
        line = QtCore.QLineF(x0, -y0, x1, -y1)
        pen = QtGui.QPen(QtGui.QColor(250, 0, 0, 255), 0, QtCore.Qt.SolidLine)
        pen.setDashPattern([1, 4, 5, 4])
        l = self.scene.addLine(line, pen)

    def addRect(self, left, top, width, height):
        rect = QtCore.QRectF(left, -top, width, abs(height))
        r = self.scene.addRect(rect, self.pen, self.brush)

    def fit(self):

    def resizeEvent(self, event = None):

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.addRect(0, 1, 1, 1)
    window.addLine(-1, -1, 2, 2)
    window.addLine(0, 1, 1, 0)


I can draw two red lines that are of constant width; which means they don't change, doesn't matter the size (coordinates) of the square and lines, and doesn't matter if I resize the window:

enter image description hereenter image description here

This is because I am using QtGui.Qpen

with width 0

. However, if I use a different width > 0

, then the observed line width changes to the window size (or changes if the square and lines are also different sizes):

enter image description hereenter image description here

Is it possible to change the line width so that the observed lines are thicker than those obtained when the width is set to 0

, while maintaining the same "observed" width when the window is resized or when the square / line is resized?


Using setCosmetic(True)

as suggested by o11c has unexpected behavior (at least I didn't expect this to happen); it adds margins to the image (increases size scene.sceneRect()

). These margins appear to be proportional to the width QPen

when isCosmetic() == True


enter image description here

A new question has been created related to this issue. See question 26231374 for more details :


source to share

1 answer

According to the Qt C ++ documentation, use a setCosmetic

in QPen

. I assume the python shell provides this.



All Articles