Qt диалог выбора файла
На этом шаге рассмотрим стандартное диалоговое окно выбора файлов.
Использование стандартных окон значительно ускоряет разработку тех приложений, в которых необходимо использовать диалоговые окна выбора файлов, шрифта, цвета и т. д. Вместо того чтобы тратить время на разработку своих собственных классов, можно воспользоваться готовыми классами библиотеки Qt. К достоинствам стандартных диалоговых окон можно отнести и целостность пользовательского интерфейса, т. к. вид окон во всех приложениях, их использующих, будет один и тот же.
Диалоговое окно выбора файлов предназначено для выбора одного или нескольких файлов, а также файлов, находящихся на удаленном компьютере, и поддерживает возможность переименования файлов и создания каталогов.
Класс QFileDialog предоставляет реализацию диалогового окна выбора файлов (рис. 1) и отвечает за создание и работоспособность сразу трех диалоговых окон. Одно из них позволяет осуществлять выбор файла для откры-тия, второе предназначено для выбора пути и имени файла для его сохранения, а третье — для выбора каталога.
Рис.1. Диалоговое окно выбора файлов
Класс QFileDialog унаследован от класса QDialog. Его определение находится в файле QFileDialog.
Этот класс предоставляет следующие статические методы:
- getOpenFileName() — создает диалоговое окно выбора одного файла. Этот метод возвращает значение типа QString, содержащее имя и путь выбранного файла (см. рис. 1);
- getOpenFileNames() — создает диалоговое окно выбора нескольких файлов. Возвращает список строк типа QStringList, содержащих пути и имена файлов;
- getSaveFileName() — создает диалоговое окно сохранения файла. Возвращает имя и путь файла в строковой переменной типа QString;
- getExistingDirectory() — создает окно выбора каталога. Этот метод возвращает значение типа QString, содержащее имя и путь выбранного каталога.
Первым параметром этих методов является указатель на объект-предок, вторым передается текст заголовка окна, третьим — строка, представляющая собой рабочий каталог.
Вызов метода getOpenFileName() запустит диалоговое окно открытия файла (см. рис. 1). Четвертый параметр, передаваемый в этот метод, представляет собой фильтр (или маску), задающий расширение файлов. Например:
Покажем, как можно использовать статический метод getSaveFileName(), предназначенный для диалогового окна записи файла.
Файлы приложения можно взять здесь.
При помощи метода getExistingDirectory() можно предоставить пользователю возможность выбора каталога (рис. 2). Например:
Рис.2. Диалоговое окно выбора папки
Файлы приложения можно взять здесь.
На следующем шаге рассмотрим cтандартное диалоговое окно настройки принтера.
The QFileDialog class enables a user to traverse the file system in order to select one or many files or a directory.
The easiest way to create a QFileDialog is to use the static functions.
In the above example, a modal QFileDialog is created using a static function. The dialog initially displays the contents of the “/home/jana” directory, and displays files matching the patterns given in the string “Image Files (*.jpg *.jpg *.bmp)”. The parent of the file dialog is set to this , and the window title is set to “Open Image”.
If you want to use multiple filters, separate each one with two semicolons. For example:
You can create your own QFileDialog without using the static functions. By calling setFileMode() , you can specify what the user must select in the dialog:
In the above example, the mode of the file dialog is set to AnyFile , meaning that the user can select any file, or even specify a file that doesn’t exist. This mode is useful for creating a “Save As” file dialog. Use ExistingFile if the user must select an existing file, or Directory if only a directory may be selected. See the FileMode enum for the complete list of modes.
The fileMode property contains the mode of operation for the dialog; this indicates what types of objects the user is expected to select. Use setNameFilter() to set the dialog’s file filter. For example:
In the above example, the filter is set to "Images (*.jpg *.xpm *.jpg)" , this means that only files with the extension png , xpm , or jpg will be shown in the QFileDialog . You can apply several filters by using setNameFilters() . Use selectNameFilter() to select one of the filters you’ve given as the file dialog’s default filter.
The file dialog has two view modes: List and Detail . List presents the contents of the current directory as a list of file and directory names. Detail also displays a list of file and directory names, but provides additional information alongside each name, such as the file size and modification date. Set the mode with setViewMode() :
The last important function you will need to use when creating your own file dialog is selectedFiles() .
In the above example, a modal file dialog is created and shown. If the user clicked OK, the file they selected is put in fileName .
The dialog’s working directory can be set with setDirectory() . Each file in the current directory can be selected using the selectFile() function.
The Standard Dialogs example shows how to use QFileDialog as well as other built-in Qt dialogs.
By default, a platform-native file dialog will be used if the platform has one. In that case, the widgets which would otherwise be used to construct the dialog will not be instantiated, so related accessors such as layout() and itemDelegate() will return null. You can set the DontUseNativeDialog option to ensure that the widget-based implementation will be used instead of the native dialog.
See also
QDir QFileInfo QFile QColorDialog QFontDialog Standard Dialogs Example Application Example
PySide2.QtWidgets.QFileDialog([parent=None[, caption=””[, directory=””[, filter=””]]]])
The QFileDialog class enables a user to traverse the file system in order to select one or many files or a directory.
The easiest way to create a QFileDialog is to use the static functions.
In the above example, a modal QFileDialog is created using a static function. The dialog initially displays the contents of the “/home/jana” directory, and displays files matching the patterns given in the string “Image Files (*.jpg *.jpg *.bmp)”. The parent of the file dialog is set to this, and the window title is set to “Open Image”.
If you want to use multiple filters, separate each one with two semicolons. For example:
You can create your own QFileDialog without using the static functions. By calling setFileMode() , you can specify what the user must select in the dialog:
In the above example, the mode of the file dialog is set to AnyFile , meaning that the user can select any file, or even specify a file that doesn’t exist. This mode is useful for creating a “Save As” file dialog. Use ExistingFile if the user must select an existing file, or Directory if only a directory may be selected. See the FileMode enum for the complete list of modes.
The fileMode property contains the mode of operation for the dialog; this indicates what types of objects the user is expected to select. Use setNameFilter() to set the dialog’s file filter. For example:
In the above example, the filter is set to "Images (*.jpg *.xpm *.jpg)" , this means that only files with the extension png , xpm , or jpg will be shown in the QFileDialog . You can apply several filters by using setNameFilters() . Use selectNameFilter() to select one of the filters you’ve given as the file dialog’s default filter.
The file dialog has two view modes: List and Detail . List presents the contents of the current directory as a list of file and directory names. Detail also displays a list of file and directory names, but provides additional information alongside each name, such as the file size and modification date. Set the mode with setViewMode() :
The last important function you will need to use when creating your own file dialog is selectedFiles() .
In the above example, a modal file dialog is created and shown. If the user clicked OK, the file they selected is put in fileName .
The dialog’s working directory can be set with setDirectory() . Each file in the current directory can be selected using the selectFile() function.
The Standard Dialogs example shows how to use QFileDialog as well as other built-in Qt dialogs.
By default, a platform-native file dialog will be used if the platform has one. In that case, the widgets which would otherwise be used to construct the dialog will not be instantiated, so related accessors such as layout() and itemDelegate() will return null. Also, not all platforms show file dialogs with a title bar, so be aware that the caption text might not be visible to the user. You can set the DontUseNativeDialog option to ensure that the widget-based implementation will be used instead of the native dialog.
PySide6.QtWidgets.QFileDialog([parent=None[, caption=””[, directory=””[, filter=””]]]])
caption – str
directory – str
filter – str
f – WindowFlags
Constructs a file dialog with the given parent and widget flags .
Constructs a file dialog with the given parent and caption that initially displays the contents of the specified directory . The contents of the directory are filtered before being shown in the dialog, using a semicolon-separated list of filters specified by filter .
This enum describes the view mode of the file dialog; i.e. what information about each file will be displayed.
Constant | Description |
---|---|
QFileDialog.Detail | Displays an icon, a name, and details for each item in the directory. |
QFileDialog.List | Displays only an icon and a name for each item in the directory. |
This enum is used to indicate what the user may select in the file dialog; i.e. what the dialog will return if the user clicks OK.
Constant | Description |
---|---|
QFileDialog.AnyFile | The name of a file, whether it exists or not. |
QFileDialog.ExistingFile | The name of a single existing file. |
QFileDialog.Directory | The name of a directory. Both files and directories are displayed. However, the native Windows file dialog does not support displaying files in the directory chooser. |
QFileDialog.ExistingFiles | The names of zero or more existing files. |
Only show directories in the file dialog. By default both files and directories are shown. (Valid only in the Directory file mode.)
Don’t resolve symlinks in the file dialog. By default symlinks are resolved.
Don’t ask for confirmation if an existing file is selected. By default confirmation is requested.
Note: This opption is not supported on macOS when using the native file dialog.
Constant | Description |
---|---|
QFileDialog.DontUseNativeDialog | Don’t use the native file dialog. By default, the native file dialog is used unless you use a subclass of QFileDialog that contains the Q_OBJECT macro, or the platform does not have a native dialog of the type that you require. |
This option must be set before changing dialog properties or showing the dialog.
Indicates that the model is readonly.
Indicates if the file name filter details are hidden or not.
Always use the default directory icon. Some platforms allow the user to set a different icon. Custom icon lookup cause a big performance impact over network or removable drives. Setting this will enable the QFileIconProvider::DontUseCustomDirectoryIcons option in the icon provider. This enum value was added in Qt 5.2.
This property holds the accept mode of the dialog.
The action mode defines whether the dialog is for opening or saving files.
By default, this property is set to AcceptOpen .
See also
AcceptMode
path – str
This property holds suffix added to the filename if no other suffix was specified.
This property specifies a string that will be added to the filename if it has no suffix already. The suffix is typically used to indicate the file type (e.g. “txt” indicates a text file).
If the first character is a dot (‘.’), it is removed.
Returns the directory currently being displayed in the dialog.
directory – str
Returns the url of the directory currently being displayed in the dialog.
This property holds the file mode of the dialog.
The file mode defines the number and type of items that the user is expected to select in the dialog.
By default, this property is set to AnyFile .
This function will set the labels for the FileName and Accept DialogLabel s. It is possible to set custom text after the call to .
See also
FileMode
file – str
files – list of strings
Returns the filter that is used when displaying files.
filter – str
caption – str
dir – str
options – Options
This is a convenience static function that will return an existing directory selected by the user.
This function creates a modal file dialog with the given parent widget. If parent is not None , the dialog will be shown centered over the parent widget.
The dialog’s working directory is set to dir , and the caption is set to caption . Either of these may be an empty string in which case the current directory and a default caption will be used respectively.
The options argument holds various options about how to run the dialog, see the Option enum for more information on the flags you can pass. To ensure a native file dialog, ShowDirsOnly must be set.
On Windows and macOS, this static function will use the native file dialog and not a QFileDialog . However, the native Windows file dialog does not support displaying files in the directory chooser. You need to pass DontUseNativeDialog to display files using a QFileDialog .
Note that the macOS native file dialog does not show a title bar.
On Unix/X11, the normal behavior of the file dialog is to resolve and follow symlinks. For example, if /usr/tmp is a symlink to /var/tmp , the file dialog will change to /var/tmp after entering /usr/tmp . If options includes DontResolveSymlinks , the file dialog will treat symlinks as regular directories.
On Windows, the dialog will spin a blocking modal event loop that will not dispatch any QTimers, and if parent is not None then it will position the dialog just below the parent’s title bar.
Do not delete parent during the execution of the dialog. If you want to do this, you should create the dialog yourself using one of the QFileDialog constructors.
Использование стандартных окон значительно ускоряет разработку тех приложений, в которых необходимо использовать стандартные диалоговые окна выбора файлов, шрифта, цвета и т. д. Вместо того, чтобы тратить время на разработку своих собственных классов, можно воспользоваться готовыми классами библиотеки Qt. К достоинствам стандартных диалоговых окон можно отнести целостность пользовательского интерфейса, так как вид окон, во всех приложениях использующих их, будет один и тот же.
Диалоговое окно выбора файлов QFileDialog
Оно предназначено для выбора одного или нескольких файлов, а также файлов, находящихся на удаленном компьютере, включает в себя возможность переименования файлов и создания директорий. Класс QFileDialog предоставляет реализацию диалогового окна выбора файлов и отвечает за создание и работоспособность сразу трех диалоговых окон. Одно из них позволяет осуществлять выбор файла для открытия, второе – предназначено для выбора пути и имени файла для его сохранения, а третье — предназначено для выбора директории. Класс QFileDialog унаследован от класса QDialog. Его определение находится в файле QFileDialog.
Этот класс предоставляет следующие статические методы:
- getOpenFileName() создает диалоговое окно выбора одного файла. Этот метод возвращает значение типа QString, содержащее имя и путь выбранного файла;
- getOpenFileNames() создает диалоговое окно выбора нескольких файлов. Возвращает список строк типа QStringList, содержащих пути и имена файлов;
- getSaveFileName() создает диалоговое окно сохранения файла. Возвращает имя и путь файла в строковой переменной типа QString;
- getExistingDirectory() создает окно выбора директории. Этот метод возвращает значение типа QString, содержащее имя и путь выбранной директории.
- Первым параметром этих методов является указатель на объект-предок, вторым — передается текст заголовка окна, третьим — строка, представляющая собой рабочую директорию.
Вызов метода getOpenFileName() запустит диалоговое окно открытия файла. Четвертый параметр, передаваемый в этот метод, представляет собой фильтр (или маску), задающий расширение файлов. Например:
При помощи метода getExistingDirectory() можно предоставить пользователю возможность выбора директории. Например:
Программа, показанная на рисунке, является результатом создания собственного диалогового окна. При запуске на экране окно с кнопкой Press Me (Нажми меня), нажатие на которую отображает диалоговое окно ввода имени First Name (Имя) и фамилии Last Name (Фамилия).
В файле main.cpp создается виджет класса StartDialog, предназначенный для запуска диалогового окна.
Класс StartDialog унаследован от класса кнопки нажатия. Сигнал clicked() соединяется в методе connect() со слотом slotButtonClicked(). В этом слоте создается объект диалогового окна InputDialog, который не имеет предка.
Примечание: Диалоговые окна, не имеющее предка, будут центрироваться по экрану. Окна с предками будут отцентрированы относительно предка.
В операторе if производится запуск диалогового окна. После его закрытия управление передается основной программе и метод exec() возвращает значение нажатой пользователем кнопки. В том случае, если пользователем была нажата кнопка Ok, произойдет отображение информационного окна с введенными в диалоговом окне данными. По завершении метода диалоговое окно нужно удалить самому, так как у него нет предка, который позаботится об этом.
Для создания своего собственного диалогового окна нужно унаследовать класс QDialog. Класс InputDialog содержит два атрибута — указатели m_ptxtFirstName и m_ptxtLastName на виджеты однострочного текстового поля, и два метода, возвращающие содержимое этих полей — firstName() и lastName().
По умолчанию область заголовка диалогового окна содержит кнопку ?, служащую для получения подробной информации о назначении виджетов.
В нашем примере я решил пренебречь ею — для этого необходимо установить флаги окна, поэтому вторым параметром передаются флаги Qt::WindowTitleHint и Qt::WindowSystemMenuHint, первый устанавливает заголовок окна, а второй — добавляет системное меню с возможностью закрытия окна.
Модальное диалоговое окно всегда должно содержать кнопку Cancel (Отмена). Сигналы clicked() кнопок Ok и Cancel (Отмена) соединяются со слотами accept() и rejected() соответственно. Это делается для того, чтобы метод exec() возвращал при нажатии кнопки Ok значение QDialog::Accepted, а при нажатии на кнопку Cancel (Отмена) — значение QDialog::Rejected.
Читайте также: