Custom QGraphicsView items are not movable



  • I made my own QGraphicsView, but the items I've created are not movable.

    this is the code:

    #include "graphicsview.h"
    
    GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent)
    {
        scene = new QGraphicsScene();
        this->setScene(scene);
        this->setAlignment(Qt::AlignLeft | Qt::AlignTop);
        LoadImage();
    }
    
    void GraphicsView::mousePressEvent(QMouseEvent *event)
    {
        if(event->buttons().testFlag(Qt::LeftButton))
        {
            int x,y;
            x = event->pos().x();
            y = event->pos().y();
            qDebug() << x << ", " << y;
            QPointF point = mapToScene(x, y);
            QGraphicsEllipseItem *ellipse;
            ellipse = scene->addEllipse(point.x(),point.y(),5,5,QPen(Qt::red), QBrush(Qt::red));
            ellipse->setFlag(QGraphicsEllipseItem::ItemIsMovable);
        }
    }
    

  • Lifetime Qt Champion

    Hi
    I think you just broke GraphicsView normal handling.
    Try also calling base class mousePressEvent as it might use for the actual item selection

    void GraphicsView::mousePressEvent(QMouseEvent *event)
    {
        if(event->buttons().testFlag(Qt::LeftButton))
        {
            int x,y;
            x = event->pos().x();
            y = event->pos().y();
            qDebug() << x << ", " << y;
            QPointF point = mapToScene(x, y);
            QGraphicsEllipseItem *ellipse;
            ellipse = scene->addEllipse(point.x(),point.y(),5,5,QPen(Qt::red), QBrush(Qt::red));
            ellipse->setFlag(QGraphicsEllipseItem::ItemIsMovable);
        }
    // call base class
    QGraphicsView::mousePressEvent(event);
    }