Handling MouseEvents in Qt c++
Sorry for my beginner's question... What is the easiest way to define procedures, which are executed when MousePressEvent o开发者_StackOverflow社区r MouseReleaseEvent occurs?
For now I am defining my own class (MyGraphicsView class), which inherits QGraphicsView and I am reimplementing mouse events (which are virtual functions). It works fine but is there any way to solve this problem without a need to define a new class? Can I connect Events with Slots somehow?
Thanks for your help.
This thread on the Qt Centre forum describes quite well what your options are. Simply put:
Do what you are doing (ie subclassing and reimplementing)
Work with an event filter as described in the thread and link therein.
Because the mouse events are protected virtual functions, the easiest approach is exactly what you are doing. I don't see any reason why defining a subclass would cause a problem, so I say stick with what you have.
If you really want to connect the events with slots, you can make your subclass implementation of mousePressEvent()
, for example, simply emit mousePressSignal()
. Of course, you would also need to declare mousePressSignal()
in the signals
section of the subclass header.
I can see no problem with overriding QGraphicsView::mousePressEvent
and QGraphisView::mouseReleaseEvent
. The whole QGraphicsView
/QGraphicsScene
/QGraphicsItem
event-handling concept is built around virtual event-handling functions.
Additionally, also the Qt documentation suggests that "you can provide your own custom scene interaction, by creating a subclass of QGraphicsView
, and reimplementing the mouse and key event handlers."
From your question,
is there any way to solve this problem without having to define a new class?
The answer is No. You can't.
You have to have inherit from the class that you want to handle the events.
Can I connect Events with Slots somehow?
No. You cannot connect events to slots but only signals can be connected to slots.
The way you are now doing is the way to do.
You can use event filters: See http://doc.qt.nokia.com/4.6/qobject.html#eventFilter Or, for graphics items in particular, http://doc.qt.nokia.com/4.6/qgraphicsitem.html#sceneEventFilter
Note that for the latter, some events change: QMouseEvent becomes QGraphicsSceneMouseEvent for example, so make sure to filter for the right type.
What is easier, depends on the situation. If you have a subclass anyway, reimplementing the virtual method is often more straight-forward than the event filter approach. But if you want to track several widgets from several different classes and need special handling for a certain event, subclassing just for this purpose is tedious and not a good design (and makes e.g. using designer for those widgets harder).
精彩评论