Qt World Summit: Register Today!

How d i load a textfile to QListwidget and also save it back

  • How do i load a text file into QListWidget , such that each line in the textfile is an item in QListWidget,

    and once i populate it, i also want to save all items of listwidget into a text file , such that each item of listwidget is in a line in the text file , to accomplish that i am attempting this

    QString temp;
      for(int i=0; i< ui->mylistwidget->count();i++)
    QListWidgetItem* item = ui->mylistwidget->item(i);
    temp += item->text();
    std::string total_script = temp.toStdString();

    i got all the text of listwidget items in a string , what do i do next if i want to save it in a text file? and also how do i load text file and populate my qlistwidget with items ?

  • Lifetime Qt Champion

    Hi and welcome to the forums.

    You could do like this using QFile and TextStream

        // save
        QFile file("e:/test.txt");
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            // bind it
            QTextStream stream(&file);
            for (int i = 0; i < ui->mylistwidget->count(); i++) {
                QListWidgetItem *item = ui->mylistwidget->item(i);
                stream << item->text() << '\n';
        // load
            QFile file("e:/test.txt");
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                // bind it
                QTextStream in(&file);
                while(!in.atEnd()) {
                    QString line = in.readLine();

  • @mrjj
    Thank you so much, can i use the file dialog box in this, if so how ?

  • Yes sure, use class QFileDialog, here is the documentation to it, so you can see all the functions and what they do. I would also really recommend using qt documentation, its a cool thing:)
    QFileDialog: https://doc.qt.io/qt-5/qfiledialog.html

    QString fileName = QFileDialog::getOpenFileName(this, "Please, chose a file to open");
    QFile file(fileName); // this creates a QFile object of our selected file

    This code gets you the name of the file you have chosen in the file dialog.

    Now if you want to save the file also via file dialog, then call:

    QString fileName = QFileDialog::getSaveFileName(this, "Please, chose where to save the file");
    QFile file(fileName); // this creates a QFile object of our selected file

    "This is a convenience static function that will return a file name selected by the user. The file does not have to exist." as the qt documentation says.

    Hope it will help)
    Have fun programming ;)

  • @mrjj Thanks so much , really helped me understand.