如何在 QFileDialog 中预填文件名?
How to pre-fill the file name in a QFileDialog?
美好的一天,
我制作了一个程序来进行测量并将它们绘制在图表上。由于 QFileDialog,用户可以在自定义位置以自定义名称将数据导出为 .csv 或将图形导出为 .png。下面是代码,大家可以自行使用。
我的问题是:如何在对话框中预先填写文件名以便用户仍然可以指定自定义名称,但如果他们不在意的话已经充满了实验参数。提前致谢。
def export_picture(self):
"""Grabs the plot on the interface and saves it in a .png file at a custom location."""
# Setup a file dialog.
MyDialog = QFileDialog()
MyDialog.setWindowTitle("Select a location to save your graph.")
MyDialog.setAcceptMode(QFileDialog.AcceptSave)
# MyDialog.a_method_to_prefill_the_file_name("name") <-- ?
MyDialog.exec_()
# Abort the function if somebody closed the file dialog without selecting anything.
if len(MyDialog.selectedFiles()) == 0:
return
# Save the file and notify the user.
CompleteName = MyDialog.selectedFiles()[0] + ".png"
self.ui.Graph.figure.savefig(fname=CompleteName, dpi=254, format="png")
Directory, File = os.path.split(FileAndPath)
print('Graph exported as "%s.png" in the folder "%s".' %(File, Directory))
您可以使用 getSaveFileName。
import sys
from PyQt5 import QtWidgets
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
button = QtWidgets.QPushButton('Get File Name...')
button.show()
def _get_file_name():
save_file, _ = QtWidgets.QFileDialog.getSaveFileName(button, "Save File...", 'foo.txt')
print(f'save_file = {save_file}')
button.clicked.connect(_get_file_name)
sys.exit(app.exec_())
美好的一天,
我制作了一个程序来进行测量并将它们绘制在图表上。由于 QFileDialog,用户可以在自定义位置以自定义名称将数据导出为 .csv 或将图形导出为 .png。下面是代码,大家可以自行使用。
我的问题是:如何在对话框中预先填写文件名以便用户仍然可以指定自定义名称,但如果他们不在意的话已经充满了实验参数。提前致谢。
def export_picture(self):
"""Grabs the plot on the interface and saves it in a .png file at a custom location."""
# Setup a file dialog.
MyDialog = QFileDialog()
MyDialog.setWindowTitle("Select a location to save your graph.")
MyDialog.setAcceptMode(QFileDialog.AcceptSave)
# MyDialog.a_method_to_prefill_the_file_name("name") <-- ?
MyDialog.exec_()
# Abort the function if somebody closed the file dialog without selecting anything.
if len(MyDialog.selectedFiles()) == 0:
return
# Save the file and notify the user.
CompleteName = MyDialog.selectedFiles()[0] + ".png"
self.ui.Graph.figure.savefig(fname=CompleteName, dpi=254, format="png")
Directory, File = os.path.split(FileAndPath)
print('Graph exported as "%s.png" in the folder "%s".' %(File, Directory))
您可以使用 getSaveFileName。
import sys
from PyQt5 import QtWidgets
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
button = QtWidgets.QPushButton('Get File Name...')
button.show()
def _get_file_name():
save_file, _ = QtWidgets.QFileDialog.getSaveFileName(button, "Save File...", 'foo.txt')
print(f'save_file = {save_file}')
button.clicked.connect(_get_file_name)
sys.exit(app.exec_())