当用户将鼠标悬停在qlistWidget内的项目上以显示工具提示时,如何使用鼠标悬停事件。
我能够显示工具提示选择currentItem,现在我所选择的只是选择而只是悬停。
下面的代码显示了创建GUI界面的python脚本,其中用户选择路径并且系统读取其内容以便在比较用户输入和文本内容之后找到匹配的表达式。
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QMenu)
#from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import *
import pdfviewer
import os,pathlib
from pathlib import Path
import re
import json,datetime,time
from collections import defaultdict
import docx
import PyPDF2
class pdfViewer(QtWidgets.QMainWindow,pdfviewer.Ui_PdfPreviewWindow):
def __init__(self,PdfPreviewObj):
pdfviewer.Ui_PdfPreviewWindow.__init__(self)
self.PdfPreviewObj =PdfPreviewObj
self.setupUi(PdfPreviewObj)
self.PdfPreviewObj.show()
self.pushButtonSearch.setEnabled(False)
self.pushButtonOpenFolder.clicked.connect(self.setExistingDirectory)
self.pushButtonSearch.clicked.connect(self.FilteredListSearch)
self.listWidgetPDFlist.clicked.connect(self.MatchFunc)
#self.listWidgetPDFlist.doubleClicked.connect(self.OpenFileDirectory)
self.listWidgetPDFlist.doubleClicked.connect(self.OpenTheSelectedFile)
#self.listWidgetPDFlist.enterEvent()
self.hoverItem = None
self.listWidgetPDFlist.viewport().setMouseTracking(True)
self.listWidgetPDFlist.viewport().installEventFilter(self)
#####################################
#added
def eventFilter(self, obj, event):
if self.listWidgetPDFlist.viewport() == obj and event.type() == QtCore.QEvent.MouseMove:
it = self.listWidgetPDFlist.itemAt(event.pos())
if self.hoverItem != it:
message = it.text("test tooltip") # <--- place the message here
QtWidgets.QToolTip.showText(QtGui.QCursor.pos(),
message,
self.listWidgetPDFlist.viewport(),
self.listWidgetPDFlist.visualItemRect(it))
self.hoverItem = it
return QtWidgets.QMainWindow.eventFilter(self, obj, event)
#def enterEvent(self,QEvent):
## here the code for mouse hover
#Item=self.listWidgetPDFlist.currentItem().text()
#parentFile =Path().resolve().parent
#selectedFile = os.path.join(parentFile,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()))
##{
##color: #ffffff;
##background-color: #2a82da;
##border: 1px solid white;
##}
#toolTipResult = self.listWidgetPDFlist.setToolTip(selectedFile)
#return toolTipResult
def FileListSelected(self): # Function to select the desired file from the list in the left pane
Item=self.listWidgetPDFlist.currentItem().text()
parentFile =Path().resolve().parent
selectedFile = os.path.join(parentFile,Item)
return selectedFile
def ReadingFileContent(self,Item): # Function to read the file content
if self.lineEdit_Ext.text()=='pdf'or self.rdBtn_pdf.isChecked():
try:
with open(Item,'rb')as fw:
read_pdf = PyPDF2.PdfFileReader(fw)
PDF_of_pages = read_pdf.pages
fullText = []
for page in (PDF_of_pages):
fullText.append(page.extractText())
self.textString= ' <br/> '.join(fullText)
except:
self.textEdit_PDFpreview.insertHtml('File Not Found')
pass
elif (self.lineEdit_Ext.text()=='docx' or self.lineEdit_Ext.text()=='doc' or self.rdBtn_docx.isChecked()):
try:
Doc = docx.Document(Item)
fullText = []
for para in Doc.paragraphs:
fullText.append(para.text)
self.textString= ' <br/> '.join(fullText)
except:
self.textEdit_PDFpreview.insertHtml('File Not Found')
pass
else:
try:
with open(Item) as fw:
self.textString=fw.read()
except:
self.textEdit_PDFpreview.insertHtml('No Match Found')
pass
return self.textString
def MatchFunc(self): # Function to highlight the found criteria and display it in the right pane
self.textEdit_PDFpreview.clear()
x = self.lineEditSearch.text().strip()
TextString=self.ReadingFileContent(self.FileListSelected())
if ' ' in x:
y=list(x.split(sep=" "))
for z in y:
RepX='<u><b style="color:#FF0000">'+z+'</b></u>'
self.textEdit_PDFpreview.clear()
if z in TextString:
TextString=self.HighLight(z,TextString,RepX)
else:
RepX='<u><b style="color:#FF0000">'+x+'</b></u>'
##added
self.textEdit_PDFpreview.clear()
if x in TextString:
self.HighLight(x,TextString,RepX)
def HighLight(self,x,TextString,RepX):
thematch=TextString.replace(x,RepX)
TheCount=TextString.count(x)
self.textEdit_PDFpreview.insertHtml(str(thematch))
return thematch
def setExistingDirectory(self):
self.listWidgetPDFlist.clear()
self.fileList=[]
dialog = QDialog()
options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
Folder = QFileDialog.getExistingDirectory(dialog, "Open Folder" ,options=options)
self.checkPath(Folder)
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()):
self.fullPath=os.path.join(root,filename)
print(self.fullPath)
self.fileList.append(self.fullPath)
elif self.rdBtn_txt.isChecked() and filename.endswith("txt"):
self.fullPath=os.path.join(root,filename)
self.fileList.append(self.fullPath)
whichChecked="txt Ext was Selected"
print(fullPath)
elif self.rdBtn_pdf.isChecked() and filename.endswith("pdf"):
self.fullPath=os.path.join(root,filename)
self.fileList.append(self.fullPath)
whichChecked="pdf Ext was Selected"
print(self.fullPath)
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)
whichChecked="docx - doc Ext was Selected"
print(self.fullPath)
print(oneDir)
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)
return folder
except Exception as e:
print("this error occure {0}".format(e))
def FilteredListSearch(self): # Function to filter the list of files to the one that contains the criteria
FilteredList=[]
for Item in self.fileList:
user_input=self.lineEditSearch.text().strip()
print(user_input)
textString=self.ReadingFileContent(Item)
StrList=list(textString.splitlines())
print("str list {}".format(StrList))
#added
if ' ' in user_input:
SearchList=list(user_input.split(sep=" "))
if '' in SearchList:
SearchList.remove(" ")
CommonList=list(set(SearchList) & set(StrList))
if len(CommonList)==len(SearchList): # All the words in the list
FilteredList.append(Item)
if len(CommonList)>1: # Any word of the list
pass
else:
if user_input in textString:
FilteredList.append(Item)
self.ListFilesInViewer(FilteredList)
def ListFilesInViewer(self,Files): # Function to list all the files in the Left pane
self.listWidgetPDFlist.addItems(Files)
self.lineEditTotalPDFnumber.setText(str(self.listWidgetPDFlist.count())) #Set the total number of existing PDF files in the requested path
def OpenTheSelectedFile(self): # Function to open the selected file
os.startfile(self.FileListSelected())
def OpenFileDirectory(self):
MyDir=os.path.dirname(self.FileListSelected())
os.startfile(MyDir)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
PdfPreviewWindow = QtWidgets.QMainWindow()
pdfViewerUi = pdfViewer(PdfPreviewWindow)
PdfPreviewWindow.show()
sys.exit(app.exec_())
注意:
我删除了 pdfviewer.py 类,因为我达到了正文中允许的最大字符数。