Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Printing file content (text) on a text browser



  • Hi,

    I've a basic question. I do the follwoing to display file content in a textBrowser:

     QString name = "log_file_"+pLabel+".txt";
    
        QFile file(name);
    
        file.open(QIODevice::ReadOnly|QIODevice::Text);
    
        QTextStream instream(& file);
    
        while (!instream.atEnd()){
                QString line = instream.readLine();
    
                qDebug()<<line; // I can see all the lines here 
    
                ui->textBrowser->setText(line+"\n"); // Here only the last line is printed 
            }
    
    
         file.close();
    

    in the above snipet

    ui->textBrowser->setText(line+"\n"); /
    

    Only prints the last line of the text, whereas I need to print whole contents on the text on textBrowser. Can you spot a mistake here?



  • @russjohn834 Hi,
    please look more closely at your code.

    ui->textBrowser->setText(line+"\n");
    

    You call setText() with a single line only.
    You could either use setSource() or read the whole content of the file and then setText().

    I imagine using setSource() would eliminate the need for the QFile and related.



  • @artwaw is correct.
    An alternative is to use append instead of setText



  • @artwaw Thanks a lot for pointing it out. I replaced readLine() with readAll(), and it works!



  • @VRonin Thank you!, that also works :)


Log in to reply