Search code examples
qtqtquick2scenegraph

Mouse events not handled within QQuickItem inheritor


I want to write simple Qt Quick app with draggable QQuickItems. The items are well draggeble because of embedded MouseArea in the items. But a problem is that mouse events are not fired into C++ code in virtual overloaded functions. How to solve this problem or maybe there are some examples that I didn't find?

The QML file:

import QtQuick 2.0
import SimpleMaterial 1.0

Rectangle {
width: 320
height: 480
color: "black"

    SimpleMaterialItem {
        width: parent.width;
        height: parent.height / 3;
        color: "steelblue"
        MouseArea {
            anchors.fill: parent
            width: 64
            height: 64

            drag.target: parent
            drag.axis: Drag.XandYAxis
        }
    }
}

The C++ class:

class Item : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
public:
    Item()
    {
        setFlag(ItemHasContents, true);
        setFlag(ItemAcceptsDrops, true);
        setFlag(ItemAcceptsInputMethod, true);
        setAcceptedMouseButtons(Qt::AllButtons);
    }

    void mousePressEvent(QMouseEvent * event)
    {
        qDebug("Press");  // NOT CALLED!
    }

public:
    QSGNode *updatePaintNode(QSGNode *node, UpdatePaintNodeData *)
    {
    ...
    }
};

Solution

  • If MouseArea handles mouse event it doesn't pass event to its parent.

    You need:

    onPressed: {
        mouse.accepted = false;
    }
    

    in mouse area to let the SimpleMaterialItem handle onPressed event.