在应用程序的测试中,我需要处理并关闭QFileDialog。通过以下方式调用的对话框:
QFileDialog::getOpenFileName( ... );在测试中,我通过以下方式‘捕获’这个对话框:
QApplication::topLevelWidgets();然后选择need file by QFileDialog API。
现在我应该关闭对话框以从QFileDialog::getOpenFileName()获得有效的答案(filename);但是QDilaog的插槽没有作用(accept(),reject(),close()...)。该对话框保持打开状态。
描述here的解决方案是有效的,但在我的情况下它不是选项。我必须使用标准的对话框。
有没有办法把它关好?
发布于 2014-09-03 16:27:45
QFileDialog::getOpenFileName是一个静态方法,因此您会受到使用它的限制。
如果你想要更多的控制,我建议创建一个QFileDialog的实例并使用它。通过调用实例的close()函数,可以通过编程方式关闭对话框。
为了回应这样做不起作用的评论,下面是示例代码:
// Must create the FileDialog on the heap, so we can call close and the dialog is deleted
// Set the Qt::WA_DeleteOnClose flag if the instance is still required
QFileDialog* fileDlg = new QFileDialog(this, QString("Select Config file"), QDir::homePath(), QString("Config (*.xml)"));
// One shot timer to close the dialog programmatically
QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, &QTimer::timeout, [=]()
{
fileDlg->close();
timer->deleteLater();
} );
timer->start(3000);
fileDlg->exec();发布于 2014-09-04 00:22:23
为了显示本机对话框,您必须运行exec()或调用其中一个静态函数。
不幸的是,在Windows中,这会调用Windows API中的阻塞函数,使所显示的对话框成为模式,并运行它自己的事件循环。如果不返回到Qt事件循环,就不能使用signals/slots接口执行close()函数。
我试图通过直接从另一个线程调用close()函数来绕过这一点,但这会导致Qt尝试将事件发送到底层对话框。由于在Qt中不允许跨线程边界发送(而不是发布)事件,因此会生成致命错误。
因此,至少对于Windows来说,这是不可能的。
我没有在Windows以外的平台上测试过。我使用的代码是:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileDialog* fileDlg = new QFileDialog(0, QString("Select Config file"), QDir::homePath(), QString("Config (*.xml)"));
// spawn a new thread
QtConcurrent::run([=](){
QTimer timer;
timer.setSingleShot(true);
QEventLoop *loop = new QEventLoop;
QObject::connect(&timer, &QTimer::timeout, [=](){
fileDlg->close();
fileDlg->deleteLater();
loop->quit();
});
timer.start(3000);
loop->exec();
delete loop;
});
fileDlg->exec();
return a.exec();
}发布于 2014-09-03 16:40:41
在Windows中,您可以使用WinAPI关闭该对话框:
#define WAIT(A) while (!(A)) {}
HWND dialogHandle, button;
WAIT(dialogHandle = FindWindow(NULL, L"Open")); //write here title of the dialog
WAIT(button = FindWindowEx(dialogHandle, NULL, L"Button", L"&Open")); //write here title of the button to click
SendMessage(button, BM_CLICK, 0, 0);https://stackoverflow.com/questions/25639613
复制相似问题