How can I view a txt file in QlistWidget.
-
In my code, I'm trying to open a txt file with a openfilename then view this txt file in QlistWidget.
I have a problem on line 50 in the code: ui-> listWidget-> setText (in.readAll ());
Being that setText is not a member of QlistWidget class.
How can I solve this?My code:
@
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <iostream>
#include <string>
#include <QListWidget>
#include <QtGui>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow){
ui->setupUi(this);
}MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::on_pushButton_clicked()
{
QString filename=QFileDialog::getOpenFileName( this, tr("Open File"), "C://", "All files (*.*);; Text File (*.txt)" ); QMessageBox::information(this, tr("File Name"),filename); if (!filename.isEmpty()) { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; } QTextStream in(&file); ui->listWidget->setText(in.readAll()); file.close(); }
}
@ -
-
With QPlainTextEdit is not possible to do what I want, because I have to open a txt file and each line should behave like an itemand can be selected by full and so I will delete it or will insert another.
What I want to do is similar to the Matlab image, and these directories that appear in figure, would be those in the txt file that I want to show.
!http://www.intechgrity.com/wp-content/uploads/2012/12/setpath-dialogue-box2.png -
Ok why didn't you say that in the first post, then it actually makes sense to use a list view. :)
I think the "examples in the doc of QListWidget":http://qt-project.org/doc/qt-5/qlistwidget.html#details should show you all you need for a simple list view? if you don't have thousands of lines in your text file that should be performant enough to populate the list with all lines at startup, you could also use a QListView with a custom model and load the text dynamically if you want, but if you text file is not that large that is just more work with the same result I think. -
Well you know how to read a text file and how to display text in a list widget, sometimes I think nobody want to think for themselves anymore.. :p
just split the text by line breaks or better read the file line by line directly and create list item for every item, is that so hard?
@
QString line = in.readLine(); // in = your QTextStream
while (!line.isNull()) {
new QListWidgetItem(line, ui->listWidget);
line = in.readLine();
}
@
that is all I guess :)