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

时间:2015-02-09 11:21:18

标签: c++ qt

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

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

2 个答案:

答案 0 :(得分:4)

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);

答案 1 :(得分:1)

您需要逐行读取文件,然后添加到QStringList,然后添加到listView。

 QStringList *allLines = new QStringList(); //Your list for lines from the file.
 allLines->clear();

 QStringListModel *linesModel = new QStringListModel(*allLines, NULL); //Your model to set to the view.

 QFile file("/path/to/yourFileName.txt");
 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
     return;

 while (!file.atEnd()) {
     QByteArray line = file.readLine(); //Lines are read as QByteArray.
     const char *line_c = line.data(); //convert to const char*
     QString line_str = QString(QLatin1String(line_c)); //And finally convert to QString
     allLines->append(line_str); //Add to the list
 }

 linesModel->setStringList(*allLines); //Set your model's list your stringlist
 listView->setModel(linesModel); //set model of your listView linesModel. You need to use your listView's name, which might be ui->listView.