简体   繁体   中英

how to create a File Dialog in python using PyQt5

i have python class called PDFviewer that upon run the program the system display a window that handle button (open folder) witch will open a file Dialog that allow the user to choose a directory and display files inside it.

the problem is that when i try to click the button the system crash and display this error :

File "C:\\Users\\test\\Documents\\Python_Projects\\final_project\\myPDFviewer.py", line 36, in sys.exit(app.exec_()) File "C:\\Users\\test\\Documents\\Python_Projects\\final_project\\myPDFviewer.py", line 24, in setExistingDirectory options=options)

builtins.TypeError: getExistingDirectory(parent: QWidget = None, caption: str = '', directory: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = QFileDialog.ShowDirsOnly): argument 1 has unexpected type 'bool'

code:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
                             QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
                             QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton)

from PyQt5.QtCore import QDir, Qt

import pdfviewer

class pdfViewer(pdfviewer.Ui_PdfPreviewWindow):

    def __init__(self,PdfPreviewObj ):
        self.PdfPreviewObj =PdfPreviewObj 
        self.setupUi(PdfPreviewObj)
        self.PdfPreviewObj.show()
        self.pushButtonOpenFolder.clicked.connect(self.setExistingDirectory)



    def setExistingDirectory(self,qf):    
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        directory = QFileDialog.getExistingDirectory(self,
                                                     "Open Folder",
                options=options)






if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    PdfPreviewWindow = QtWidgets.QMainWindow()
    pdfViewerUi = pdfViewer(PdfPreviewWindow)
    sys.exit(app.exec_())

i found the solution it did not work before because i wasn't refer the object dialog to self so the solution become :

def setExistingDirectory(self): 
    self.dialog = Dialog()
    options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
    self.directory = QFileDialog.getExistingDirectory(self.dialog, "Open Folder" ,options=options)
    self.dialog.show()       

Selecting files:

filepath = QtWidgets.QFileDialog.getOpenFileName(self, 'Select File')

Here, self represents the parent window usually the mainWindow .

Similarly, for selecting folder:

folderpath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM