25 June 2012

Adding Signals and Slots to QGraphicsItem

Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal. 


The QGraphicsItem class is the base class for all graphical items in a QGraphicsSceneIt provides a light-weight foundation for writing your own custom items. This includes defining the item's geometry, collision detection, its painting implementation and item interaction through its event handlers.


When we want to create a graphics item of our own, we can inherit from QGraphicsItem. QGraphicsItem is an abstract class. So two functions namely, 

virtual QRectF boundingRect() const;
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

These two functions have to be defined in the class which inherits from QGraphicsItem. But QGraphicsItem is not inherited from QObject, so we can't add signals or slots to this. So we need to inherit our class from QObject as well to access the signal slot functionality. QGraphicsObject is a predefined class which does the same thing but it is relatively slow as it has lot of other signals which you might not require. So, I prefer going for my own class which derives from both QGraphicsItem and QObject. The class below is a sample class to do so. 
 
class MyGraphicsObject : public QGraphicsItem, public QObject
{
     Q_OBJECT
     Q_INTERFACES(QGraphicsItem)
public:
     MyGraphicsObject(QGraphicsItem *parent = 0);

private:
     virtual QRectF boundingRect() const;
     virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

}; 



After defining this class, you can add signals/slots of your choices.


No comments:

Post a Comment