I develop a cross platform Qt program which plots a polyline on a QGraphicsScene:
QPolygonF polygon;
//Init polygon here
for(int i = 0; i < (polygon.size()-1); i++) {
float x1 = polygon[i].x();
float y1 = polygon[i].y();
float x2 = polygon[i+1].x();
float y2 = polygon[i+1].y();
QGraphicsLineItem* item = new QGraphicsLineItem(x2, y2, x1, y1);
item->setPen(QPen(QBrush(color), 2));
item->setZValue(30);
item->setData(0, QVariant((int)value));
addItem(item);
}
The program crashes on windows when it recieves the following values:
float x1 = 249.573;
float y1 = 183.471;
float x2 = 303.983;
float y2 = 183.45;
This polyline is composed of an almost horizontal line. The crash doesn’t occur when the line is horizontal or the absolute difference between y1 and y2 is 0 or larger than 0.5.
It doesn’t crash on Ubuntu.
When I change the polyline to a polygon the program doesn’t crash. My best, but ugly solution was to draw the polyline as a polygon – append the same points twice to the polygon:
QPolygonF polygon;
//Init polygon here
for(int i = polygon.size()-1; i > 0; i--) {
QPointF point(polygon[i].x(), polygon[i].y());
polygon.append(point);
}
QGraphicsPolygonItem* item = new QGraphicsPolygonItem(polygon);
item->setPen(QPen(QBrush(color), 2));
item->setZValue(30);
item->setData(0, QVariant((int)value));
addItem(item);
I tried to recreate the bug in a small and independent program, that plots a line with the same coordinates on a QGraphicScene. No crash was observed.
Why is this crash happening? Is there a more prettier solution to this bug?
By the way, the call stack in VS2008 debugger tells me that the crash is in malloc.c in msvcr90.dll which is called by QtGui4.dll.
Technicals:
Qt version: 4.7.0
OS: Windows 7 and Ubuntu
Did you know that there is also the
QGraphicsPathItem? (QGraphicsPolygonItemis for closed polygons only, not for polylines. The path item is for general paths.)You need to construct a
QPainterPathfrom yourQPolygon:Then make and use the path item:
But note that since your posted code seems to be error-free, there has to be a serious bug in your program (probably at a different (maybe related) position in the code), which you should fix anyway!
Probably there is a bug in the generation of the coordinates? Or some calculation even before generating the QPolygonF? Did you try commenting out the code which generates the item?
You could also try using valgrind alternative for Windows. See this Stackoverflow question for some tools.