mouseevent - Qt: How do I notify changing mouse coordinates to parent object -


i have little problem qt class qgraphicsscene: detect current mouse coordinates made new class qgraphicssceneplus qgraphicsscene base class. have redefined slot function mousemoveevent(qgraphicsscenemouseevent* event) , received coordinates seem correct. want notify parent qmainwindow class, qgraphicssceneplus object stored, whenever mouse coordinates change. best way this? tried define signals , slots, didn't work. slot function wasn't found during execution of program.

here code far:

qgraphicssceneplus.h

#ifndef qgraphicssceneplus_h #define qgraphicssceneplus_h  #include <qobject> #include <qgraphicsscene> #include <qgraphicsscenemouseevent>  class qgraphicssceneplus : public qgraphicsscene {  public:     qgraphicssceneplus(qobject* parent = 0);  public slots:     void mousemoveevent(qgraphicsscenemouseevent* event);  public:     int mx = 0;     int = 0; };  #endif // qgraphicssceneplus_h 

qgraphicssceneplus.cpp

#include "qgraphicssceneplus.h"  qgraphicssceneplus::qgraphicssceneplus(qobject* parent) : qgraphicsscene(parent) {  }   void qgraphicssceneplus::mousemoveevent(qgraphicsscenemouseevent* mouseevent) {      mx = mouseevent->scenepos().x();     = mouseevent->scenepos().y();      this->update(); } 

comment

i not sure how made above code compiled.

1. though subclass qobject, still need q_object macro keep meta-object compiler informed:

class qgraphicssceneplus : public qgraphicsscene {      q_object    // <--- miss  public:     qgraphicssceneplus(qobject* parent = 0); 

2. it's not allowed assign primitive value in c++ class definition, in constructor instead:

public:     int mx /*= 0*/;     int /*= 0*/; }; 

solution

as question:

what best way this? tried define signals , slots, didn't work.

the best way still signals & slots.

code

qgraphicssceneplus.h

class qgraphicssceneplus : public qgraphicsscene {      q_object  public:     qgraphicssceneplus(qobject* parent = 0);  public slots:     void mousemoveevent(qgraphicsscenemouseevent* event);  signals:     void sendcoord(int,int);  // sending information of coordinates  public:     int mx;     int my; }; 

qgraphicssceneplus.cpp

qgraphicssceneplus::qgraphicssceneplus(qobject* parent) : qgraphicsscene(parent) {      mx = 0;     = 0; }  void qgraphicssceneplus::mousemoveevent(qgraphicsscenemouseevent* mouseevent) {      mx = mouseevent->scenepos().x();     = mouseevent->scenepos().y();      emit sendcoord(mx, my);  // emit signal      this->update(); } 

to catch signal, define slot in qmainwindow. example:

public slots:     void receivecoord(int x, int y); 

and connect signal of graphic scene.

demo

enter image description here


Popular posts from this blog