August 8, 2011

MFreeM MFreeM
Lab Rat
12 posts

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.

7 replies

August 8, 2011

Eddy Eddy
Area 51 Engineer
1295 posts

Example code :

  1. QString str;
  2. QTextEdit *fileText;
  3.  
  4.  fileText->append(str));

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

 Signature 

Qt Certified Specialist
Qt Ambassador

August 8, 2011

MFreeM MFreeM
Lab Rat
12 posts

Thanks Eddy, I’ll have a play.

January 24, 2012

mariusmssj mariusmssj
Lab Rat
39 posts

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

January 24, 2012

Volker Volker
Robot Herder
5428 posts

A 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:

  1. QFile file("/path/to/the/file.txt");
  2. file.open(QIODevice::ReadOnly);
  3. QTextStream stream(&file);
  4. QString content = stream.readAll();
  5. file.close();
  6. textBrowser.setPlainText(content);

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

January 25, 2012

mariusmssj mariusmssj
Lab Rat
39 posts

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

January 25, 2012

Volker Volker
Robot Herder
5428 posts

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

January 25, 2012

mariusmssj mariusmssj
Lab Rat
39 posts

Once again Volker thank you very much for your help!

 
  ‹‹ Qmake flags      QImage Rotation and Translation ››

You must log in to post a reply. Not a member yet? Register here!