Time for action – creating an item for Benjamin
First we need a custom item class for Benjamin. We call the class Player and choose QGraphicsPixmapItem as the base class because Benjamin is a PNG image. In the item's Player class, we further create a property of integer type and call it m_direction. Its value signifies in which direction Benjamin walks—left or right—or if he stands still. Of course, we use a getter and setter function for this property. Since the header file is simple, let's have a look at the implementation right away (you will find the whole source code at the end of this book):
Player::Player(QGraphicsItem *parent)
: QGraphicsPixmapItem(parent), m_direction(0) {
setPixmap(QPixmap(":/elephant"));
setTransformOriginPoint(boundingRect().center());
}In the constructor, we set m_direction to 0, which means that Benjamin isn't moving at all. If m_direction is 1, Benjamin moves right, and if the value is -1, he moves left. In the body of the constructor, we set the...