GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Friday, April 1, 2011

PyQt - File Dialog

To get a filename using open file dialog, use:
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.')
fname = open(filename)
data = fname.read()
self.textEdit.setText(data)
fname.close()

While to save data to file, from example from textEdit:
filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '.')
fname = open(filename, 'w')
fname.write(textEdit.toPlainText())
fname.close()
Share/Bookmark

8 comments:

  1. i am getting this Error :\
    unhandled TypeError
    "QFileDialog.getOpenFileName(QWidget parent=None, QString caption=QString(), QString directory=QString(), QString filter=QString(), QString selectedFilter=None, QFileDialog.Options options=0): argument 1 has unexpected type 'Ui_Dialog'"

    ReplyDelete
    Replies
    1. i have the same problem as well. i used QT designer to layout but i got the same error liked you mentioned when i defined the pushButton. how to fix this??

      Delete
  2. hey it worked when i typed in the first argument 'Dialog':
    filename = QtGui.QFileDialog.getOpenFileName(Dialog, 'Open File', '.')
    not 'self'

    ReplyDelete
    Replies
    1. thanks
      i got same error but solved because of ur reply

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This works for an existing file in directory, but what about saving to a new file?

    ReplyDelete
  5. Never mind, :) , didn't notice the field at the top for typing in file name.

    ReplyDelete
  6. def open_file(self):
    filename = QtGui.QFileDialog.getOpenFileName(None, 'Open File', '.')

    fname = open(filename)
    data = fname.read()
    self.textEdit.setText(data)
    fname.close()

    ReplyDelete