Read textfile and display on QLabel [SOLVED]
General and Desktop
3
Posts
2
Posters
14.4k
Views
2
Watching
-
wrote on 28 Sept 2015, 16:31 last edited by marlenet15
So I am trying to read a textfile and display it on a QLabel. This is what I have:
QFile file("test.txt"); QLabel *testLabel= new QLabel; QString line; if (file.open(QIODevice::ReadOnly | QIODevice::Text)){ QTextStream stream(&file); while (!stream.atEnd()){ line = stream.readLine(); testLabel->setText(line+"\n"); } } file.close();
However, it only writes the last line of the file. So if my file is:
apple
oranges
bananait only displays banana.
-
wrote on 28 Sept 2015, 18:04 last edited by Paul H.
It looks to me like your problem is in the loop. You are setting
line
at each iteration thru the loop to be equal to the line read. You need to append the lines you are reading from the file toline
, then set the label after the loop. -
wrote on 28 Sept 2015, 18:42 last edited by
Thank you!! I changed it to the following and it works!!!!
QFile file("test.txt"); QLabel *testLabel= new QLabel; QString line; if (file.open(QIODevice::ReadOnly | QIODevice::Text)){ QTextStream stream(&file); while (!stream.atEnd()){ line.append(stream.readLine()+"\n"); } testLabel->setText(line); } file.close();
3/3