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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (306)

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

例子:

  • C:\user\test\Desktop\MicrosoftWord Document.docx=>行0
  • C:\User\test\桌面\test_arabic.docx=>第1行

当尝试打印结果时,系统会显示正确的行号,但显示错误的路径,其中显示你下一步选择的第一个选定的文件路径。

代码:

  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
提问于
用户回答回答于

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

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

  1. 执行add items
  2. Show selected file

试一试:

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

所属标签

可能回答问题的人

  • 嗨喽你好

    7 粉丝480 提问8 回答
  • uncle_light

    5 粉丝518 提问6 回答
  • 人生的旅途

    10 粉丝484 提问6 回答
  • 富有想象力的人

    3 粉丝0 提问6 回答

扫码关注云+社区

领取腾讯云代金券