Tips and tricks

How to create a QT GUI Application that reads a text file and outputs in a Text Box
Posted on February 4 2011 / in QT/C++ Tutorials / 9 comments
- create new QT Project, choose QT C++ Project > Qt Gui Application, click Next
- name your application as you wish, click Next
- leave everything as it is, click Next
- click Finish
- click on the Design Tab, drag a Text Edit box
- include the following headers
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QString>
#define IO_ReadOnly QIODevice::ReadOnly - write this function before the main function
void MainWindow::populate(){}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();return a.exec();
}
- inside MainWindow.h add
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();private:
Ui::MainWindow *ui;
public slots:
void populate();
}; - open main.cpp – inside main() function add w.populate();
- inside MainWindow::populate() write ui->textEdit->append(“test”);
- if it works, we can go forward, if not, review the steps
- write this inside populate function
QFile file("c:/in.txt"); // Create a file handle for the file named
QString line;if (!file.open(IO_ReadOnly)) // Open the file
{
// handle error
}QTextStream stream( &file ); // Set the stream to read from myFile
while(!stream.atEnd()){
line = stream.readLine(); // this reads a line (QString) from the file
ui->textEdit->append(line);
} - write your text file in.txt in C:
- all done, download the source if you need to – http://digitalzoomstudio.net/misc/testut.pro.zip
Way too much time on your hands Cary, but a fantastic job
nsane! Will be taking a gander at this one for sure.
Valuable very touchable information. I would like to thank you for sharing your great facts.
Superbly written article, if only all bloggers oered the same content as you, the internet would be a far better place..
The post is written in very a good manner and it entails much useful information for me. I am happy to find your distinguished way of writing the post.
Very interesting post. really informative. of all the blogs I have read the same topic, this one is actually enlightening.
Wow, this post is pleasant, my younger sister is analyzing these things, so I am going to tell her.
Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your blog? My blog is in the very same area of interest as yours and my users would certainly benefit from some of the information you provide here. Please let me know if this alright with you. Thanks a lot!
Needed to compose you a word regarding the nice opinions you have contributed. Your good knowledge in playing with all the pieces is very useful. To be honest, this has been one outstanding blog