PDA

View Full Version : how to use QtextEdit to open & read text files



joebats72
27th June 2012, 16:13
Hi, I would like the following code to open any text file and display it in a QTextEdit box. This eventually works if I give the file a file name but i want this to open any text file. This is not working and cant figure out why, please help, thx.


void MainWindow::openfiledlg()
{
QFileDialog *filedlg;
filedlg->getOpenFileName(this);

QString fname;
QFile file(fname);
//QFile file("test.txt");

file.open(QFile::ReadOnly | QFile::Text);

QTextStream ReadFile(&file);
ui->textEdit->setText(ReadFile.readAll());
}

high_flyer
27th June 2012, 16:31
You are not setting your filename in to 'fname'.

joebats72
27th June 2012, 16:49
Can you please provide an example? If I enable "QFile file("test.txt");" it will work but only open this file. I would like this code to open any text file regardless of the file name.

high_flyer
27th June 2012, 17:04
Example for what?
I told you what you are doing wrong - just set the file name you get from the file selection dialog in to 'fname'.

joebats72
27th June 2012, 18:44
I meant a code example or a quick correction of what I'm doing wrong in my code. I've tried several things and it doesn't work.

Added after 24 minutes:

OK I fixed it. Thx

kito
27th June 2012, 22:36
void MainWindow:penfiledlg()
{

QString fname = QFileDialog::getOpenFileName(this);
QFile file(fname);

file.open(QFile::ReadOnly | QFile::Text);

QTextStream ReadFile(&file);
ui->textEdit->setText(ReadFile.readAll());
}

It should work for you