PDA

View Full Version : Issue with QFileDialog



baluk
25th November 2010, 12:42
Hi,

I am using QFilDialog::getOpenFilename() to get the file name chosen by the user. It is working fine for me. But the issue is when the user chose to press the "Cancel" button instead of "Open". When I press the Cancel button I am closing the dialog with close signal. But program get struck after closing the window. I am confused of writing the logic between "open" and cancel" button. My code is



QString Directoryfinder::getFilename()
{
QFileDialog *dialog;
QString filepath = dialog->getOpenFileName(this, tr("Open File"),"/home",tr("Text files(*.txt)"));
if(filepath.isNull())
connect(dialog,SIGNAL(rejected()),dialog,SLOT(clos e()));

return filepath;
}


Can anyone please guide me with the logic.

Thank You,

baluk

Lykurg
25th November 2010, 12:47
you might want to initialize your dialog? dialog is a null pointer! and by the way your connect statement doesn't make any sense.

franz
25th November 2010, 13:12
QString filepath = dialog->getOpenFileName(this, tr("Open File"),"/home",tr("Text files(*.txt)"));

QFileDialog::getOpenFileName() is a static function. You don't need an instance of QFileDialog for it, which is why this code is properly executed in the first place.

The following code is (arguably) better:

QString file = QFileDialog::getOpenFileName(this, tr("Open File"),"/home",tr("Text files(*.txt)"));




if(filepath.isNull())
connect(dialog,SIGNAL(rejected()),dialog,SLOT(clos e()));

As lykurg said, this doesn't make sense. That is for two reasons:
QFileDialog::getOpenFileName() is a static function and blocking function. When the function returns, the file dialog is already closed.
dialog is uninitialized




return filepath;

This basically means that your function should have been:

QString Directoryfinder::getFilename()
{
return QFileDialog::getOpenFileName(this, tr("Open File"), "/home", tr("Text files (*.txt)");
}

When the dialog is canceled, the string will be null. When the dialog is accepted, the string will be non-null. Based on that you can make decisions. The signals and slots will be involved as soon as you stop using the static functions and start the open() paradigm.

baluk
25th November 2010, 13:15
oke now I have initialized the dialog. it works fine. but how can I close the dialog when the user press the "Cancel" button.

Lykurg
25th November 2010, 13:18
Have you tried the static version as franz had suggested? The dialog closes itself when pressing cancel.

baluk
25th November 2010, 13:47
Thanks to both of you for detailed explanation. It is working fine now except that I have to press "Cancel" twice before it is closed. It's not an issue but just want to know the reason.