Search code examples
c++qtqlistqlineedit

Saving QList<T> to a file?


I've got a QList of QLineEdit*'s

QList<QLineEdit*> example;

Example will hold 100 items of lineEdits.

When I try to save or load to a file, it fails to save or load the QList properly, if at all. I get a much lower than expected count of data.

I see on QList<T>'s resource page here that there's the correct operator for << & >>, however I can't seem to get them to save to a file using QDataStream

I've also tried copying all the "text()" values from the LineEdits into a seperate String List but I still can't save them to a file. Any help would be appreciated.

EDIT: Looks like that did it. This is how I'm reading them back, is there a more simple approach to this, or have I pretty much covered it?

    //memoryAddresses
    for(int i = 0; i < 100; i++)
    {
        QString temp;
        loadFile >> temp;
        memAddr.at(i)->setText(temp);
    }

Solution

  • QList<QLineEdit*> is a list of pointers (basically ints so if you write that to a file you won't get much useful information.

    The text() method should do what you are looking for.

    foreach( const QLineEdit* le, example )
    {
      if( le )
      {
         ds << le->text();
      }
    }
    

    Note the differences between displayText and text.

    To read back:

    If you are only working with strings, the QTextStream class is a little nicer to use (could also be used above rather than the QDataStream...to be consistent though you should use the same type of stream for reading and writing). I am not able to test this code at the moment but you can try something like this:

    QList<QLineEdit*> example;
    while(!stream.atEnd())
    {
       QString str;
       stream >> str;
       if( stream.isNull() )
         break;
       QLineEdit* le = new QLineEdit();
       le->setText(str);
       example.append(le);
    }