Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

MouseClick event in Qt's custom widget

From Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Emulator / desktop / device
Platform(s): All Qt Supported
Keywords: QWidget, MouseClick, Event
Created: Avis (25 Nov 2009)
Last edited: hamishwillee (11 Oct 2012)


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.



#include <QWidget>
class SampleWidget : public QWidget
// define mouseClick signal
void mouseClickEvent();
// constructor
SampleWidget(QWidget *aParent);
// re-implement processing of mouse events
void mouseReleaseEvent ( QMouseEvent * e );
void mousePressEvent ( QMouseEvent * e );
// member variable to store click position
QPoint m_lastPoint;
// member variable - flag of click beginning
bool m_mouseClick;

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.


// constructor
SampleWidget::SampleWidget(QWidget *aParent)
: QWidget(aParent)
m_mouseClick = false;
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
emit mouseClickEvent;

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.

--Avis 13:33, 30 November 2010 (UTC)

This page was last modified on 11 October 2012, at 01:17.
418 page views in the last 30 days.