【问题标题】:why the Items in QlistWidget keep the focusing on it once the user select one of the Item为什么一旦用户选择了其中一个项目,QlistWidget 中的项目就会一直关注它
【发布时间】:2018-11-28 02:35:39
【问题描述】:

一旦用户选择系统显示其内容的项目之一,我有一个代码会在 QlistWidget 中显示引用文件路径的项目。

问题在于,一旦用户选择了其中一项,它就会将焦点保持在该项上,而用户无法选择其他项。

下图显示两个项目都有焦点,这意味着当我尝试选择第二个项目时,我必须取消选择第一个项目,反之亦然。

如何解决这个问题?

示例:

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

控制台显示结果:

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

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

如果用户选择两次相同的项目,系统会显示此错误:

mouseHover toolTipResult = self.listWidgetPDFlist.setToolTip(Item)

builtins.UnboundLocalError: 之前引用的局部变量 'Item' 作业

代码:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import (QMimeData)
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
                             QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
                             QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QMenu,QListWidgetItem)

#from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import *
import pdfviewer
import pathlib
from pathlib import Path
import os
import re
from os import path
import json,datetime,time
from collections import defaultdict

import docx

import PyPDF2


class pdfViewer(pdfviewer.Ui_PdfPreviewWindow):

    def __init__(self,PdfPreviewObj):
        pdfviewer.Ui_PdfPreviewWindow.__init__(self)

        self.PdfPreviewObj =PdfPreviewObj 
        self.setupUi(PdfPreviewObj)
        self.PdfPreviewObj.show()

        '''
        buttons status at the init of the program
        '''
        self.pushButtonSearch.setEnabled(False)    
        rMyIcon = QtGui.QPixmap("checkBox.ico");
        self.SelectAll.setIcon(QtGui.QIcon(rMyIcon))
        self.SelectAll.setEnabled(False)


        self.pushButtonOpenFolder.clicked.connect(self.openfolder)
        self.ExportButton.clicked.connect(self.openExport)        
        self.pushButtonSearch.clicked.connect(self.FilteredListSearch)
        self.listWidgetPDFlist.clicked.connect(self.MatchFunc)
        self.listWidgetPDFlist.doubleClicked.connect(self.OpenTheSelectedFile)
        #self.NewClearList.clicked.connect(self.NewClearListFN)
        self.SelectAll.clicked.connect(self.selectAllFN)

    def mouseHover(self):
        p = pathlib.Path(self.fullPath) 
        print("MouseHover this is P==>{}".format(p))
        oneDir = os.path.join(*p.parts[:-2])
        print("MouseHover this is oneDir==>{}".format(oneDir))  

        if self.listWidgetPDFlist.selectedItems():
            Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[0].text()
            print("MouseHover this is the cuurent Item =={}".format(Item))   

        self.listWidgetPDFlist.setStyleSheet("""QToolTip { 
                                   background-color: black; 
                                   color: white;                            
                                   border-radius: 10px;
                                   border: black solid 1px;
                                   font: 12px
                                   }""")

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

        toolTipResult = self.listWidgetPDFlist.setToolTip(Item)
        return toolTipResult

    def FileListSelected(self):             # Function to select the desired file from the list in the left pane
        self.mouseHover()
        p = pathlib.Path(self.fullPath) 
        print("this is P==>{}".format(p))
        oneDir = os.path.join(*p.parts[:-2])
        print("this is oneDir==>{}".format(oneDir))  

        if self.listWidgetPDFlist.selectedItems():
            Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[0].text()
            print("this is the cuurent Item =={}".format(Item))   
            return Item

        else:
            print("<b>!!! NO SELECTED FILE !!!</b>\n")

 def checkPath(self,folder):         # Funtion to check the given path for the wanted extension (Files)

        try:
            directory=folder

            whichChecked=""
            for root,dirs,files in os.walk(directory):

                for filename in files:
                    if len(self.lineEdit_Ext.text())>0:
                        self.lineEdit_Ext.setStyleSheet("background-color:white")
                        self.lineEdit_Ext.setPlaceholderText("Enter The Filetype Extention Here")

                        if filename.endswith(self.lineEdit_Ext.text()):
                            fullPath=os.path.join(root,filename)
                            print(fullPath)
                            self.fileList.append(fullPath)

                    elif self.rdBtn_txt.isChecked() and filename.endswith("txt"):
                        fullPath=os.path.join(root,filename)
                        self.fileList.append(fullPath)
                        whichChecked="txt Ext was Selected"


                    elif self.rdBtn_pdf.isChecked() and filename.endswith("pdf"):
                        fullPath=os.path.join(root,filename)
                        self.fileList.append(fullPath)
                        whichChecked="pdf Ext was Selected"
                    elif self.rdBtn_docx.isChecked() and filename.endswith("docx") or filename.endswith("doc") :
                        self.fullPath=os.path.join(root,filename)

                        p = pathlib.Path(self.fullPath)
                        oneDir = os.path.join(*p.parts[-2:])                    
                        self.fileList.append(oneDir)                        
                        #self.fileList.append(self.fullPath)
                        whichChecked="docx - doc Ext was Selected"

                    if len(self.fileList) > 0:
                        self.lineEdit_Ext.setStyleSheet("bacground-color:white;")
                        self.lineEdit_Ext.setPlaceholderText("{0}".format(whichChecked))
                    else:
                        self.lineEdit_Ext.setStyleSheet("background-color:Red")
                        self.lineEdit_Ext.setPlaceholderText("No Ext is Specified")                            


            self.ListFilesInViewer(self.fileList)           # add the list into the  listWidgetPDFlist 
            self.pushButtonSearch.setEnabled(True)
            self.SelectAll.setEnabled(True)

            return folder

        except Exception as e:
            print("this error occure {0}".format(e))

【问题讨论】:

  • 你没有包含你的 pdfviewer ui 文件来使它成为一个可运行的例子,但是从你的选择描述我猜你有 listWidgetPDFlist 设置为你想要 SingleSelection 的 selectionMode MultipleSelection。
  • 是的,你是对的,谢谢。发表您的评论作为为您投票的答案

标签: python path pyqt pyqt5 qlistwidget


【解决方案1】:

我猜您将 listWidgetPDFlist 设置为您想要 SingleSelection 的 selectionMode MultipleSelection。这可以在 Qt Designer 中或通过代码更改,如下例所示。

import sys
from PyQt5 import QtWidgets

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QListWidget()
    for i in range(10):
        w.addItem('Item {}'.format(i))
    # w.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)  # Multiple selection via control key        
    # w.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)  # Multiple selection (click toggle)
    w.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)  # Single selection
    w.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多