Important: Please read the Qt Code of Conduct -

QPainter::drawLine() draws some weird dashes instead of zero-length lines

  • Here is some code:


    #include "widget.h"
    #define SIZE 400
    #define LOGICAL_SIZE 30
    #define LINE_WIDTH 0.5
    Widget::Widget(QWidget *parent)
    	: QWidget(parent),
    	  img(SIZE, SIZE, QImage::Format_ARGB32)
    	QPointF p1(1.23, 4.56);
    	QPointF p2(1.23, 4.56);
    	QPointF p3(6.54, 3.21);
    	QPointF p4(6.54, 3.21);
    	this->resize(SIZE, SIZE);
    	QPainter painter(&img);
    	painter.setPen(QPen(Qt::black, LINE_WIDTH));
    	painter.drawLine(p1, p2);
    	painter.setPen(QPen(Qt::red, LINE_WIDTH));
    	painter.drawLine(p3, p4);"result.png");

    AFAIK this should generate blank image or two dots.
    However it outputs two dashes:


    What am i doing wrong?

  • Try setting the cap style of the pen to Qt::FlatCap

  • Moderators

    setting a line-width of 0.5 doesn't make much sense. See QPen::setWidth(). Even a pen with a width of 0 draws a 1-pixel line.

    Either you want to draw or surround your drawing code with an if-condition and prevent drawing.

  • @raven-worx :
    Help entry you linked to mentions "cosmetic pen", which is "independant to transformations".

    Here setting width of the pen does make quite a sense, because i'm setting a "transformation" (QPainter::setWindow()).

    P.S.: Image in the post is the real output image (the result.png one).

  • Moderators

    but you are setting a pen width of a half pixel in a QWidget context where only full pixels can be drawn

  • @raven-worx
    You can play around with the code (clickable link) and discover that setting pen width to .25 or .75 does indeed change the width of the line

  • @Asperamanca
    Thanks, this helped.
    Seems like square capping rounds up non-integer width to highest int.
    (this does not apply to round caps)

    Is it a bug?

Log in to reply