Search code examples
c#c++qtqlistviewqfile

What is the fastest method to populate a QListView from the content of a QFile?


Using QFile, I am reading a plain text file that contains 16,280 vocabularies, each in a new line. Then I am appending the content line by line to a QStringList. The QStringList is fed into a QStringListModel that populates a QListView.

Appending the QFile content line by line to a QStringList is killing me having to wait for a long time. Here is my code:

void MainWindow::populateListView()
{
    QElapsedTimer elapsedTimer;
    elapsedTimer.start();

    // Create model
    stringListModel = new QStringListModel(this);

    // open the file
    QFile file("Data\\zWordIndex.txt");
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
         statusBar()->showMessage("Cannot open file: " + file.fileName());
    }    

    // teststream to read from file
    QTextStream textStream(&file);

    while (true)
    {
        QString line = textStream.readLine();
        if (line.isNull())
            break;
        else
            stringList.append(line); // populate the stringlist
    }

    // Populate the model
    stringListModel->setStringList(stringList);

    // Glue model and view together
    ui->listView->setModel(stringListModel);

    //Select the first listView index and populateTextBrowser
    const QModelIndex &index = stringListModel->index(0,0);
    ui->listView->selectionModel()->select(index, QItemSelectionModel::Select);
    populateTextBrowser(index);

    //Show time
    statusBar()->showMessage("Loaded in " + QString::number(elapsedTimer.elapsed()) + " milliseconds");
}

I also developed the same app in C#. In C# I simply use: listBox1.DataSource = System.IO.File.ReadAllLines(filePath); which is so much so fast, lightning fast.

This time I am developing my app in C++ with Qt. Could you please kindly tell me a similar method, the fastest method, to populate a QListView from the content of a QFile?


Solution

  • Using QTextSteam here does not give you any benefit, it only has some overhead. Using QFile directly is probably much faster :

    while (!file.atEnd())
    {
       QByteArray lineData = file.readLine();
       QString line(lineData);
       stringList.append(line.trimmed()); // populate the stringlist
    }
    

    An other way is read the total file using readAll and parse it using split :

    stringList = QString(file.readAll()).split("\n", QString::SkipEmptyParts);