Important: Please read the Qt Code of Conduct -

[Solved] A way to save QTreeWidget to file

  • Hello,

    I'm trying to save QTreeWidget to file and load it another time. I wrote this code but it didnt work.


    @ QList<QTreeWidgetItem *> myList;
    for(int i = 0; i < treeWidget->topLevelItemCount(); i++)
    myList << treeWidget->takeTopLevelItem(i);

        QDataStream outStream(&file);
        outStream << myList;@


    @QDataStream inStream(&file);
    inStream >> myList; // error

    Is there any simple function or way to do this?


  • "This": page contains a list of all the Qt types/objects that are serializable, QTreeWidgetItem isn't one of them I'm afraid. AFAIK there is no built in way to directly stream a QTreeWidget to a file. I think you'll have to traverse the data structure and save it in a suitably structured file format (JSON or XML for example).

  • thanks for your reply jazzycamel. Any example code to do it with XML?

  • I use a Qt Library called "Qtilities": It has its own way of "building trees": with Observers

    I has its own "observer widget": that can then be used to display this tree.

    Using the built in functions, this tree can then saved to an XML or binary file. Perhaps you can also use this library as is or look at the code of how it is done.

    There is a section in the docs on "saving and loading the tree to XML": that will do all the work for you.

  • Thanks Badger. I didn't know about Qtilities before.

    also I found a way to do it with QStringList because my structure was simple..

    Like this

    QList<QStringList> myList;

            QDataStream inStream(&file);
            inStream >> myList;
             for(int i = 0; i < myList.size(); i++)
             QTreeWidgetItem *item = new QTreeWidgetItem(;


    Thanks all for replying. Problem solved!

Log in to reply