[Development] Issues with QPainter::drawPolygon (off by one error?)

Henry Skoglund henry at tungware.se
Fri Apr 26 22:48:44 CEST 2024


On 2024-04-26 21:52, Christian Ehrlicher via Development wrote:
> Hello,
>
> I'm currently trying to investigate a painting problem within the
> windowsvista / common style:
>
>     QImage img(7, 7, QImage::Format_ARGB32_Premultiplied);
>     QPolygon poly{ QPoint(1, 1), {5, 1}, {3, 5} };
>     QPainter p(&img);
>     p.setPen(Qt::NoPen);
>     p.setBrush(QColor(Qt::black));
>     p.drawPolygon(poly);
>     p.setPen(QColor(0, 255, 0, 128));
>     p.drawPoints(poly.data(), poly.size());
>     p.end();
>     img.save("output.png");
>
> This code should draw a small down arrow (e.g. for a QPushButton with a
> QMenu attached) and should look similar to this:
>
>   0123456
> 0
> 1  XXXXX
> 2   XXX
> 3   XXX
> 4    X
> 5    X
> 6
>
> But the outcome is this:
>
>   0123456
> 0
> 1  XXXX
> 2   XX
> 3   XX
> 4
> 5
> 6
>
> Setting a non-cosmetic pen at least result in painting of all three
> corners but gives a non-symmetric triangle:
>
>   0123456
> 0
> 1  XXXXX
> 2  XXXX
> 3   XXX
> 4   XX
> 5    X
> 6
>
> I've no idea how to draw this triangle the way I want (and everyone is
> satisfied with the outcome). Do you have any ideas?
>
>
> Thx,
> Christian
>
Hi, I think the QPainter draws very poorly using direct polygon paths.
You could try going via a QPainterPath, say:

     QImage img(7, 7, QImage::Format_ARGB32_Premultiplied);
     img.fill(QColor(0, 255, 0, 128));    // to be sure the img contains 
no junk values
     QPolygon poly{ QPoint(1, 1), {5, 1}, {3, 5} };
     QPainter p(&img);
     p.setPen(Qt::NoPen);
     p.setBrush(QColor(Qt::black));
     p.setPen(QColor(0, 255, 0, 128));
     QPainterPath path;
     path.addPolygon(poly);
     p.drawPath(path);
     p.end();
     img.save("output.png");

Rgrds Henry



More information about the Development mailing list