首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在QlistWidget中获取PyQt5中存在的所有项

如何在QlistWidget中获取PyQt5中存在的所有项
EN

Stack Overflow用户
提问于 2018-04-04 08:11:56
回答 1查看 4.6K关注 0票数 1

我有一个函数,显示所选目录中存在的文件列表,然后用户输入一个搜索单词,程序在后台读取这些文件,以便找到匹配的单词,最后它只显示包含匹配单词的文件,从而覆盖现有的列表。

问题是同时循环系统显示了这个错误:

而索引< len(self.listWidgetPDFlist.count()): builtins.TypeError:'int‘类型的对象没有len()

代码:

代码语言:javascript
复制
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))     
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-04 08:19:24

count()返回项目数,因此它是一个整数,函数len()仅适用于可迭代的,而不是整数,因此您将得到该错误,而且它是不必要的。你必须做以下工作:

代码语言:javascript
复制
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,您将在第一次迭代中完成循环。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49645898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档