How to set QGraphicsScene/View to a specific coordinate system

20,427

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();
}
Share:
20,427

Related videos on Youtube

QLands
Author by

QLands

Updated on April 16, 2020

Comments

  • QLands
    QLands about 4 years

    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.

  • QLands
    QLands about 12 years
    Excellent. Just one question: Why 360?
  • Anthony
    Anthony about 12 years
    @QLands 360 is the width, not the right coordinate. To go from -180 to 180, the width is 360.
  • dani
    dani about 8 years
    note: flipping y with scale(1,-1) will also flip text!