-2

I need to work with 512 individual rectangle items in Qt which I am implementing in a QGraphicsScene. I don't really want to declare all 512 elements manually unless I really have to. At the moment I have something like:

QGraphicsRectItem *rec1;
QGraphicsRectItem *rec2;
QGraphicsRectItem *rec3;
QGraphicsRectItem *rec4;
QGraphicsRectItem *rec5;
QGraphicsRectItem *rec6;
QGraphicsRectItem *rec7;
QGraphicsRectItem *rec8;
QGraphicsRectItem *rec9;
QGraphicsRectItem *rec10;
QGraphicsRectItem *rec11;
QGraphicsRectItem *rec12;

etc etc. This will have to go up to rec512.

I have tried to implement a for loop to do this for me:

   for(int i = 1;i=512;i++){
        QGraphicsRectItem *rec[i];
    }

However I get an error saying 'expected member name or ; after declaration specifiers'

I'm thinking its not possible to implement a loop here, is there any other way to easily declare all 512 items?

Thanks :)

Mitchell D
  • 465
  • 8
  • 24
  • 2
    You're already starting to use an advanced framework like Qt and you haven't even learned about arrays? – Benjamin Lindley Mar 04 '15 at 00:42
  • I can't believe I didn't think of that. I was so wrapped up in learning QGraphics stuff, using an array to initialise totally slipped my mind. thanks mate – Mitchell D Mar 04 '15 at 00:48

2 Answers2

0

Thanks to Benjamin Lindley for pointing out the obvious use of an array, which totally slipped my mind.

    QGraphicsRectItem *rec[512];
Mitchell D
  • 465
  • 8
  • 24
  • 3
    I'd suggest you look into [QVector](http://doc.qt.io/qt-5/qvector.html) or [QList](http://doc.qt.io/qt-5/qlist.html) which might be easier to handle in the Qt environment. When in Rome.... – Bowdzone Mar 04 '15 at 14:19
0

A better approach:

// in some .cpp file
#include <QVector>
#include <QSharedPointer>
#include <QDebug>

// Suppose we have some Test class with constructor, destructor and some methods
class Test
{
public:
    Test()
    {
        qDebug() << "Creation";
    }

    ~Test()
    {
        qDebug() << "Destruction";
    }

    void doStuff()
    {
        qDebug() << "Do stuff";
    }
};

void example()
{
    // create container with 4 empty shared poiters to Test objects
    QVector< QSharedPointer<Test> > items(4);

    // create shared poiters to Test objects
    for ( int i = 0; i < items.size(); ++i )
    {
        items[i] = QSharedPointer<Test>(new Test());
    }

    // do some stuff with objects
    for ( int i = 0; i < items.size(); ++i )
    {
        items.at(i)->doStuff();
    }

    // all Test objects will be automatically removed here (thanks to QSharedPointer)
}

In your project you should replace Test with QGraphicsRectItem (or some other class) and call appropriate functions. Good luck!

iamantony
  • 1,345
  • 17
  • 32