PDA

View Full Version : The QInputDialog::getText(0, unexpected behaviour ...



DiIvPa
28th February 2014, 14:40
Dear Forumers, I tryed to get input file name by QInputDialog::getText(0 method and came up with strange behaviour. If after click on OK at the dialog window program didn't returned :confused:. I made another click and after that I got what I expected after first click. Why ? In case I clicked on Cancel button - everything is Ok. Could you please to give me hint how to get right behaviour ? Se my code below (I am workin on LINUX Debian Wheezy machine). Thank you in advance for help.


#include <QApplication>
#include <QInputDialog>
#include <QDebug>

void writ_file();
QString InputFileName();

QString file_name = "test.txt";

int main(int argc, char **argv){
QApplication app(argc, argv);
writ_file();
return app.exec();
}

void writ_file() {

if(InputFileName() == "" ) {
qDebug() << "Input file name -> cancelled. Uses the default name : "
<< file_name << endl;
}
else file_name = InputFileName();
qDebug() << "writ_file() -> " << file_name;
return;
}

QString InputFileName() {

bool bOk;
QString FileName = QInputDialog::getText(0,
"Input File Name",
"Name:",
QLineEdit::Normal,
"test.txt",
&bOk
);
if (!bOk) {
// Была нажата кнопка Cancel
return "";
}
qDebug() << FileName ;
//printed Filename after first click (hanging, don't make return)
// and after second click print again and make return
return FileName;
}
// Output if I press OK
// "test.txt"
// "test.txt"
// writ_file() -> "test.txt"
// Output if I press Cancel
// Input file name -> cancelled. Uses the default name : "test.txt"

// writ_file() -> "test.txt"

anda_skoa
28th February 2014, 16:01
Well, if you click OK, then InputFileName() will return the filename you have selected.

Since that filename is not "", you are getting into the else case of your if condition in writ_file, which again calls InputFileName().

And this of course shows the dialog again and again requires you to click either OK or Cancel.

I think want you want to do is



void writ_file() {
QString fileName = InputFileName();
if(fileName == "" ) {
qDebug() << "Input file name -> cancelled. Uses the default name : "
<< file_name << endl;
}
else file_name = fileName;
qDebug() << "writ_file() -> " << file_name;
return;
}


Btw, instead of returning "" just return QString() and instead of checking == "", check fileName.isEmpty()

Cheers,
_