首页 > 解决方案 > 如何在python中修复列表索引超出范围?

问题描述

我有一个代码在 QlistWidget 中显示项目(文件),用户单击该项目并且系统显示其内容。

问题是当用户单击项目时系统崩溃并显示以下错误:

FileListSelected Item= oneDir + "\" + self.listWidgetPDFlist.selectedItems()[index] 中的文件“c:\Users\test\Documents\Python_Projects\tests_scripts\qt_creator\Python_Projects-AnthonyKifawi-\myPDFviewer.py”,第 159 行。文本()

builtins.IndexError:列表索引超出范围

列表中的现有文件:

显示结果:

这是 P==>C:\Users\test\Desktop\test_arabic.docx
这是 oneDir==>C:\Users\test
这是当前项目 ==C:\Users\test\Desktop\test_arabic.docx
这是是 ppp==>C:\Users\test\Desktop\test_arabic.docx 当前行 = 1

这是

P==>C:\Users\test\Desktop\test_arabic.docx
这是 oneDir==>C:\Users\test
这是当前项目 ==C:\Users\test\Desktop\test_arabic.docx 这是 ppp ==>C:\Users\test\Desktop\test_arabic.docx 当前行 = 0

代码:

def FileListSelected(self):             # Function to select the desired file from the list in the left pane
        ListIterator=range(self.listWidgetPDFlist.count())

        for index in ListIterator:
            p = pathlib.Path(self.fullPath)
            print("this is P==>{}".format(p))
            oneDir = os.path.join(*p.parts[:-2])
            print("this is oneDir==>{}".format(oneDir))            
            Item= oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text()
            print("this is the cuurent Item =={}".format(Item))            
            ppp=os.path.join(os.path.expanduser("~"), Item) 
            print("this is ppp==>{}".format(ppp))
            self.mouseHover()

            return ppp

标签: pythonfor-loopqlistwidget

解决方案


推荐阅读