how to use mouse move event for QGraphicsScene?

纵然是瞬间 提交于 2019-12-08 04:18:32

问题


hey want to drag this bezier curve when mouse button is pressed and moved..

I did this:

void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
qDebug()<<"in mouse move - outside if";
if((e->buttons() & Qt::RightButton) && isStart && enableDrag)
{
    qDebug()<<"mouse dragging happening";
    xc2=e->pos().x();
    yc2=e->pos().y();
    drawDragBezier(xc2,yc2);
}
}

this starts dragging when i press right button and start moving mouse in whole main window..but I want to start dragging only when I press mouse button and move mouse inside the QGraphicsScene.

how to solve this?

EDIT:

void mySubClass1::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
    qDebug()<<"in musubclass mouse press event: "<<event->pos().x()<<" "
<<event- >pos().y();
    if(shape().contains(event->pos()))
    {
        currPosX=event->pos().x();
        currPosY=event->pos().y();
        qDebug()<<"currPosX currPosY: "<<currPosX<<" "<<currPosY;
    }
}
}

And the mainwindow class is:

{
myGPath=new mySubClass1();
myScene=new QGraphicsScene;
myScene->addItem(myGPath);
ui->graphicsView->setScene(myScene);


QPointF *startPoint=new QPointF(50,50);
myPaintPath=new QPainterPath(*startPoint);

myPaintPath->quadTo(100,25,200,200);

myGPath->setPath(*myPaintPath);
}

is this the right way?


回答1:


Personally, to solve this issue I'd take a different approach.

Create a class inherited from QGraphicsItem (or QGraphicsObject if you want signals and slots) to represent the bezier curve. Then implement the mouseMoveEvent of the object in this class.

class MyBezierCurve : public QGraphicsItem
{
    protected:
        void mousePressEvent(QGraphicsSceneMouseEvent*);
        void mouseMoveEvent(QGraphicsSceneMouseEvent*);
        void mouseReleaseEvent(QGraphicsSceneMouseEvent*);

};

This way, the object can detect in its mousePressEvent when the mouse is directly over one of its control points and update the control points with mouse move events until the release event occurs.

Handling the mouse events in the QGraphicsView will work, but if you introduce more bezier curves, or other objects you'll find you'll need to check which of them you need to be interacting with. Handling it in the object itself will take care of that for you.




回答2:


You should subclass QGraphicsView and detect mouseMoveEvent over there.

class MyGraphicsView : public QGraphicsView
{
   Q_OBJECT
   ...
protected:       
   void mouseMoveEvent(QMouseEvent *event);  
   ... 
};


来源:https://stackoverflow.com/questions/18817538/how-to-use-mouse-move-event-for-qgraphicsscene

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