I have a little problem with the Qt class QGraphicsScene
:
To detect the current mouse coordinates I made a new class QGraphicsScenePlus
with QGraphicsScene
as the base class. I have already redefined the slot function mouseMoveEvent(QGraphicsSceneMouseEvent* event)
and the received coordinates seem to be correct. Now I want to notify the parent QMainWindow
class, where the QGraphicsScenePlus
object is stored, whenever the mouse coordinates change. What is the best way to do this? I already tried to define signals and slots, but it didn't work. The slot function wasn't found during the execution of the program.
Here is the code so 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 my = 0;
};
#endif // QGRAPHICSSCENEPLUS_H
qgraphicssceneplus.cpp
#include "qgraphicssceneplus.h"
QGraphicsScenePlus::QGraphicsScenePlus(QObject* parent) : QGraphicsScene(parent) {
}
void QGraphicsScenePlus::mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent) {
mx = mouseEvent->scenePos().x();
my = mouseEvent->scenePos().y();
this->update();
}
Comment
I am not sure how you made the above code compiled.
1. Even though you subclass from a
QObject
, you still need theQ_OBJECT
macro to keep meta-object compiler informed:2. It's not allowed to assign primitive value in C++ class definition, do it in the constructor instead:
Solution
As for your question:
The best way is still Signals & Slots.
Code
qgraphicssceneplus.h
qgraphicssceneplus.cpp
To catch the signal, define the slot in
QMainWindow
. For example:and connect it to the signal of your graphic scene.
Demo