PDA

View Full Version : Handling mouse events in QGraphicsWidget subclass



Asperamanca
27th October 2010, 13:14
Hi all,

I have written a QGraphicsWidget subclass that should behave like a simple button. As it is, it should show a pixmap, and emit a signal when the left mouse button is pressed on it.

However, I never receive any mouse events. I've re-implemented the mousePressedEvent, but never reach my breakpoint within this event.

I've seen samples doing similar things that work (e.g. in the AnimatedTile example). I do not see a significant difference, and I'd like to understand what I am doing wrong.

Here's the source code, first the header file:



#ifndef BUTTON_H
#define BUTTON_H

#include <QGraphicsWidget>
#include <QGraphicsPixmapItem>

class Button : public QGraphicsWidget
{
Q_OBJECT
public:
explicit Button(QGraphicsItem *parent = 0);
void setPixmap(const QPixmap pixmap);

signals:
void pressed(void);

public slots:

protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event);

// Tried my own implementations, but no change
//QRectF boundingRect() const;
//QPainterPath shape() const;

private:
QGraphicsPixmapItem* _buttonImage;
};

#endif // BUTTON_H


Now the cpp file:



#include "button.h"
#include <QGraphicsSceneMouseEvent>

Button::Button(QGraphicsItem *parent) :
QGraphicsWidget(parent, 0)
{
setSizePolicy(QSizePolicy::Fixed,
QSizePolicy::Fixed,
QSizePolicy::DefaultType);
setPreferredSize(0,0);
setAcceptHoverEvents(true);
}

void Button::setPixmap(const QPixmap pixmap)
{
if (!_buttonImage)
delete _buttonImage;

_buttonImage = new QGraphicsPixmapItem(pixmap, this);
_buttonImage->setPos(0,0);
setPreferredSize(_buttonImage->pixmap().width(),
_buttonImage->pixmap().height());
}

void Button::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if ((event->button() == Qt::LeftButton) &&
(event->modifiers() == Qt::NoModifier))
{
emit pressed();
// Just for testing: Toggle pixmap visibility
_buttonImage->setVisible(!_buttonImage-isVisible());
event->accept();
}
else
QGraphicsWidget::mousePressEvent(event);

}

/* Tried my own implementation of boundingRect and shape,
but it did not change anything
QRectF Button::boundingRect() const
{
return QRectF(0,0,
_buttonImage->pixmap().width(),
_buttonImage->pixmap().height());
}

QPainterPath Button::shape() const
{
if (_buttonImage)
return _buttonImage->shape();
else
{
QPainterPath emptyPath;
return emptyPath;
}
}
*/


Thanks for any hints!

edit: typo

Asperamanca
27th October 2010, 16:00
I have since found out the problem only occurs if my Button object is a child of another QGraphicsWidget subclass (ButtonBar).
However, ButtonBar does not handle any events, or install any event filters. Why should a child of a QGraphicsWidget not receive any events?