代码之家  ›  专栏  ›  技术社区  ›  Guimoute

如何在QFileDialog中预填充文件名?

  •  1
  • Guimoute  · 技术社区  · 6 年前

    很好的一天,

    我做了一个程序来测量并把它们画在图表上。然后,用户可以使用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))
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   shao.lo    6 年前

    您可以使用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_())