MouseClick event in Qt's custom widget
This article shows how a developer can process mouse press and release events in a custom QWidget. It also shows how to trigger signals from these events.
Events are the raw input that the user gives the computer. After receiving the events, the user interface can interact with the user and provide the expected functionality. Basic widgets based on QWidget have no MouseClick event processing. In this case usual way to process mouse events - is to process mousePressEvent or mouseReleaseEvent. But sometimes this leads to incorrect interaction with the user. So we need to form MouseClick event by ourself. We need process mousePressEvent and mouseReleaseEvent in pair. And the main part of this work - is to store position of MousePress and check it in MouseRelease. In this case we will generate events that trigger signals and provides interaction.
class SampleWidget : public QWidget
// define mouseClick signal
// re-implement processing of mouse events
void mouseReleaseEvent ( QMouseEvent * e );
void mousePressEvent ( QMouseEvent * e );
// member variable to store click position
// member variable - flag of click beginning
The events are processed by the event handlers, which are virtual protected methods that the widget classes override when they need to react to a given event.Each event is accompanied with an event object.
void SampleWidget::mousePressEvent ( QMouseEvent * e )
// store click position
m_lastPoint = e->pos();
// set the flag meaning "click begin"
m_mouseClick = true;
void SampleWidget::mouseReleaseEvent ( QMouseEvent * e )
// check if cursor not moved since click beginning
if ((m_mouseClick) && (e->pos() == m_lastPoint))
// do something: for example emit Click signal
The base class of all event classes is QEvent, which enables the receiver to accept or ignore an event using the methods with the same names.
--13:33, 30 November 2010 (UTC)