37,721
社区成员
发帖
与我相关
我的任务
分享
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
_fromUtf8 = lambda s: s
#修改点 为model.mulu = r'D:\Books'的子目录
#应根据你的文件夹做调整
books = ['Python','eclipse','Antlr', 'UML', 'Java', 'Android',
'unix','Web', 'C++','面向对象', '算法']
class Ui_Dialog(object):
''' UI '''
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(1278, 743)
self.widget = QWidget(Dialog)
self.widget.setGeometry(QRect(4, 16, 1259, 703))
self.widget.setObjectName(_fromUtf8("widget"))
self.horizontalLayout_3 = QHBoxLayout(self.widget)
self.horizontalLayout_3.setMargin(0)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QLabel(self.widget)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.lineEdit = QLineEdit(self.widget)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.horizontalLayout.addWidget(self.lineEdit)
self.verticalLayout.addLayout(self.horizontalLayout)
self.listWidget = QListWidget(self.widget)
self.listWidget.setObjectName(_fromUtf8("listWidget"))
self.verticalLayout.addWidget(self.listWidget)
self.horizontalLayout_3.addLayout(self.verticalLayout)
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_2 = QLabel(self.widget)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_2.addWidget(self.label_2)
self.comboBox = QComboBox(self.widget)
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.comboBox.setMinimumSize(QSize(221, 16))
global books
for book in books :
self.comboBox.addItem(book)
self.horizontalLayout_2.addWidget(self.comboBox)
spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.textBrowser = QTreeWidget(self.widget)
self.textBrowser.setFont(QFont("Times", 12))
self.textBrowser.setMinimumSize(QSize(891, 703))
self.textBrowser.setMaximumSize(QSize(891, 703))
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
#self.highlighter = PythonHighlighter(self.textBrowser.document())
self.verticalLayout_2.addWidget(self.textBrowser)
self.horizontalLayout_3.addLayout(self.verticalLayout_2)
self.retranslateUi(Dialog)
QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QApplication.translate("Dialog", "Dialog", None, QApplication.UnicodeUTF8))
self.label.setText(QApplication.translate("Dialog", "<html><head/><body><p>Search</p></body></html>", None, QApplication.UnicodeUTF8))
self.label_2.setText(QApplication.translate("Dialog", "Books ", None, QApplication.UnicodeUTF8))
文件开始:model.py
import os ;import re
import sys
from PDFNetPython3 import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
#修改点
mulu = r'D:\Books' #一个目录 他的子目录内有pdf文件
class xml_content:
#修改点 python是一个子目录的名称
def __init__(self ,source = r'Python'):
'''
初始化自己的一些东西
'''
PDFNet.Initialize()
self.source = source # 首先打开的目录
self.pdfdir = {} # 名称 --> 路径
self.pdfcontent ={} # 路径 --> 内容(用于关键字的搜索)
self.pdftree_item ={} # 路径 --> tree_item(用于更新view)
self.find_pdf()
#得到所有的数据
def get_dir(self):
return self.pdfdir
def get_content(self):
return self.pdfcontent
def set_path(self, source): #重新搜索新的路径
''' 重新搜索子文件夹 '''
self.source = source
self.pdfdir = {}
self.find_pdf()
#1.2.0 得到书签
def get_book_mark(self ,FirstBookmark):
content = []
while FirstBookmark.IsValid():
indent = FirstBookmark.GetIndent() - 1
a = ' ' * indent
content.append(a + FirstBookmark.GetTitle())
if FirstBookmark.HasChildren():
content.extend(self.get_book_mark(FirstBookmark.GetFirstChild()))
FirstBookmark = FirstBookmark.GetNext()
return content
#1.2 寻找pdf内的书签
def find_in_pdf(self ,searched):
'''得到所有的pdf书签 并保存到pdfcontent中'''
self.searched = searched
if(not searched):
return list(self.pdfdir.keys())
finded = []
for file in self.pdfdir.keys(): #在所有的文件之中遍历
file_path = self.pdfdir[file]
if(not self.pdfcontent.__contains__(file_path)):
doc = PDFDoc(file_path) #先确定所有的content是存在的
doc.InitSecurityHandler()
root = doc.GetFirstBookmark()
content = self.get_book_mark(root )
joined = '\n'.join(content)
self.pdfcontent[file_path] = joined
doc.Close()
for file in self.pdfdir.keys(): #在所有的文件之中遍历
content = self.pdfcontent[self.pdfdir[file]]
if(re.search(self.searched,content)):
finded.append(file)
return finded
#1. 在指定的目录中找到所有的pdf文件
def find_pdf(self):
global mulu
lists = os.listdir(mulu+'\\'+self.source)
for file in lists:
full_path = mulu+'\\'+self.source+'\\'+file
if(not os.path.isdir(full_path) and full_path.endswith('.pdf')):
self.pdfdir[file.replace('.pdf','')] = full_path
#3.1 添加到widget item是书签的item parent是Wight或是treeItem
def add_to_widget (self, item , treeWight):
item_list = []
while item.IsValid():
cur_item = QTreeWidgetItem(treeWight) #建立widgt的顶层目录
cur_item.setText(0,item.GetTitle()) #设置显示的名字
cur_item.setData(2,Qt.UserRole,item) #底层数据column 2
#书签除了goto还能够是什么呢?
action = item.GetAction()
if action.IsValid():
if action.GetType() == Action.e_GoTo:
dest = action.GetDest()
if dest.IsValid():
page = dest.GetPage()
position = str(page.GetIndex())
cur_item.setData(1,Qt.UserRole,position) #设置跳转的页数 column 0
else:
cur_item.setData(1,Qt.UserRole,None) #设置跳转的页数 为空
item = item.GetNext()
item_list.append(cur_item)
#广度优先的算法 先计算所有的子元素,再计算子元素的子元素
for tree_item in item_list:
if tree_item.data(2,Qt.UserRole).HasChildren():
self.add_to_widget(tree_item.data(2,Qt.UserRole).GetFirstChild(),tree_item)
if(type(treeWight) is QTreeWidget):
treeWight.insertTopLevelItems(0,item_list)
return item_list
else:
treeWight.addChildren(item_list)
#3. 只显示当前这本书的书签
def set_viewer(self,book,item_widgt):
'''
先隐藏掉在treeview中的所有
然后查看是否有已经初始化的treeItem
没有则初始化之
显示即可
'''
n = item_widgt.topLevelItemCount()
for i in range(n):
item_widgt.topLevelItem(i).setHidden(True)
if(book in self.pdftree_item.keys()):
for item in self.pdftree_item[book]:
item.setHidden(False)
else:
doc = PDFDoc(book)
doc.InitSecurityHandler()
root = doc.GetFirstBookmark() #得到第一个书签
bookMarks = self.add_to_widget(root,item_widgt) #添加所有的书签
self.pdftree_item[book] = bookMarks
doc.Close()
if __name__ == '__main__':
test = xml_content()
print(test.get_dir())
文件结束:model.py
文件开始:main.py
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import dia ; import model ;import sys
import os ; import re
#修改点 用于打开pdf的程序 要能够接受 -n 参数
pdf_exe = r'C:\cygwin\bin\pdf.exe '
class myDia(QDialog,dia.Ui_Dialog):
def __init__(self ):
super(myDia,self).__init__()
self.setupUi(self)
self.search_generator = None
self.item_list=[]
self.init_list() #1. 创建列表
#1. 创建列表
def init_list(self):
self.model = model.xml_content()
mhash = self.model.get_dir()
for aa in mhash.keys():
item = QListWidgetItem(aa)
item.setData(1,mhash[aa])
self.item_list.append(item) #保存所有的item
self.listWidget.addItem(item)
self.add_action() #1.0 给list添加弹出菜单
self.zip_comments = self.model.get_content()
print('initOk')
#1.0 添加弹出菜单
def add_action(self):
self.listWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
self.textBrowser.setContextMenuPolicy(Qt.ActionsContextMenu)
#1.0.0私有方法 创建Action
run_action = self.createAction("Open pdf",slot = self.open_pdf_file)
self.listWidget.addAction(run_action)
dir_action = self.createAction("Open Dir",slot = self.dir_script)
self.listWidget.addAction(dir_action)
bookmark_action = self.createAction("open Book Mark",slot = self.open_bookmark)
self.textBrowser.addAction(bookmark_action)
#1.0.0私有方法 创建Action
def createAction(self, text, slot=None, shortcut=None, icon=None,tip=None, checkable=False, signal="triggered()"):
action = QAction(text, self)
if icon is not None:
action.setIcon(QIcon("/%s.png" % icon))
if shortcut is not None:
action.setShortcut(shortcut)
if tip is not None:
action.setToolTip(tip)
action.setStatusTip(tip)
if slot is not None:
self.connect(action, SIGNAL(signal), slot)
if checkable:
action.setCheckable(True)
return action
#2.0 Action : 用系统文件打开它就可以了
def open_pdf_file(self):
global pdf_exe
cur_itm = self.listWidget.currentItem()
print('the cur item is',cur_itm.data(1))
path = cur_itm.data(1)
os.system(pdf_exe+path)
#2.0 Action : 打开所在目录
def dir_script(self):
cur_itm = self.listWidget.currentItem()
print('the cur item is',cur_itm.data(1))
path = cur_itm.data(1)
filename = re.search(r'(\\[^\\]*?\.pdf)',path).group(1)
path = path.replace(filename,'')
os.system(r'explorer '+path)
#打开书签
def open_bookmark(self):
global pdf_exe
cur_itm = self.listWidget.currentItem()
print('the cur item is',cur_itm.data(1))
path = cur_itm.data(1)
items = self.textBrowser.selectedItems()
if(not items):
return
else :
item = items[0]
position = str(item.data(1,Qt.UserRole))
print('position',position)
if(position):
print('go to bookmark ',position)
print(pdf_exe+'"'+path+'"'+' -n '+position)
os.system(pdf_exe+'"'+path+'"'+' -n '+position)
else:
os.system(pdf_exe+path)
pass
#3.0 event : 根据item的改变而变换信息
@pyqtSignature("QListWidgetItem *,QListWidgetItem *")
def on_listWidget_currentItemChanged(self,item_new,item_old):
if(item_new is None):
return
print('the item change',item_new.data(1))
self.model.set_viewer(item_new.data(1),self.textBrowser)
self.on_lineEdit_textChanged(self.lineEdit.text()) #同时也将搜索清空
#3.0 event : comboBox的值变化了
@pyqtSignature("QString")
def on_comboBox_currentIndexChanged(self ,string):
print('the item change',string)
self.model.set_path(string)
mhash = self.model.get_dir()
self.listWidget.clear()
self.item_list = []
for aa in mhash.keys():
item = QListWidgetItem(aa)
item.setData(1,mhash[aa])
self.item_list.append(item) #保存所有的item
self.listWidget.addItem(item)
#双击 其实就是open_pdf_file
@pyqtSignature("QListWidgetItem *")
def on_listWidget_itemDoubleClicked(self,item_new):
#print('the item double clicked',item_new.data(1))
self.open_pdf_file()
#过滤器
@pyqtSignature("")
def on_lineEdit_returnPressed(self):
text = self.lineEdit.text()
search_keys = self.model.find_in_pdf(text)
finded_item = []
for item in self.item_list:
item.setHidden(True)
full_path = item.text()
if(full_path in search_keys):
finded_item.append(item)
if(finded_item):
for item in finded_item:
item.setHidden(False)
self.listWidget.setItemSelected(finded_item[0],True)
self.on_listWidget_currentItemChanged(finded_item[0],None)
#设置要搜索的东西
@pyqtSignature("QString")
def on_lineEdit_textChanged(self ,text):
#print('text chaned ',text)
self.searched = text
self.search_generator = None
#双击事件
@pyqtSignature("QTreeWidgetItem *,int")
def on_textBrowser_itemDoubleClicked(self ,item,index):
#print('on_textBrowser_itemDoubleClicked',item,index)
self.open_bookmark()
#处理F3
def event(self, event):
if (event.type() == QEvent.KeyPress and
event.key() == Qt.Key_F3):
self.search() #Action 搜索 (F3)
self.textBrowser.setFocus()
return True
return QDialog.event(self, event)
#Action 搜索 (F3) main
def search(self):
self.textBrowser.childCount = self.textBrowser.topLevelItemCount
self.textBrowser.child = self.textBrowser.topLevelItem
self.__searched=[]
if(not self.search_generator):
self.search_item(self.textBrowser)
self.search_generator = self.search_in()
try:
item = self.search_generator.__next__()
#print('yousearched item ',item.text(0))
self.textBrowser.scrollToItem(item)
self.textBrowser.setItemSelected(item,True)
except StopIteration:
self.search_generator = None
#Action 搜索 遍历所有的元素 为yield做准备
def search_item(self, parentitem):
top_count = parentitem.childCount()
for top in range(0,top_count):
item = parentitem.child(top)
if(re.search(self.searched,item.text(0),flags = 2)):
self.__searched.append(item)
if(item.childCount()>0): #添加所有的书签
self.search_item(item)
#Action 搜索 用yield得到已经搜索的
def search_in(self,):
for item in self.__searched:
yield item
def main(arg = None):
app = QApplication(sys.argv)
form = myDia()
form.show()
app.exec_()
if __name__ == "__main__":
main()
文件结束:main.py