Qt – Handling mouse events on a QQuickItem

mouseeventqtqtquick2

I have created a basic QML application which uses QQuickView for creating a view, and has custom QQuickItems in it. I want to handle mouse events on one such QQuickItem by reimplementing the mousepressevent(QEvent *) method. However, when I run the application and click on the QQuickItem, no call is made to mousepressevent(QEvent *) method.

The header file of the QQuickItem looks like this:

#include <QQuickItem>
#include <QSGGeometry>
#include <QSGFlatColorMaterial>

class TriangularGeometry: public QQuickItem
{
         Q_OBJECT
         public:
              TriangularGeometry(QQuickItem* parent = 0);
              QSGNode* updatePaintNode(QSGNode*, UpdatePaintNodeData*);
              void mousePressEvent(QMouseEvent *event);

         private:
              QSGGeometry m_geometry;
              QSGFlatColorMaterial m_material;
              QColor m_color;
}; 

Note: I am making use of scenegraph to render the QuickItem.

This is a snippet from the cpp file:

void TriangularGeometry::mousePressEvent(QMouseEvent *event)
{
    m_color = Qt::black;
    update(); //changing an attribute of the qquickitem and updating the scenegraph
}

I can handle mouse events from the application but, as per my requirements, I need to handle it by overriding the method mousePressEvent(QMouseEvent *event).

Best Answer

Make sure, you have called this method before handling events (constructor is a good place):

setAcceptedMouseButtons(Qt::AllButtons);

Buttons enum of course can be any what you want.

Related Topic