Click event for QGraphicsView Qt

被刻印的时光 ゝ 提交于 2019-12-23 18:33:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16039020/click-event-for-qgraphicsview-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!