本文整理汇总了Python中AnyQt.QtWidgets.QFileDialog类的典型用法代码示例。如果您正苦于以下问题:Python QFileDialog类的具体用法?Python QFileDialog怎么用?Python QFileDialog使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QFileDialog类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_save_filename
def get_save_filename(self): # pragma: no cover
if sys.platform == "darwin":
def remove_star(filt):
return filt.replace(" (*.", " (.")
else:
def remove_star(filt):
return filt
no_ext_filters = {remove_star(f): f for f in self._valid_filters()}
filename = self._initial_start_dir()
while True:
dlg = QFileDialog(
None, "Save File", filename, ";;".join(no_ext_filters))
dlg.setAcceptMode(dlg.AcceptSave)
dlg.selectNameFilter(remove_star(self._default_valid_filter()))
dlg.setOption(QFileDialog.DontConfirmOverwrite)
if dlg.exec() == QFileDialog.Rejected:
return "", ""
filename = dlg.selectedFiles()[0]
selected_filter = no_ext_filters[dlg.selectedNameFilter()]
filename = self._replace_extension(
filename, self._extension_from_filter(selected_filter))
if not os.path.exists(filename) or QMessageBox.question(
self, "Overwrite file?",
f"File {os.path.split(filename)[1]} already exists.\n"
"Overwrite?") == QMessageBox.Yes:
return filename, selected_filter
示例2: save_image_as
def save_image_as(self):
img = self.get_selection().toImage()
if img.isNull():
QMessageBox.critical(self, self.tr('Error'), self.tr('No image was selected!'))
return
self.hide()
formats = {
self.tr('Portable Network Graphics (*.png)'): 'png',
self.tr('Joint Photographic Experts Group (*.jpg *.jpeg)'): 'jpg',
self.tr('Graphics Interchange Format (*.gif)'): 'gif',
self.tr('Bitmap (*.bmp)'): 'bmp',
self.tr('All Images (*.png *.jpg *.gif *.bmp)'): 'all'
}
file_format = None
destination = QFileDialog.getSaveFileName(self, 'Save image', '', ';;'.join(formats.keys()))
if isinstance(destination, tuple):
destination, file_format = destination
file_format = formats[file_format]
if file_format == 'all':
file_format = None
if not file_format:
file_format = destination.rsplit('.', 1)[-1]
if destination:
if file_format not in formats.values():
file_format = 'png'
if not destination.endswith('.' + file_format):
destination += '.' + file_format
img.save(destination, file_format, 0 if file_format == 'png' else 90)
self.reject()
示例3: main
def main(argv=sys.argv):
if len(argv) == 1:
filename = None
else:
if argv[1] in ["-h", "--help"]:
usage(argv)
return 0
else:
filename = argv[1]
app = QApplication(argv)
app.setAttribute(Qt.AA_EnableHighDpiScaling)
app.setAttribute(Qt.AA_UseHighDpiPixmaps)
if filename is None:
filename, _ = QFileDialog.getOpenFileName(
None, "Image file", os.path.expanduser("~/Documents"),
"Image (*.png)")
if not filename:
return 1
print(filename)
form = MainForm(filename=filename)
rect = QApplication.desktop().availableGeometry()
form.show()
form.raise_()
return app.exec_()
示例4: save_report
def save_report(self):
"""Save report"""
filename, _ = QFileDialog.getSaveFileName(
self, "Save Report", self.save_dir,
"HTML (*.html);;PDF (*.pdf);;Report (*.report)")
if not filename:
return QDialog.Rejected
self.save_dir = os.path.dirname(filename)
self.saveSettings()
_, extension = os.path.splitext(filename)
if extension == ".pdf":
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(filename)
self.report_view.print_(printer)
elif extension == ".report":
self.save(filename)
else:
def save_html(contents):
try:
with open(filename, "w", encoding="utf-8") as f:
f.write(contents)
except PermissionError:
self.permission_error(filename)
save_html(self.report_view.html())
self.report_changed = False
return QDialog.Accepted
示例5: open_report
def open_report(self):
filename, _ = QFileDialog.getOpenFileName(
self, "Open Report", self.open_dir, "Report (*.report)")
if not filename:
return
self.report_changed = False
self.open_dir = os.path.dirname(filename)
self.saveSettings()
try:
report = self.load(filename)
except (IOError, AttributeError, pickle.UnpicklingError) as e:
message_critical(
self.tr("Could not load an Orange Report file"),
title=self.tr("Error"),
informative_text=self.tr("Error occurred "
"while loading '{}'.").format(filename),
exc_info=True,
parent=self)
log.error(str(e), exc_info=True)
return
self.set_instance(report)
self = report
self._build_html()
self.table.selectRow(0)
self.show()
self.raise_()
示例6: saveScript
def saveScript(self):
index = self.selectedScriptIndex()
if index is not None:
script = self.libraryList[index]
filename = script.filename
else:
filename = os.path.expanduser("~/")
filename, _ = QFileDialog.getSaveFileName(
self, 'Save Python Script',
filename,
'Python files (*.py)\nAll files(*.*)'
)
if filename:
fn = ""
head, tail = os.path.splitext(filename)
if not tail:
fn = head + ".py"
else:
fn = filename
f = open(fn, 'w')
f.write(self.text.toPlainText())
f.close()
示例7: save_project
def save_project(self, project_path=None):
try:
if project_path is None:
project_path = QFileDialog.getExistingDirectory(self, "Select the project directory")
if project_path is not None and str(project_path)!='':
project_path = str(project_path)
self.save({}, project_path)
except Exception as e:
QMessageBox.critical(self, "Error", str(e))
示例8: save_file_as
def save_file_as(self):
file_name = self.filename or self.last_dir or os.path.expanduser("~")
filename, _ = QFileDialog.getSaveFileName(
self, "Select file", file_name, 'Distance files (*.dst)')
if not filename:
return
self.filename = filename
self.unconditional_save_file()
self.last_dir = os.path.split(self.filename)[0]
self.adjust_label()
示例9: onAddScriptFromFile
def onAddScriptFromFile(self, *args):
filename, _ = QFileDialog.getOpenFileName(
self, 'Open Python Script',
os.path.expanduser("~/"),
'Python files (*.py)\nAll files(*.*)'
)
if filename:
name = os.path.basename(filename)
contents = open(filename, "rb").read().decode("utf-8", errors="ignore")
self.libraryList.append(Script(name, contents, 0, filename))
self.setSelectedScript(len(self.libraryList) - 1)
示例10: browse
def browse(self):
"""Select a filename using an open file dialog."""
if self.filename is None:
startdir = stdpaths.Documents
else:
startdir = os.path.dirname(self.filename)
filename, _ = QFileDialog.getOpenFileName(
self, self.tr("Open"), directory=startdir, filter=self.FILTER)
if filename:
self.load(filename)
示例11: onAddScriptFromFile
def onAddScriptFromFile(self, *args):
filename, _ = QFileDialog.getOpenFileName(
self, 'Open Python Script',
os.path.expanduser("~/"),
'Python files (*.py)\nAll files(*.*)'
)
if filename:
name = os.path.basename(filename)
# TODO: use `tokenize.detect_encoding`
with open(filename, encoding="utf-8") as f:
contents = f.read()
self.libraryList.append(Script(name, contents, 0, filename))
self.setSelectedScript(len(self.libraryList) - 1)
示例12: browse_file
def browse_file(self):
"""
Open the file dialog and open the chosen file.
"""
start_path = self.last_path() or os.path.expanduser("~")
filename, _ = QFileDialog.getOpenFileName(
None, "Open File", start_path, 'All Files (*.*)')
if not filename:
return
self.closeContext()
self.add_path(filename)
self.openContext(filename)
self.open_file()
示例13: get_file_name
def get_file_name(start_dir, start_filter, file_formats):
"""
Get filename for the given possible file formats
The function uses the standard save file dialog with filters from the
given file formats. Extension is added automatically, if missing. If the
user enters file extension that does not match the file format, (s)he is
given a dialog to decide whether to fix the extension or the format.
Function also returns the writer and filter to cover the case where the
same extension appears in multiple filters. Although `file_format` is a
dictionary that associates its extension with one writer, writers can
still have other extensions that are allowed.
Args:
start_dir (str): initial directory, optionally including the filename
start_filter (str): initial filter
file_formats (dict {extension: Orange.data.io.FileFormat}): file formats
Returns:
(filename, writer, filter), or `(None, None, None)` on cancel
"""
writers = sorted(set(file_formats.values()), key=lambda w: w.PRIORITY)
filters = [format_filter(w) for w in writers]
if start_filter not in filters:
start_filter = filters[0]
while True:
filename, filter = QFileDialog.getSaveFileName(
None, 'Save As...', start_dir, ';;'.join(filters), start_filter)
if not filename:
return None, None, None
writer = writers[filters.index(filter)]
base, ext = os.path.splitext(filename)
if not ext:
filename += writer.EXTENSIONS[0]
elif ext not in writer.EXTENSIONS:
format = writer.DESCRIPTION
suggested_ext = writer.EXTENSIONS[0]
suggested_format = \
ext in file_formats and file_formats[ext].DESCRIPTION
res = fix_extension(ext, format, suggested_ext, suggested_format)
if res == fix_extension.CANCEL:
continue
if res == fix_extension.CHANGE_EXT:
filename = base + suggested_ext
elif res == fix_extension.CHANGE_FORMAT:
writer = file_formats[ext]
filter = format_filter(writer)
return filename, writer, filter
示例14: browse_file
def browse_file(self, in_demos=False):
if in_demos:
start_file = get_sample_datasets_dir()
if not os.path.exists(start_file):
QMessageBox.information(
None, "File",
"Cannot find the directory with documentation data sets")
return
else:
start_file = self.last_path() or os.path.expanduser("~/")
filename, _ = QFileDialog.getOpenFileName(
self, 'Open Distance File', start_file, "(*.dst)")
if not filename:
return
self.add_path(filename)
self.open_file()
示例15: browse_file
def browse_file(self, in_demos=False):
if in_demos:
start_file = get_sample_datasets_dir()
if not os.path.exists(start_file):
QMessageBox.information(
None, "File",
"Cannot find the directory with documentation data sets")
return
else:
start_file = self.last_path() or os.path.expanduser("~/")
filename, _ = QFileDialog.getOpenFileName(
self, 'Open Orange Data File', start_file, dialog_formats())
if not filename:
return
self.add_path(filename)
self.source = self.LOCAL_FILE
self.load_data()