4

I have made a GUI in Qt that is basically a widget with a QGraphicsView on it i have a function:

void GUI::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        QPointF mousePoint = ui->graphicsView->mapToScene(event->pos());
        qDebug() << mousePoint;
    }
}

which links to a public slot:

  void mousePressEvent(QMouseEvent *event);

this shows me on the console the x,y coordinate of where i have clicked, however currently this is working on the entire widget and i ideally would like x,y(0,0) to be the top left of the QGraphicsView instead of the top left of the entire widget. does anyone have any idea how to make this work, i thought from my code that this is what it was doing but it turns out this is not so, iv had a look around for a while now but im coming up with nothing

any help would be really appreciated thanks.

AngryDuck
  • 4,358
  • 13
  • 57
  • 91

1 Answers1

4

Reimplement the mousePressEvent(QMouseEvent *event) of the QGraphicsView not your widget would be the 'proper' way of doing it. Otherwise you can hack it with:

// Detect if the click is in the view.
QPoint remapped = ui->graphicsView->mapFromParent( event->pos() );
if ( ui->graphicsView->rect().contains( remapped ) )
{
     QPointF mousePoint = ui->graphicsView->mapToScene( remapped );
}

This assumes that the widget is the parent of the QGraphicsView.

cmannett85
  • 21,725
  • 8
  • 76
  • 119
  • Thank you very much!!!! thats working nicely, now i know that my top left most corner will now be (0,0) but is there some form of bounds() function or something i can do to rind out bottom right coordinate. Im basically putting a map as the image in the `QGrpahicsView` and want to find the xy coordinate of clicks so i cant convert this to lat long values, however id need top left and bottom right of map to work this out – AngryDuck Apr 16 '13 at 14:14
  • `ui->graphicsView->rect().bottomLeft()` Will give you the bottom corner in the view widget coordinates. Is that what you wanted? – cmannett85 Apr 16 '13 at 14:17
  • haha bottom right was actually what i was after but i think i can work that one out `ui->graphicsView->rect().bottomRight()`?? cheers though ill accept answer now, youve saved me a lot of time – AngryDuck Apr 16 '13 at 14:20