Creating custom QGraphicsItems
by fred on Jun.13, 2009, under Qt
Previously, I’ve shown you how to place items in a scene (through convenience functions). Now we’ll talk about how to create your own custom QGraphicsItems.
In order to do that, you must first subclass from QGraphicsItem class. There are two important methods to be reimplemented:
- boundingRect: virtual function that returns the area that needs to be painted. All items have a bounding rectangle and QGraphicsView uses this function to determine what parts need to be redrawn.
- paint: virtual function that implements the painting method itself. It uses a QPainter object.
Let’s take a look at a sample code:
class CustomItem : public QGraphicsItem { public: CustomItem(QGraphicsItem *parent = 0); QRectF boundingRect() const { return QRectF(0, 0, 250, 250); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setRenderHint(QPainter::Antialiasing); painter->setBrush(Qt::blue); painter->drawRoundedRect(0, 0, 250, 250, 5, 5); } };
As you can see, the boundingRect method returns a QRectF object containing the draw area. Inside the paint method, we set the brush color to blue and draw a rounded rectangle of same size as the bounding rectangle. Also, the Antialiasing flag is enabled so that the engine draw smooth edges.
There are 2 more parameters in the paint method: QStyleOptionGraphicsItem and QWidget. The first is the style option for the item and the second is an optional parameter that describes the widget to draw the item.
The QPainter parameter is the most important one right now. But, as you become more acquainted with the Qt Canvas Programming, you should look further into the other 2 parameters, specially the QStyleOptionGraphicsItem.
After adding the item (CustomItem class) to the scene and displaying it, the result is this:

Custom item drawn from QGraphicsItem.
There are several options to choose from when drawing an item with the QPainter object. You just have to replace the drawRoundedRect method with the another suitable one. There are a couple of examples below:

QPainter draw methods.
The source code used for this post is available here: custom-qgraphicsitem.tar.gz. Use it to create your customized QGraphicsItems.
Till next time.