Search code examples
pythonpyqtpyqt5qlistwidgetqlistwidgetitem

how to get the all items exist in QlistWidget in PyQt5


i have a function that display a list of files exist in selected directory then the user enter a searched word where the program read these file in the background in order to find the matching word, at the end it override the existing list by just displaying the files that include the matching word.

the problem is it the while loop the system display this error :

while index < len(self.listWidgetPDFlist.count()):

builtins.TypeError: object of type 'int' has no len()

code:

def listFiles(self):

        readedFileList = []
        index = 0
        while index < len(self.listWidgetPDFlist.count()):
            readedFileList.append(self.listWidgetPDFlist.item(index))
        print(readedFileList)

        try:
            for file in readedFileList:

                with open(file) as lstf:
                    filesReaded = lstf.read()
                    print(filesReaded)
                return(filesReaded)

        except Exception as e:
            print("the selected file is not readble because :  {0}".format(e))     

Solution

  • count() returns the number of items so it is an integer, the function len() applies only to iterable, not integers, so you get that error, plus it is not necessary. you must do the following:

    def listFiles(self):
        readedFileList = [self.listWidgetPDFlist.item(i).text() for i in range(self.listWidgetPDFlist.count())]
        try:
            for file in readedFileList:
                with open(file) as lstf:
                    filesReaded = lstf.read()
                    print(filesReaded)
                    # return(filesReaded)
    
        except Exception as e:
            print("the selected file is not readble because :  {0}".format(e)) 
    

    Note: do not use return, you will have the loop finish in the first iteration.