如何获取QlistWidget中存在的文件路径

时间:2022-02-15 23:00:36

I have a code that display items (files) in a QlistWidget where the user click on the item and the system display its content.

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

example :

  • C:\Users\test\Desktop\New Microsoft Word Document.docx ==> row 0
  • C:\ Users \ test \ Desktop \ New Microsoft Word Document.docx ==> row 0

  • C:\Users\test\Desktop\test_arabic.docx ==> row 1
  • C:\ Users \ test \ Desktop \ test_arabic.docx ==>第1行

when try to print the result the system display the correct row number but wrong path, where it display the first selected file path whatever you choose next

当尝试打印结果时,系统显示正确的行号但路径错误,它显示第一个选择的文件路径,无论您接下来选择什么

code:

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

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

            print("current row = {}".format(self.listWidgetPDFlist.currentRow()))
            self.mouseHover()
            return Item

1 个解决方案

#1


0  

Since you did not submit the complete code, I inserted your fileListSelected(self) method into my example.

由于您没有提交完整的代码,我将fileListSelected(self)方法插入到我的示例中。

I do not know what self.fullPath is, so I set the path of the current directory toos.getcwd().

我不知道self.fullPath是什么,所以我设置了当前目录toos.getcwd()的路径。

  1. Execute the add items
  2. 执行添加项目

  3. Show selected file
  4. 显示所选文件

Try it:

import os      
import pathlib

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.textEditTotalPDFnumber = QtWidgets.QTextEdit('QTextEdit')
        self.textEditTotalPDFnumber.setReadOnly(True)

        self.listWidgetPDFlist = QtWidgets.QListWidget()

        self.vlayout = QtWidgets.QVBoxLayout()
        self.vlayout.addWidget(self.listWidgetPDFlist)
        self.vlayout.addWidget(self.textEditTotalPDFnumber)

        self.btnAddItems = QtWidgets.QPushButton()
        self.btnAddItems.setText('add items')
        self.vlayout.addWidget(self.btnAddItems)
        self.btnAddItems.clicked.connect(self.addItems)

        self.btnPrintItems = QtWidgets.QPushButton()
        self.btnPrintItems.setText('print the total number of checked items')
        self.vlayout.addWidget(self.btnPrintItems)
        self.btnPrintItems.clicked.connect(self.printItems)

        ### +++++++++++++++++++++++++++++++++++++++++++++++
        self.btnShowSelectedFile = QtWidgets.QPushButton()
        self.btnShowSelectedFile.setText('Show selected file')
        self.vlayout.addWidget(self.btnShowSelectedFile)
        self.btnShowSelectedFile.clicked.connect(self.fileListSelected)        

        self.setLayout(self.vlayout)

    def addItems(self):
        Files = ["file1.txt", "file2.py", "file3.txt",]
        self.textEditTotalPDFnumber.append("\naddItems --> Files {}".format(Files))

        self.ListFilesInViewer(Files)

    def ListFilesInViewer(self, Files):              
        for itemFile in Files:
            item = QtWidgets.QListWidgetItem(itemFile)
            item.setCheckState(QtCore.Qt.Unchecked)  #Unchecked
            item.setText('{}'.format(str(itemFile), str(self.listWidgetPDFlist.count())))
            self.listWidgetPDFlist.addItem(item)  # listWidgetPDFlist

    ### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++        
    def fileListSelected(self):             # Function to select the desired file from the list in the left pane
        """
        ListIterator=range(self.listWidgetPDFlist.count() -1)
        for index in ListIterator:
            p = pathlib.Path(self.fullPath)
            print(" FILE SELECTED this is P==>{}".format(p))
            oneDir = os.path.join(*p.parts[:-2])
            print("FILE SELECTED this is oneDir==>{}".format(oneDir))            
            Item= oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text()
            print("FILE SELECTED this is the cuurent Item =={}".format(Item))            
            print("current row = {}".format(self.listWidgetPDFlist.currentRow()))
            self.mouseHover()
            return Item            
        """
        #p = pathlib.Path(self.fullPath) 
        p = pathlib.Path(os.getcwd())  
        self.textEditTotalPDFnumber.append("\n FILE SELECTED this is   P              =>`{}`".format(p))
        oneDir = os.path.join(*p.parts[:-2])
        self.textEditTotalPDFnumber.append(" FILE SELECTED this is   oneDir      =>`{}`".format(oneDir))   
        self.textEditTotalPDFnumber.append("listWidgetPDFlist.selectedItems     =>`{}`".format(self.listWidgetPDFlist.selectedItems()))
        #Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text()
        if self.listWidgetPDFlist.selectedItems():
            Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[0].text()
            self.textEditTotalPDFnumber.append(" FILE SELECTED this is the cuurent Item =>`<b>{}</b>`\n".format(Item))
            #self.mouseHover()
            #return Item
        else:
            self.textEditTotalPDFnumber.append("<b>!!! NO SELECTED FILE !!!</b>\n")

    def printItems(self):
        checkedItem = 0

        for index in range(self.listWidgetPDFlist.count()):
            if self.listWidgetPDFlist.item(index).checkState() == QtCore.Qt.Checked:
                 checkedItem += 1        

        self.textEditTotalPDFnumber.append("\nchecked items --> {}".format(str(checkedItem)))


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.resize(600, 400)
    window.show()
    sys.exit(app.exec_())

如何获取QlistWidget中存在的文件路径

#1


0  

Since you did not submit the complete code, I inserted your fileListSelected(self) method into my example.

由于您没有提交完整的代码,我将fileListSelected(self)方法插入到我的示例中。

I do not know what self.fullPath is, so I set the path of the current directory toos.getcwd().

我不知道self.fullPath是什么,所以我设置了当前目录toos.getcwd()的路径。

  1. Execute the add items
  2. 执行添加项目

  3. Show selected file
  4. 显示所选文件

Try it:

import os      
import pathlib

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.textEditTotalPDFnumber = QtWidgets.QTextEdit('QTextEdit')
        self.textEditTotalPDFnumber.setReadOnly(True)

        self.listWidgetPDFlist = QtWidgets.QListWidget()

        self.vlayout = QtWidgets.QVBoxLayout()
        self.vlayout.addWidget(self.listWidgetPDFlist)
        self.vlayout.addWidget(self.textEditTotalPDFnumber)

        self.btnAddItems = QtWidgets.QPushButton()
        self.btnAddItems.setText('add items')
        self.vlayout.addWidget(self.btnAddItems)
        self.btnAddItems.clicked.connect(self.addItems)

        self.btnPrintItems = QtWidgets.QPushButton()
        self.btnPrintItems.setText('print the total number of checked items')
        self.vlayout.addWidget(self.btnPrintItems)
        self.btnPrintItems.clicked.connect(self.printItems)

        ### +++++++++++++++++++++++++++++++++++++++++++++++
        self.btnShowSelectedFile = QtWidgets.QPushButton()
        self.btnShowSelectedFile.setText('Show selected file')
        self.vlayout.addWidget(self.btnShowSelectedFile)
        self.btnShowSelectedFile.clicked.connect(self.fileListSelected)        

        self.setLayout(self.vlayout)

    def addItems(self):
        Files = ["file1.txt", "file2.py", "file3.txt",]
        self.textEditTotalPDFnumber.append("\naddItems --> Files {}".format(Files))

        self.ListFilesInViewer(Files)

    def ListFilesInViewer(self, Files):              
        for itemFile in Files:
            item = QtWidgets.QListWidgetItem(itemFile)
            item.setCheckState(QtCore.Qt.Unchecked)  #Unchecked
            item.setText('{}'.format(str(itemFile), str(self.listWidgetPDFlist.count())))
            self.listWidgetPDFlist.addItem(item)  # listWidgetPDFlist

    ### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++        
    def fileListSelected(self):             # Function to select the desired file from the list in the left pane
        """
        ListIterator=range(self.listWidgetPDFlist.count() -1)
        for index in ListIterator:
            p = pathlib.Path(self.fullPath)
            print(" FILE SELECTED this is P==>{}".format(p))
            oneDir = os.path.join(*p.parts[:-2])
            print("FILE SELECTED this is oneDir==>{}".format(oneDir))            
            Item= oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text()
            print("FILE SELECTED this is the cuurent Item =={}".format(Item))            
            print("current row = {}".format(self.listWidgetPDFlist.currentRow()))
            self.mouseHover()
            return Item            
        """
        #p = pathlib.Path(self.fullPath) 
        p = pathlib.Path(os.getcwd())  
        self.textEditTotalPDFnumber.append("\n FILE SELECTED this is   P              =>`{}`".format(p))
        oneDir = os.path.join(*p.parts[:-2])
        self.textEditTotalPDFnumber.append(" FILE SELECTED this is   oneDir      =>`{}`".format(oneDir))   
        self.textEditTotalPDFnumber.append("listWidgetPDFlist.selectedItems     =>`{}`".format(self.listWidgetPDFlist.selectedItems()))
        #Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text()
        if self.listWidgetPDFlist.selectedItems():
            Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[0].text()
            self.textEditTotalPDFnumber.append(" FILE SELECTED this is the cuurent Item =>`<b>{}</b>`\n".format(Item))
            #self.mouseHover()
            #return Item
        else:
            self.textEditTotalPDFnumber.append("<b>!!! NO SELECTED FILE !!!</b>\n")

    def printItems(self):
        checkedItem = 0

        for index in range(self.listWidgetPDFlist.count()):
            if self.listWidgetPDFlist.item(index).checkState() == QtCore.Qt.Checked:
                 checkedItem += 1        

        self.textEditTotalPDFnumber.append("\nchecked items --> {}".format(str(checkedItem)))


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.resize(600, 400)
    window.show()
    sys.exit(app.exec_())

如何获取QlistWidget中存在的文件路径