7
votes

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).

1
Got the solution. Have to call setAcceptedMouseButtons(Qt::AllButtons) first (in the constructor). Any click on the QuickItem routes the mouse event handling to mousePressEvent(QMouseEvent *) function.Sarin
I'm not sure it's a good idea to use mouse directly in item, you have MouseArea for that. "Single Responsibility Principle" : do one thing, but doing well.gbdivers

1 Answers

15
votes

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.