1

How to simulate the cancel button pressing for QFileDialog?

Searching doesn't help much here as most threads (like this one) are talking about simulating key pressing for QT application, not particularly for a QFileDialog.

P.S.: I want to do this because currently I am using a library created by others, the code somehow depend on the QFileDialog to open. It is becoming very annoying if needing user intersection each time by manually pressing the cancel button.

Any help is appreciated.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • Does the library use static methods like `QFileDialog::getOpenFileName` or `QFileDialog` objects? Can you acquire `QFileDialog` pointer? Can you change the library code? Do you want to cancel dialog immediately after showing it (or prevent showing it) or at any time after showing? – Pavel Strakhov Apr 27 '14 at 10:33
  • @PavelStrakhov I can acquire the `QFileDialog` pointer and have the right to change the library code. It'll be better if I can cancel the dialog at any time after showing. Thanks. – herohuyongtao Apr 27 '14 at 10:37

1 Answers1

1

I assume the library uses QFileDialog as shown in the documentation:

QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::AnyFile);
QStringList fileNames;
if (dialog.exec()) {
  fileNames = dialog.selectedFiles();
}

In that case you can just hide it. It causes exec() to return QDialog::Rejected immediately:

fileDialog->hide();
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • Hi Pavel, thanks for quick response. But it doesn't work for me, it still shows the dialog without closing automatically. Is there anything related to the dialog calling function `getSaveFileName()`? – herohuyongtao Apr 27 '14 at 11:14
  • 1
    `getSaveFileName` is a static function that uses native file dialog. I'm not even sure that `QFileDialog` object is created when it's used. At least on Windows it blocks event loop, so I can't execute anything while the dialog is open. I think it's not possible to do something with this kind of dialog. If you can change the code, you should replace all `QFileDialog` calls to a custom wrapper that will behave as you wish. – Pavel Strakhov Apr 28 '14 at 13:02