PDA

View Full Version : Read from text file



kulsekarr
8th June 2012, 11:38
Hi,
Can any one help me how to open a text file & read values and display it in a textbox ?

Thanks...

sonulohani
8th June 2012, 12:06
Hey,
I am also from Bangalore.
So, For reading file you have to use the file handling. By using file handling, you can read the content of the text file and then set all the content on the textEdit. From that you can easily read the file. Use plainText to set the text.

Added after 10 minutes:

Try this code:---->
notepad.h


#ifndef NOTEPAD_H
#define NOTEPAD_H

#include <QWidget>
#include<QFile>
#include<QTextStream>

namespace Ui {
class Notepad;
}

class Notepad : public QWidget
{
Q_OBJECT

public:
explicit Notepad(QWidget *parent = 0);
~Notepad();

private:
Ui::Notepad *ui;
};

#endif // NOTEPAD_H



notepad.cpp


#include "notepad.h"
#include "ui_notepad.h"
Notepad::Notepad(QWidget *parent) :
QWidget(parent),
ui(new Ui::Notepad)
{
ui->setupUi(this);
QString str;
QFile file("C:\\Users\\Sonu\\Desktop\\test.txt");
if(file.open(QIODevice::ReadOnly)){
QTextStream stream(&file);
stream>>str;
file.close();
}
ui->textEdit->setText(str);
}

Notepad::~Notepad()
{
delete ui;
}


main.cpp


#include "notepad.h"
#include "ui_notepad.h"
Notepad::Notepad(QWidget *parent) :
QWidget(parent),
ui(new Ui::Notepad)
{
ui->setupUi(this);
QString str;
QFile file("yourfile.txt");
if(file.open(QIODevice::ReadOnly)){
QTextStream stream(&file);
stream>>str;
file.close();
}
ui->textEdit->setText(str);
}

Notepad::~Notepad()
{
delete ui;
}

kulsekarr
8th June 2012, 12:09
Hi,
Thankyou verymuch!!! it has worked out!!

sonulohani
8th June 2012, 12:11
notepad.ui

7818