pythonpyqtqfiledialogqdir

QFileDialog returns selected file with wrong seperators


I noticed that QFileDialog instance is returning absolute paths for the member function selectedFile() that have the wrong separator for the given operating system. This is not expected on a cross platform language (python)

What should I do to correct this so that the rest of my properly OS-independant python code using 'os.sep' can be correct? I don't want to have to remember where I can and can't use it.


Solution

  • The answer came from another thread ( HERE ) that mentioned I need to use QDir.toNativeSeparators()

    so I did the following in my loop (which should probably be done in pyqt itself for us):

    def get_files_to_add(some_directory):
      addq = QFileDialog()
      addq.setFileMode(QFileDialog.ExistingFiles)
      addq.setDirectory(some_directory)
      addq.setFilter(QDir.Files)
      addq.setAcceptMode(QFileDialog.AcceptOpen)
      new_files = list()
      if addq.exec_() == QDialog.Accepted:
        for horrible_name in addq.selectedFiles():
          ### CONVERSION HERE ###
          temp = str(QDir.toNativeSeparators(horrible_name)
          ### 
          # temp is now as the os module expects it to be
          # let's strip off the path and the extension
          no_path = temp.rsplit(os.sep,1)[1]
          no_ext = no_path.split(".")[0]
          #... do some magic with the file name that has had path stripped and extension stripped
          new_files.append(no_ext)
          pass
        pass
      else:
        #not loading  anything
        pass
      return new_files