Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Read textfile and display on QLabel [SOLVED]

Read textfile and display on QLabel [SOLVED]

Scheduled Pinned Locked Moved General and Desktop
c++textfilereadlinux
3 Posts 2 Posters 14.4k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    marlenet15
    wrote on last edited by marlenet15
    #1

    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
    banana

    it only displays banana.

    1 Reply Last reply
    0
    • Paul H.P Offline
      Paul H.P Offline
      Paul H.
      wrote on last edited by Paul H.
      #2

      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 to line, then set the label after the loop.

      1 Reply Last reply
      1
      • M Offline
        M Offline
        marlenet15
        wrote on last edited by
        #3

        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();
        
        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved