简体   繁体   中英

Qt mouse events not working in QGraphicsScene

I am using Qt 5.7 (the latest version). I can't get the mouse events to work in QGraphicsScene, but they work in window outside of my scene. I have followed this question.

So I have overwritten QWidget::mouseMoveEvent() in my main widget's subclass like this:

// header:
class MyWidget {
    ...
    void mouseMoveEvent( QMouseEvent * event );
};

// source:
MyWidget::MyWidget() {
    setMouseTracking();
}

void MyWidget::mouseMoveEvent( QMouseEvent * event ) {

}

It doesn't work for: mouseMoveEvent , mouseGrabber , mousePressEvent , mouseReleaseEvent , or mouseDoubleClickEvent . But somehow it only works for mousePressEvent .

Could this be a bug in Qt?

SOURCE CODE: In objectloader.cpp

ObjectLoader::ObjectLoader(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ObjectLoader)
{
  ui->setupUi(this);
   scene=new QGraphicsScene(this);
   ui->graphicsView->setScene(scene);
   ui->graphicsView->setMouseTracking(true);
  setMouseTracking(true);



}

Thats were i set mouse tracking twice In objectloader.h Then i define that method in objectloader.h

class ObjectLoader : public QMainWindow
{
    Q_OBJECT


    public:
        explicit ObjectLoader(QWidget *parent = 0);
        ~ObjectLoader();

    private slots:
    void mouseMoveEvent(QMouseEvent *event);
    protected:

    private:

    };

    #endif // OBJECTLOADER_H

And implementation of that method in objectloader.cpp

void ObjectLoader::mouseMoveEvent(QMouseEvent *event){

    qDebug()<<"Mouse moved";

}

When a mouse event is generated by Qt it is generally passed initially to the QWidget that was under the mouse pointer when the event was generated. If that QWidget accepts the event then no further processing will take place. If the event isn't accepted then Qt may propogate the event to that QWidget 's parent and so on.

In your particular case the mouse move events you are interested in are being sent to the QGraphicsView / QGraphicsScene conponents where they are being accepted and, hence, no further processing takes place. In a case like that you generally need to install an event filter to intercept and process the events of interest.

Mouse move events will occur only when a mouse button is pressed down, unless mouse tracking has been enabled with QWidget::setMouseTracking().

So, I think you should check whether mouseTracking is really enabled or not, by using ` bool hasMouseTracking() const '.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM