简体   繁体   中英

Automatically saving a file with QFileDialog

I have to automate a test using QTest, Qt, C++: I write text in a tab (part of tabwidget) and then try to close it, afterwards a QFileDialog appears ( because I made changes to the plaintext in the tab), I try to "catch" the QFileDialog like this:

    QWidgetList topWidgets = QApplication::topLevelWidgets();
    foreach (QWidget *w, topWidgets) {
        if (QFileDialog *fd = qobject_cast<QFileDialog *>(w)) {
            fd->setFileMode(QFileDialog::ExistingFiles);
            fd->selectFile("/tmp/test.txt");

        }
    }

After getting the QFileDialog object I want my changes from the tab to be saved in the file "test.txt" which I created before in the tmp directory. When I execute this nothing happens, the QFileDialog pops up, but test.txt is not selected and not saved, how can I achieve this?

The selectFile method does not work if the filedialog is visible and if the focus is set to the line edit widget. From the qfiledialog.cpp (QT 5.2):

if (!isVisible() || !d->lineEdit()->hasFocus())
    d->lineEdit()->setText(file);

For our automated tests, we just hide the filedialog for a moment, call selectFile() and show it again

Try this:

QWidgetList topWidgets = QApplication::topLevelWidgets();
foreach (QWidget *w, topWidgets) {
    if (QFileDialog *fd = qobject_cast<QFileDialog *>(w)) {
        fd->hide();
        fd->selectFile("/tmp/test.txt");
        fd->show();
        fd->exec();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM