Read textfile and display on QLabel [SOLVED]



  • 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.



  • 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.



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

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.