简体   繁体   中英

Disable file name box in QFileDialog

I used a QFileDialog to open a browser. Here is my code :

QString filePath = QFileDialog::getSaveFileName(this,
                                               "Export Xml", "PluginPythonQt",
                                                "Xml files (*.xml)");

When excute it will show a dialog like this:

在此处输入图像描述

I want to disable the "File name:" box in the picture or prevent user to enter a new name. How can i do that? Thanks.

I believe you can't achieve this — save dialog is about choosing name besides the choosing where to save it. Of course, you might just ignore what user typed and force your name when he hits OK but it will just make the user angry.

Better way, in my opinion, is to use QFileDialog::getExistingDirectory which will allow the user to choose where to save the file but won't allow him to choose the file name. It will be fair, at least.

Similar question was answered in https://forum.qt.io/topic/73973/qfiledialog-with-no-edit-box .

In general, you can hide any element in any widget if you dig a bit into widget's source code to find element's name, when you have a name, you can find the corresponding element via findChild<QWidget *>(elementName) . Usually if you check QSomeWidget.h (Qt is open source.) you can find element names very easily as they are typically listed as the widgets members, To hide both labels, fileEdit, ComboBox and even buttons: you can use this code:

QFileDialog fileDialog = new QFileDialog;

QWidget * fileNameEdit = fileDialog->findChild<QWidget *>("fileNameEdit");
Q_ASSERT(fileNameEdit);
fileNameEdit->setVisible(false);

QWidget * fileNameLabel = fileDialog->findChild<QWidget *>("fileNameLabel");
fileNameLabel->setVisible(false);

QWidget * fileTypeCombo = fileDialog->findChild<QWidget *>("fileTypeCombo");
Q_ASSERT(fileTypeCombo);
fileTypeCombo->setVisible(false);
    
QWidget * fileTypeLabel = fileDialog->findChild<QWidget *>("fileTypeLabel");
fileTypeLabel->setVisible(false);

QWidget * fileButtonBox = fileDialog->findChild<QWidget *>("buttonBox");
fileButtonBox->setVisible(false);

Note that even though buttons are hidden, typing Enter on keyboard (or double clicking) would trigger Open button, and dialog might disappear if you haven't done anything in Accept method. So it would also be a good idea to handle state of that button as well if you really wish buttons to be hidden as well.

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