View Full Version : Qt4/Mac: funny problem with QGraphicsItems

19th November 2007, 19:02
Hi all,

I'm experiencing a very funny problem with the Graphics View Framework (Mac OS, Qt 4.3.2, G++ 4).

I've created a very simple class, called Obstacle, that inherits from QGraphicsItem:

#ifndef OBSTACLE_H
#define OBSTACLE_H

#include <QGraphicsItem>

class Obstacle : public QObject, public QGraphicsItem {



// Constructor
Obstacle(int width, int height, bool movable);

// Size
int obstacle_width, obstacle_height;

// itemChange() function
QVariant itemChange(GraphicsItemChange change, const QVariant & value);

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

// Tooltip
QString str_obstacle_tooltip;

void dragged();



Since I need to use a lot of objects belonging to this class, I've chosen to create a couple of dynamically allocated vectors, defined as:

Obstacle *obstacles_A[], *obstacles_B[];

Then, I create the various instances using the "new" command and I add all the object to my scene:

obstacles_A[0] = new Obstacle(130, 82, true);
obstacles_A[1] = new Obstacle(130, 82, true);
obstacles_A[2] = new Obstacle(95, 190, true);
obstacles_A[3] = new Obstacle(55, 230, true);
obstacles_A[12] = new Obstacle(49, 38, true);



Everything works fine in this way. Except if I try to create another object (the number 13). In this case, my application compiles correctly but I get an error during the linking.

This is why I'm using also another vector (obstacles_B). Using this second vector, I'm able to create more than 13 obstacles, but the amazing thing is that, when I add to the scene the first objects belonging to the second vector, the first object belonging to the first vector disappears from the scene! If I try with a second obstacle_b object, the second obstacle_a disappears, and so on.

Even more strange, it seems that the objects of the second vector "inherits" some properties from the disappearing objects: if I select (since the obstacles are selectable) one of the obstacles_b, it appears to my application as if I'd selected an object of the obstacles_a class.

Anyone could please help me to clarify this behaviour?

Many thanks,
Fabio Ruini

19th November 2007, 19:25
Obstacle *obstacles_A[]
This is incorrect - it doesn't carry the dimensions of the array and you probably trash your stack or something like that.

You should definitely use a vector or a list:

QList<Obstacle*> obstacles;
obstacles << new Obstacle(...);
obstacles[7] = new Obstacle(...);

22nd November 2007, 12:42
Hey Wisota,

thank you very much. You were right, the problem wasn't related to the Qt, but just to C++! :o

Sorry for the late reply, but I've experienced few login problems during the last days.

Thanks again,
Fabio Ruini