Search code examples
c++qtvariablesqlist

Create List dynamically in Qt


I have a struct and a QList of struct. Based on a count I want to create multiple QList.

For eg:

struct Data
{
    QString id;
    QString name;
};

QList<Data> lst;

Suppose if I have 3 values in lst, I want to create 3 QList.

for(int i=0;i<=lst.count();i++)
{
     //Declare new list here for each.
     //Result 3 lists : QList<Data> lst1,QList<Data> lst2,QList<Data> lst3
} 

Can someone please tell me if this is possible in Qt? Is there a way out?


Solution

  • You cannot declare a variing number of variables. Instead, you make lists (or other containers).

    From your comment (lst1 would have all the data where id=1), I would suggest to use a QMap<int, QList<Data>>. E.g.

    QMap<int, QList<Data>> lstN;
    QList<Data> lst;
    for(int i=0;i<lst.count();i++)
    {
        lstN[lst[i].id] << lst[i];
    }
    

    This gives you a mapping from id to the list of Data objects with that id. E.g. lstN[1] is the list of all objects with ID = 1