user3676560
user3676560

Reputation: 151

Draw multiple Lines in QT

I want to draw multiple lines with a application. Each line consists of three "x" values and three "y" Values, so i use QPointF with 3 points.

Now i want to draw 4 lines with values from my arrays. i have two arrays. One for "x" values and one for "y" values.

the arrays looks like that:

("676.0", "930.0", "930.0", "930.0", "930.0", "1002.0", "1002.0", "1002.0", "1170.0", "1170.0", "1410.0", "1410.0")

Values 1-3 are for the first line. 4-6 for the 2nd line...

I create an simple loop for all 4 lines.

for(int z = 0; z < 12; z+=3)
{
    static const QPointF points[3] = {
         QPointF(lineXarray[z].toDouble(), lineYarray[z].toDouble()),
         QPointF(lineXarray[z+=1].toDouble(), lineYarray[z+=1].toDouble()),
         QPointF(lineXarray[z+=2].toDouble(), lineYarray[z+=2].toDouble())};
    painter.drawPolyline(points, 3);
}

My Idea was that the 2nd QPoint get the 2nd Value and so on, and increment the loop by 3. But he only draw the first line. What did i wrong?

Upvotes: 1

Views: 1803

Answers (2)

vahancho
vahancho

Reputation: 21220

The problem is that you increment z counter in your [] operators too, so it quickly reaches the higher limit. Thus your loop executed only once. I would write the loop in the following way:

for(int z = 0; z <= 12 - 3; z += 3)
{
    QPointF points[3] = {
         QPointF(lineXarray[z].toDouble(), lineYarray[z].toDouble()),
         QPointF(lineXarray[z + 1].toDouble(), lineYarray[z + 1].toDouble()),
         QPointF(lineXarray[z + 2].toDouble(), lineYarray[z + 2].toDouble())};
    painter.drawPolyline(points, 3);
}

You do not need to declare points array as static. Please note, that I increment z up to 12 - 3 = 9 to prevent overflow.

Upvotes: 1

dfranca
dfranca

Reputation: 5322

In those lines you are not only referencing the element at z+1 and z+2, but you are incrementing z:

  QPointF(lineXarray[z+=1].toDouble(), lineYarray[z+=1].toDouble()),
  QPointF(lineXarray[z+=2].toDouble(), lineYarray[z+=2].toDouble())

As you are incrementing by 3 in the loop itself you can just reference z+1 or z+2, the new code would be like that:

  QPointF(lineXarray[z+1].toDouble(), lineYarray[z+1].toDouble()),
  QPointF(lineXarray[z+2].toDouble(), lineYarray[z+2].toDouble())

Upvotes: 1

Related Questions