Time for action – creating a black, rectangular item
As a first approach, let's create an item that paints a black rectangle:
class BlackRectangle : public QGraphicsItem { public: explicit BlackRectangle(QGraphicsItem *parent = 0) : QGraphicsItem(parent) {} virtual ~BlackRectangle() {} QRectF boundingRect() const { return QRectF(0, 0, 75, 25); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) painter->fillRect(boundingRect(), Qt::black); } };
What just happened?
First, we subclass QGraphicItem
and call the new class BlackRectangle
. The class' constructor accepts a pointer to a QGraphicItem
item. This pointer is then passed to the constructor of the QGraphicItem
item. We do not have to worry about it; QGraphicItem
will take care of it and establish the parent-child relationship for our item, among other things. Next, the virtual destructor makes sure that it gets called even if the...