MouseArea Element Reference

The MouseArea item enables simple mouse handling.

[Inherits Item]

This element was introduced in Qt 4.7.

Detailed Description

The MouseArea item enables simple mouse handling.

A MouseArea is an invisible item that is typically used in conjunction with a visible item in order to provide mouse handling for that item. By effectively acting as a proxy, the logic for mouse handling can be contained within a MouseArea item.

For basic key handling, see the Keys attached property.

The enabled property is used to enable and disable mouse handling for the proxied item. When disabled, the mouse area becomes transparent to mouse events.

The pressed read-only property indicates whether or not the user is holding down a mouse button over the mouse area. This property is often used in bindings between properties in a user interface. The containsMouse read-only property indicates the presence of the mouse cursor over the mouse area but, by default, only when a mouse button is held down; see below for further details.

Information about the mouse position and button clicks are provided via signals for which event handler properties are defined. The most commonly used involved handling mouse presses and clicks: onClicked, onDoubleClicked, onPressed, onReleased and onPressAndHold.

By default, MouseArea items only report mouse clicks and not changes to the position of the mouse cursor. Setting the hoverEnabled property ensures that handlers defined for onPositionChanged, onEntered and onExited are used and that the containsMouse property is updated even when no mouse buttons are pressed.

Example Usage

The following example uses a MouseArea in a Rectangle that changes the Rectangle color to red when clicked:

  1. import QtQuick 1.0
  2.  
  3. Rectangle  {
  4.     width: 100; height: 100
  5.     color: "green"
  6.  
  7.     MouseArea  {
  8.         anchors.fill: parent
  9.         onClicked:  { parent.color = 'red' }
  10.     }
  11. }

Many MouseArea signals pass a mouse parameter that contains additional information about the mouse event, such as the position, button, and any key modifiers.

Here is an extension of the previous example that produces a different color when the area is right clicked:

  1.                 Rectangle  {
  2.     width: 100; height: 100
  3.     color: "green"
  4.  
  5.     MouseArea  {
  6.         anchors.fill: parent
  7.         acceptedButtons: Qt.LeftButton | Qt.RightButton
  8.         onClicked:  {
  9.             if (mouse.button == Qt.RightButton)
  10.                 parent.color = 'blue';
  11.             else
  12.                 parent.color = 'red';
  13.         }
  14.     }
  15. }

Properties

Signal Handlers

Property Documentation

This property holds the mouse buttons that the mouse area reacts to.

The available buttons are:

  • Qt.LeftButton
  • Qt.RightButton
  • Qt.MiddleButton

To accept more than one button the flags can be combined with the "|" (or) operator:

  1. MouseArea  { acceptedButtons: Qt.LeftButton | Qt.RightButton }

The default value is Qt.LeftButton.

  • containsMouse : bool

This property holds whether the mouse is currently inside the mouse area.

Warning: This property is not updated if the area moves under the mouse: containsMouse will not change. In addition, if hoverEnabled is false, containsMouse will only be valid when the mouse is pressed.

drag provides a convenient way to make an item draggable.

  • drag.target specifies the id of the item to drag.
  • drag.active specifies if the target item is currently being dragged.
  • drag.axis specifies whether dragging can be done horizontally (Drag.XAxis), vertically (Drag.YAxis), or both (Drag.XandYAxis)
  • drag.minimum and drag.maximum limit how far the target can be dragged along the corresponding axes.

The following example displays a Rectangle that can be dragged along the X-axis. The opacity of the rectangle is reduced when it is dragged to the right.

  1.                 Rectangle  {
  2.     id: container
  3.     width: 600; height: 200
  4.  
  5.     Rectangle  {
  6.         id: rect
  7.         width: 50; height: 50
  8.         color: "red"
  9.         opacity: (600.0 - rect.x) / 600
  10.  
  11.         MouseArea  {
  12.             anchors.fill: parent
  13.             drag.target: rect
  14.             drag.axis: Drag.XAxis
  15.             drag.minimumX: 0
  16.             drag.maximumX: container.width - rect.width
  17.         }
  18.     }
  19. }

Note: Items cannot be dragged if they are anchored for the requested drag.axis. For example, if anchors.left or anchors.right was set for rect in the above example, it cannot be dragged along the X-axis. This can be avoided by settng the anchor value to undefined in an onPressed handler.

If drag.filterChildren is set to true, a drag can override descendant MouseAreas. This enables a parent MouseArea to handle drags, for example, while descendants handle clicks:

  1. import QtQuick 1.0
  2.  
  3. Rectangle  {
  4.     width: 480
  5.     height: 320
  6.     Rectangle  {
  7.         x: 30; y: 30
  8.         width: 300; height: 240
  9.         color: "lightsteelblue"
  10.  
  11.         MouseArea  {
  12.             anchors.fill: parent
  13.             drag.target: parent;
  14.             drag.axis: "XAxis"
  15.             drag.minimumX: 30
  16.             drag.maximumX: 150
  17.             drag.filterChildren: true
  18.  
  19.             Rectangle  {
  20.                 color: "yellow"
  21.                 x: 50; y : 50
  22.                 width: 100; height: 100
  23.                 MouseArea  {
  24.                     anchors.fill: parent
  25.                     onClicked: console.log("Clicked")
  26.                 }
  27.             }
  28.         }
  29.     }
  30. }

This property holds whether the item accepts mouse events.

By default, this property is true.

  • hoverEnabled : bool

This property holds whether hover events are handled.

By default, mouse events are only handled in response to a button event, or when a button is pressed. Hover enables handling of all mouse events even when no mouse button is pressed.

This property affects the containsMouse property and the onEntered, onExited and onPositionChanged signals.

These properties hold the coordinates of the mouse cursor.

If the hoverEnabled property is false then these properties will only be valid while a button is pressed, and will remain valid as long as the button is held down even if the mouse is moved outside the area.

By default, this property is false.

If hoverEnabled is true then these properties will be valid when:

  • no button is pressed, but the mouse is within the MouseArea (containsMouse is true).
  • a button is pressed and held, even if it has since moved out of the area.

The coordinates are relative to the MouseArea.

This property holds whether the mouse area is currently pressed.

  • pressedButtons : MouseButtons

This property holds the mouse buttons currently pressed.

It contains a bitwise combination of:

  • Qt.LeftButton
  • Qt.RightButton
  • Qt.MiddleButton

The code below displays "right" when the right mouse buttons is pressed:

  1.                 Text  {
  2.     text: mouseArea.pressedButtons & Qt.RightButton ? "right" : ""
  3.     horizontalAlignment: Text.AlignHCenter
  4.     verticalAlignment: Text.AlignVCenter
  5.  
  6.     MouseArea  {
  7.         id: mouseArea
  8.         anchors.fill: parent
  9.         acceptedButtons: Qt.LeftButton | Qt.RightButton
  10.     }
  11. }

See also acceptedButtons.

  • preventStealing : bool

This property holds whether the mouse events may be stolen from this MouseArea.

If a MouseArea is placed within an item that filters child mouse events, such as Flickable, the mouse events may be stolen from the MouseArea if a gesture is recognized by the parent element, e.g. a flick gesture. If preventStealing is set to true, no element will steal the mouse events.

Note that setting preventStealing to true once an element has started stealing events will have no effect until the next press event.

By default this property is false.

This property group was introduced in QtQuick 1.1.

Signal Handler Documentation

  • MouseArea::onCanceled ()

This handler is called when mouse events have been canceled, either because an event was not accepted, or because another element stole the mouse event handling.

This signal is for advanced use: it is useful when there is more than one MouseArea that is handling input, or when there is a MouseArea inside a Flickable. In the latter case, if you execute some logic on the pressed signal and then start dragging, the Flickable will steal the mouse handling from the MouseArea. In these cases, to reset the logic when the MouseArea has lost the mouse handling to the Flickable, onCanceled should be used in addition to onReleased.

This handler is called when there is a click. A click is defined as a press followed by a release, both inside the MouseArea (pressing, moving outside the MouseArea, and then moving back inside and releasing is also considered a click).

The mouse parameter provides information about the click, including the x and y position of the release of the click, and whether the click was held.

The accepted property of the MouseEvent parameter is ignored in this handler.

This handler is called when there is a double-click (a press followed by a release followed by a press). The mouse parameter provides information about the click, including the x and y position of the release of the click, and whether the click was held.

If the accepted property of the mouse parameter is set to false in the handler, the onPressed/onReleased/onClicked handlers will be called for the second click; otherwise they are suppressed. The accepted property defaults to true.

  • MouseArea::onEntered ()

This handler is called when the mouse enters the mouse area.

By default the onEntered handler is only called while a button is pressed. Setting hoverEnabled to true enables handling of onEntered when no mouse button is pressed.

See also hoverEnabled.

  • MouseArea::onExited ()

This handler is called when the mouse exists the mouse area.

By default the onExited handler is only called while a button is pressed. Setting hoverEnabled to true enables handling of onExited when no mouse button is pressed.

See also hoverEnabled.

  • MouseArea::onPositionChanged ( MouseEvent mouse )

This handler is called when the mouse position changes.

The mouse parameter provides information about the mouse, including the x and y position, and any buttons currently pressed.

The accepted property of the MouseEvent parameter is ignored in this handler.

By default the onPositionChanged handler is only called while a button is pressed. Setting hoverEnabled to true enables handling of onPositionChanged when no mouse button is pressed.

This handler is called when there is a long press (currently 800ms). The mouse parameter provides information about the press, including the x and y position of the press, and which button is pressed.

The accepted property of the MouseEvent parameter is ignored in this handler.

This handler is called when there is a press. The mouse parameter provides information about the press, including the x and y position and which button was pressed.

The accepted property of the MouseEvent parameter determines whether this MouseArea will handle the press and all future mouse events until release. The default is to accept the event and not allow other MouseArea beneath this one to handle the event. If accepted is set to false, no further events will be sent to this MouseArea until the button is next pressed.

This handler is called when there is a release. The mouse parameter provides information about the click, including the x and y position of the release of the click, and whether the click was held.

The accepted property of the MouseEvent parameter is ignored in this handler.

See also onCanceled.

Notes provided by the Qt Community
Cool Hack
  • 4

Votes: 4

Coverage: Qt library 4.7, 4.8

Picture of njeisecke njeisecke

Lab Rat
4 notes

Nokia Certified Qt Developer

Mouse Wheel Support

Mouse Wheel Support would be very useful for Qt Quick on the Desktop. An official implementation is planned for Qt Quick 2.0 (see http://bugreports.qt.nokia.com/browse/QTBUG-7369).

In the meantime, you can use a custom C++ extension (courtesy of Max Desyatov):

wheelarea.h

  1. #ifndef WHEELAREA_H
  2. #define WHEELAREA_H
  3.  
  4. #include <QDeclarativeItem>
  5. #include <QGraphicsSceneWheelEvent>
  6.  
  7. class WheelArea : public QDeclarativeItem
  8. {
  9.     Q_OBJECT
  10.  
  11. public:
  12.     explicit WheelArea(QDeclarativeItem *parent = 0) : QDeclarativeItem(parent) {}
  13.  
  14. protected:
  15.     void wheelEvent(QGraphicsSceneWheelEvent *event) {
  16.         switch(event->orientation())
  17.         {
  18.             case Qt::Horizontal:
  19.                 emit horizontalWheel(event->delta());
  20.                 break;
  21.             case Qt::Vertical:
  22.                 emit verticalWheel(event->delta());
  23.                 break;
  24.             default:
  25.                 event->ignore();
  26.                 break;
  27.         }
  28.     }
  29.  
  30. signals:
  31.     void verticalWheel(int delta);
  32.     void horizontalWheel(int delta);
  33. };
  34.  
  35. #endif // WHEELAREA_H

main.cpp

  1. #include <QtDeclarative>
  2. #include "wheelarea.h"
  3.  
  4. int main(int argc, char **argv)
  5. {
  6. ...
  7.   qmlRegisterType<WheelArea>("MyTools", 1, 0, "WheelArea");
  8. ...
  9. }

example.qml

  1. import QtQuick 1.0
  2. import MyTools 1.0
  3.  
  4. Rect {
  5.   width: 500; height: 500
  6.   WheelArea {
  7.     anchors.fill: parent
  8.     onVerticalWheel: console.log("Vertical Wheel: " + delta)
  9.     onHorizontalWheel: console.log("Horizontal Wheel: " + delta)
  10.   }
  11. }

[Revisions]

Cool Hack
  • 4

Votes: 8

Coverage: Qt library 4.7, 4.8

Picture of njeisecke njeisecke

Lab Rat
4 notes

Nokia Certified Qt Developer

Cursor Shape Support

In its current state, Qt Quick is rather touch focused. On the Desktop however there might be a need for cursor shape support. The following C++ extension introduces a new CursorShapeArea element that allows to set a cursor in declarative way.

cursorshapearea.h

  1. #ifndef CURSORSHAPEAREA_H
  2. #define CURSORSHAPEAREA_H
  3.  
  4. #include <QDeclarativeItem>
  5.  
  6. class QsltCursorShapeArea : public QDeclarativeItem
  7. {
  8.   Q_OBJECT
  9.  
  10.   Q_PROPERTY(Qt::CursorShape cursorShape READ cursorShape WRITE setCursorShape NOTIFY cursorShapeChanged)
  11.  
  12. public:
  13.  
  14.   explicit QsltCursorShapeArea(QDeclarativeItem *parent = 0);
  15.  
  16.   Qt::CursorShape cursorShape() const;
  17.   Q_INVOKABLE void setCursorShape(Qt::CursorShape cursorShape);
  18.  
  19. private:
  20.   int m_currentShape;
  21.  
  22. signals:
  23.   void cursorShapeChanged();
  24. };
  25.  
  26. #endif // CURSORSHAPEAREA_H

cursorshapearea.cpp

  1. #include "cursorshapearea.h"
  2.  
  3. QsltCursorShapeArea::QsltCursorShapeArea(QDeclarativeItem *parent) :
  4.   QDeclarativeItem(parent),
  5.   m_currentShape(-1)
  6. {
  7. }
  8.  
  9. Qt::CursorShape QsltCursorShapeArea::cursorShape() const
  10. {
  11.   return cursor().shape();
  12. }
  13.  
  14. void QsltCursorShapeArea::setCursorShape(Qt::CursorShape cursorShape)
  15. {
  16.   if (m_currentShape == (int) cursorShape)
  17.     return;
  18.  
  19.   setCursor(cursorShape);
  20.   emit cursorShapeChanged();
  21.  
  22.   m_currentShape = cursorShape;
  23. }

main.cpp

  1. #include <QtDeclarative>
  2. #include "cursorshapearea.h"
  3.  
  4. int main(int argc, char **argv)
  5. {
  6. ...
  7.   qmlRegisterType<CursorShapeArea>("MyTools", 1, 0, "CursorShapeArea");
  8. ...
  9. }

  1. import QtQuick 1.0
  2. import MyTools 1.0
  3.  
  4. Rect {
  5.   width: 500; height: 500
  6.   CursorShapeArea {
  7.     anchors.fill: parent
  8.     anchors.margins: 50
  9.     cursorShape: Qt.OpenHandCursor
  10.   }
  11. }

[Revisions]