PyQt5 制作帮助查看器
帮助文档查看器是很多程序中必备要素,而利用Qt中的QTreeView组件可以很方便的查看文件,而QTextBrowser可以直接显示格式化的MarkDown文本。因此可以利用这两个组件制作一个帮助文件查看器。
本程序的文件结构如下:
.├── main.py└── ui └── docViewer.ui└── docs --这里放帮助文档 ├── a.md ├── b.md └── c.md
如果使用命令
conda install matplotlib
会自动一起安装上pyqt 5.12 和 pyqtchart 5.12
但是qt 5.12 的文字查看器并没有显示Markdown或Html的功能。
需要用命令升级一下
pip install --upgrade pyqt5
运行界面
Python代码
from PyQt5.QtWidgets import QApplication,QWidget,QFileSystemModelfrom PyQt5.uic import loadUifrom PyQt5.QtGui import QFontimport sysimport osclass Doc_Viewer(QWidget): def __init__(self,parent=None) -> None: super().__init__(parent) #加载UI文件 loadUi('./ui/docViewer.ui',self) self.__initUi() def __initUi(self): ''' 初始化运行逻辑 ''' #建立文件模型 self.fileModel = QFileSystemModel() #设置模型根目录 pathIndex=self.fileModel.setRootPath(os.path.abspath("./docs/")) print(self.fileModel.rootPath()) #绑定视图与模型 self.treeView.setModel(self.fileModel) #视图根目录文件模型根目录要一致 self.treeView.setRootIndex(pathIndex) #这里隐藏了文件的信息展示 for i in [1,2,3]: self.treeView.setColumnHidden(i, True) #建立左侧树视图与右侧文本查看器的连接 self.treeView.clicked.connect(self.loadDoc) def loadDoc(self,QpathIndex): ''' 加载文件 ''' filepath= self.fileModel.filePath(QpathIndex) print(f"选择了文件【{filepath}】" ) if os.path.isfile(filepath): # 读取文件内容 markdown=open(filepath,mode="r",encoding="utf-8").read() # 加入到浏览框 self.textBrowser.setMarkdown(markdown) if __name__=="__main__": app = QApplication(sys.argv) app.setFont(QFont("黑体",12)) w = Doc_Viewer() w.show() sys.exit(app.exec())
UI文件
<ui version="4.0"> <class>Form</class> <widget class="QWidget" name="Form"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>857</width> <height>920</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QTreeView" name="treeView"> <property name="sizePolicy"> <sizepolicy hsizetype="Fixed" vsizetype="Expanding"><horstretch>100</horstretch><verstretch>0</verstretch> </sizepolicy> </property> </widget> </item> <item> <widget class="QTextBrowser" name="textBrowser"> <property name="documentTitle"> <string/> </property> <property name="readOnly"> <bool>true</bool> </property> </widget> </item> </layout> </widget> <resources/> <connections/></ui>