简体   繁体   English

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

[英]how to get the file path existing in QlistWidget

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 ==>第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

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 to os.getcwd() . 我不知道self.fullPath是什么,所以我将当前目录的路径设置为os.getcwd()

  1. Execute the add items 执行add items
  2. Show selected file

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_())

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM