Search code examples
c++qtqgraphicsitemdeclare

Qt declaring member names using a loop


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 :)


Solution

  • 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!