简体   繁体   English

使用QFileDialog自动保存文件

[英]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: 我必须使用QTest,Qt,C ++来自动化测试:我在选项卡(tabwidget的一部分)中编写文本,然后尝试将其关闭,然后出现QFileDialog(因为我对选项卡中的纯文本进行了更改),我尝试像这样“捕获” QFileDialog:

    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. 获得QFileDialog对象后,我希望将选项卡中的更改保存到我之前在tmp目录中创建的文件“ test.txt”中。 When I execute this nothing happens, the QFileDialog pops up, but test.txt is not selected and not saved, how can I achieve this? 当我执行此操作时,什么也没有发生,QFileDialog弹出,但是未选择并保存test.txt,我该如何实现?

The selectFile method does not work if the filedialog is visible and if the focus is set to the line edit widget. 如果filedialog是可见的并且焦点设置为行编辑小部件,则selectFile方法不起作用。 From the qfiledialog.cpp (QT 5.2): 从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 对于我们的自动化测试,我们只需要暂时隐藏文件对话框,调用selectFile()并再次显示

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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