Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QGraphicsView Mouse click event help



  • Hi,

    I am new to QT and looking for someone to help.

    I have a program where I need to draw a shape on top of an image using a mouse click/drag/release. Currently this is the closest piece of code I have to drawing the shape onto it however it is in QGraphicsView and I am unsure on how to detect a mouse click in that view.

    void edit::mousePressEvent(QMouseEvent *event){
        QPointF mousePoint = ui->graphicsView->mapToScene(event->pos());
        qreal x;
        qreal y;
        mousePoint.setX(x);
        mousePoint.setY(y);
    
        QPen pen(Qt::black);
        pen.setWidth(3);
        QGraphicsRectItem *rectangle;
        rectangle = scene->addRect(x,y,200,50,pen);//x,y,width,height
        rectangle->setFlag(QGraphicsItem::ItemIsMovable);
    }
    

    I have been reading a lot online but there seems to be so many ways to do it and I'm finding it so overwhelming. I have been coding primarily in a QDialog class and I am pretty sure from what I have seen online I need to make a separate class with QGraphicsItem but I am unsure how I would link/setup these classes together once I have done it. can anyone provide me with some sort of explanation on how to do this and what the process? I would greatly appreciate it.

    I would greatly appreciate any help with this :)


  • Lifetime Qt Champion

    Hi
    Normally you would have
    mousePressEvent -> starting the shape. (we store the start point)
    mouseMoveEvent -> we drag to define size. we update current pos and redraw.
    mouseReleaseEvent -> we release mouse and now make the rect as we have end point.

    like here
    http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php
    Here they use the scene, though. not the view. Should work the same.



  • @mrjj Ok thank you for replying so quickly, that link looks very helpful, I'll give it a try :)


  • Lifetime Qt Champion

    @Marsh
    well you are on right track
    but the QPointF mousePoint = ui->graphicsView->mapToScene(event->pos());
    should be a member of the view (QPointF mousePoint; .h, in class) . so we can use the value in
    mouseRelease to define the rect.
    Or if you just using plain View, then add to the class that has the view.
    anyway, the code in example is mostly finished, you just want rect and not line :)



  • @Marsh

    You also might want to check out the Scribble Example.
    QWidget is used there for drawing, but the mouseEvents are the same. You can use them for your QGraphicsView or get at least some inspiration :)



  • @Pl45m4 Thank you this resource looks promising!


Log in to reply