Important: Please read the Qt Code of Conduct -

Print out a txt file to text box

  • Hey there, another newbie question....

    I would like to display the contents of a text file on screen. Not in console, though.

    I can read in the file using QFile and hold the contents in QString. But i want to be able to see it on screen, so perhaps print it to a textbox.

    Does anybody know how or what class i would use to do this?

    Thanks in advance.

  • Example code :
    @QString str;
    QTextEdit *fileText;

    fileText->append(str)); @

    you could use a QLabel also...depending if you want to be able to edit.

  • Thanks Eddy, I'll have a play.

  • Sorry to be a total noob but what I am trying to do is to load in the content from a .txt file that will contain code and display it in my program.

    And I am not sure sure what kind of textbox should I use because I want to keep all the tabs and code structure, also with the example by Eddy how would I put that content into the text box?

    Thank you

  • A [[Doc:QTextBrowser]] with a fixed size font would be a good start. To set the contents of a file to the text box, you can use:

    QFile file("/path/to/the/file.txt");;
    QTextStream stream(&file);
    QString content = stream.readAll();

    You will have to add error checking (file open may fail).

  • Thank you Volker it worked wonders, I got another question if you don't mind.
    How would I load in another .txt file into the same text box just below the text that I loaded in from the precious file? Because I want to combine multiple text files into one textbox.
    Thank you

  • In that case just replace setPlainText(content) with append(content).

  • Once again Volker thank you very much for your help!

Log in to reply