如何使用文本文件中的内容填充 Qt ListView?

Bha*_*gya 5 c++ qt

我有一个包含许多词汇表的文本文件,每个词汇表由一个新行分隔。

如何使用文本文件中的词汇填充 Qt ListView?

Sri*_*jan 5

QStringListModel *model;

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

QStringList stringList;

// open the file
QFile textFile("/<FullPath>/<fileName>");
if(!textFile.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0,"Error",textFile.errorString());
}

// teststream to read from file
QTextStream textStream(&textFile);
while (true)
{
    QString line = textStream.readLine();
    if (line.isNull())
        break; 
    else
        stringList.append(line); // populate the stringlist
}

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

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

// if you want to add additional feature to listview.
ui->listView->
        setEditTriggers(QAbstractItemView::AnyKeyPressed |
                        QAbstractItemView::DoubleClicked);
Run Code Online (Sandbox Code Playgroud)