Search code examples
c++qtgraphgraphics2d

QT Graph plotting, how to change coordinate system/geometry of QGraphicsView


I am using QT and try to plot a graph with QGraphicsView and QGraphicsScene..i dont want any additional dependencies, thats why i dont use QWT. When i plot my data, at the moment i use

scene->drawLine(x1,y1,x2,y2,pen);

then this draws a line between the 2 points in the QGraphicScene. But this uses a top left x=0 y=0 system... i would like to use my own system like in the picture below. Another problem is that i have double values from -3 to +3..has anyone some experience with QGraphicScene and QGraphicsView and can tell me how i can accomplish this?

enter image description here


Solution

  • Try looking into QGraphicsView::setTransform. This matrix defines how "scene coordinates" are translated to "view coordinates", it's a common concept in graphics programming.

    There are also convenience functions scale(), rotate(), translate() and shear() which modify the view's current transformation matrix.

    So you could do something like this:

    scale(1.0, -1.0); // invert Y axis
    
    // translate to account for fact that Y coordinates start at -3
    translate(0.0, 3.0); 
    
    // scale Y coordinates to height of widget
    scale(1.0, (qreal)viewport()->size().height()/6.0);
    

    And since this is dependent on the size of the widget, you'd also want to catch any resize events and reset the transformation matrix again there. Assuming you want "3" to represent the top of the viewport and "-3" the bottom.