How to set QGraphicsScene/View to a specific coordinate system
Asked Answered
F

1

22

I want to draw polygons in a QGraphicsScene but where the polygons has latitude/longitude positions. In a equirectangular projection the coordinates goes from:

                       ^
                      90
                       |
                       |
-180----------------------------------->180
                       |
                       |
                     -90

How can I set the QGraphicsScene / QGraphicsView to such projection?

Many thanks,

Carlos.

Fou answered 4/5, 2012 at 6:37 Comment(0)
C
27

Use QGraphicsScene::setSceneRect() like so:

scene->setSceneRect(-180, -90, 360, 180);

If you're concerned about the vertical axis being incorrectly flipped, you have a few options for how to deal with this. One way is to simply multiply by -1 whenever you make any calculation involving the y coordinate. Another way is to vertically flip the QGraphicsView, using view->scale(1, -1) so that the scene is displayed correctly.

Below is a working example that uses the latter technique. In the example, I've subclassed QGraphicsScene so that you can click in the view, and the custom scene will display the click position using qDebug(). In practice, you don't actually need to subclass QGraphicsScene.

#include <QtGui>

class CustomScene : public QGraphicsScene
{
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
        qDebug() << event->scenePos();
    }
};

class MainWindow : public QMainWindow
{
public:
    MainWindow()
    {
        QGraphicsScene *scene = new CustomScene;
        QGraphicsView *view = new QGraphicsView(this);
        scene->setSceneRect(-180, -90, 360, 180);
        view->setScene(scene);
        view->scale(1, -1);
        setCentralWidget(view);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
Ciliary answered 4/5, 2012 at 7:24 Comment(3)
Excellent. Just one question: Why 360?Fou
@Fou 360 is the width, not the right coordinate. To go from -180 to 180, the width is 360.Ciliary
note: flipping y with scale(1,-1) will also flip text!Effectually

© 2022 - 2024 — McMap. All rights reserved.