如何在 PyQt5 中获取 QlistWidget 中存在的所有项目
how to get the all items exist in QlistWidget in PyQt5
我有一个显示所选目录中存在的文件列表的功能,然后用户输入一个搜索词,程序在后台读取这些文件以找到匹配的词,最后它覆盖现有的通过仅显示包含匹配词的文件来列出。
问题是 while 循环
系统显示此错误:
while index < len(self.listWidgetPDFlist.count()):
builtins.TypeError: object of type 'int' has no len()
代码:
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))
count()
returns 项目的数量所以它是一个整数,函数 len(
) 只适用于可迭代的,而不是整数,所以你得到那个错误,再加上它没有必要。您必须执行以下操作:
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))
注意:不要使用return,您将在第一次迭代中完成循环。
我有一个显示所选目录中存在的文件列表的功能,然后用户输入一个搜索词,程序在后台读取这些文件以找到匹配的词,最后它覆盖现有的通过仅显示包含匹配词的文件来列出。
问题是 while 循环 系统显示此错误:
while index < len(self.listWidgetPDFlist.count()):
builtins.TypeError: object of type 'int' has no len()
代码:
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))
count()
returns 项目的数量所以它是一个整数,函数 len(
) 只适用于可迭代的,而不是整数,所以你得到那个错误,再加上它没有必要。您必须执行以下操作:
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))
注意:不要使用return,您将在第一次迭代中完成循环。