×
Namespaces

Variants
Actions

MouseClick event in Qt's custom widget

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

Overview

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.

Source

SampleWidget.h

...
#include <QWidget>
 
class SampleWidget : public QWidget
{
Q_OBJECT
signals:
// define mouseClick signal
void mouseClickEvent();
 
public:
// constructor
SampleWidget(QWidget *aParent);
...
protected:
// re-implement processing of mouse events
void mouseReleaseEvent ( QMouseEvent * e );
void mousePressEvent ( QMouseEvent * e );
...
private:
// 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.

SampleWidget.cpp

// 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 04:17.
544 page views in the last 30 days.
×