Tips and tricks
How to create a QT GUI Application that reads a text file and outputs in a Text Box
- 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