Anti-aliasing

If you look at the result of the previous screenshot, you can probably note that the drawing looks pixelated. This happens because each pixel in a line is completely black, and all the surrounding pixels are completely white. The physical display's resolution is limited, but a technique called anti-aliasing allows you to produce more smooth images with the same resolution. When drawing a line with anti-aliasing, some pixels will be more or less blacker than others, depending on how the line crosses the pixel grid.

You can easily enable anti-aliasing in Graphics View using the following code:

view.setRenderHint(QPainter::Antialiasing);

With the anti-aliasing flag turned on, the painting is done much more smoothly:

However, lines in the rectangle on the left now look thicker. This happens because we used lines with integer coordinates and 1 pixel width. Such a line is located exactly on the border between two rows of pixels, and when anti-aliased, both adjacent rows of pixels will be partially painted. This can be fixed by adding 0.5 to all coordinates:

QRectF rect(-width / 2, -height / 2, width, height);
rect.translate(0.5, 0.5);
QGraphicsRectItem *parent = new QGraphicsRectItem(rect);

Now the line is positioned right in the middle of a pixel row, so it only occupies a single row:

Another solution is to implement a custom item class and disable anti-aliasing when painting a horizontal or vertical line.

QGraphicsView also supports the QPainter::TextAntialiasing flag that enables anti-aliasing when drawing text, and the QPainter::SmoothPixmapTransform flag that enables smooth pixmap transformation. Note the anti-aliasing and smoothing impact performance of your application, so use them only when needed.