Search code examples
c++qtlines

Smoothing an inclined line


I can't find a proper way to draw a smooth inclined line without having it over-pixelated in Qt with the QPainterPath object.

Note that I know it doesn't make sense to draw the path in the paintEvent function, I put it there for sake of simplicity. I'm trying to draw the line directly in the central widget.

Hereafter is a snippet of my code:

void MyObject::paintEvent(QPaintEvent *)
{
    QPainterPath aPath;
    aPath.moveTo(40.0, 60.0); //random values to try
    aPath.lineTo(254, 354.0);

    QPainter painter(this);
    painter.setPen(QPen(QColor(20, 20, 200), 10, Qt::SolidLine));
    painter.drawPath(aPath);
}

And here is the result I get:

enter image description here

It's awful! The only beautiful lines I can draw are horizontal, vertical or 45° inclined ones...


Solution

  • If you are looking for drawing quality, the Qt documentation provides an illustrative example (5.X version) of the use of its render quality flags. Generally, you can use the flags specified here (5.X version), and set them using the QPainter::setRenderHint() (5.X version) function. See if you are able to achieve the desired quality using those methods. For your code, you'd be looking for something like

    QPainter painter(this);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
    painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
    painter.setPen(QPen(QColor(20, 20, 200), 10, Qt::SolidLine));
    painter.drawPath(aPath);