写在前面
正在用pyqt写我们比赛项目的客户端,针对左侧选项卡,写了一个简单的demo。记录一下。
环境
Python3.5.2
PyQt5
陈述
用的结构是左边一个QListWidget + 右边QStackedWidget,将QWebView加在QStackedWidget上(因为打算用来展示一些charts,用的pyecharts做的数据可视化,生成的html文件,直接嵌入在客户端内,因此用QWebView来显示,关于pyecharts可以看我另外一篇文章https://www.cnblogs.com/jyroy/p/9446486.html)
我用的QSS来进行QListWidget的美化,做成类似网易云音乐的侧边栏的样子,我用的是QSS Editor写的QSS(强烈推荐,好用!!),py代码、QSS代码和效果展示如下
详细注释见代码
py代码如下
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author: jyroy 4 import sys 5 6 from PyQt5.QtCore import QUrl 7 from PyQt5.QtWebKitWidgets import QWebView 8 from PyQt5.QtWidgets import QApplication 9 from PyQt5.QtWidgets import QListWidget,QStackedWidget 10 from PyQt5.QtWidgets import QListWidgetItem 11 from PyQt5.QtWidgets import QWidget 12 from PyQt5.QtWidgets import QHBoxLayout 13 14 from PyQt5.QtCore import QSize, Qt 15 16 17 18 class LeftTabWidget(QWidget): 19 '''左侧选项栏''' 20 def __init__(self): 21 super(LeftTabWidget, self).__init__() 22 self.setObjectName('LeftTabWidget') 23 24 self.setWindowTitle('LeftTabWidget') 25 with open('D:/python/code/qt/test/QSS/QListWidgetQSS.qss', 'r') as f: #导入QListWidget的qss样式 26 self.list_style = f.read() 27 28 self.main_layout = QHBoxLayout(self, spacing=0) #窗口的整体布局 29 self.main_layout.setContentsMargins(0,0,0,0) 30 31 self.left_widget = QListWidget() #左侧选项列表 32 self.left_widget.setStyleSheet(self.list_style) 33 self.main_layout.addWidget(self.left_widget) 34 35 self.right_widget = QStackedWidget() 36 self.main_layout.addWidget(self.right_widget) 37 38 self._setup_ui() 39 40 def _setup_ui(self): 41 '''加载界面ui''' 42 43 self.left_widget.currentRowChanged.connect(self.right_widget.setCurrentIndex) #list和右侧窗口的index对应绑定 44 45 self.left_widget.setFrameShape(QListWidget.NoFrame) #去掉边框 46 47 self.left_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) #隐藏滚动条 48 self.left_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 49 50 list_str = ['岗位需求','专业要求','薪水分布','城市分布'] 51 url_list = ['job_num_wordcloud.html', 'edu_need.html', 'salary_bar.html', 'edu_salary_bar.html'] 52 53 for i in range(4): 54 self.item = QListWidgetItem(list_str[i],self.left_widget) #左侧选项的添加 55 self.item.setSizeHint(QSize(30,60)) 56 self.item.setTextAlignment(Qt.AlignCenter) #居中显示 57 58 self.browser = QWebView() #右侧用QWebView来显示html网页 59 self.browser.setUrl(QUrl.fromLocalFile('D://python//code//vision//%s' % url_list[i])) 60 self.right_widget.addWidget(self.browser) 61 62 63 64 def main(): 65 ''' ''' 66 app = QApplication(sys.argv) 67 68 main_wnd = LeftTabWidget() 69 main_wnd.show() 70 71 app.exec() 72 73 if __name__ == '__main__': 74 main()
QSS代码如下
1 QListWidget, QListView, QTreeWidget, QTreeView { 2 outline: 0px; 3 } 4 5 QListWidget { 6 min-width: 120px; 7 max-width: 120px; 8 color: Black; 9 background: #F5F5F5; 10 } 11 12 QListWidget::Item:selected { 13 background: lightGray; 14 border-left: 5px solid red; 15 } 16 HistoryPanel:hover { 17 background: rgb(52, 52, 52); 18 }
效果展示
写在后面
因为只是写了一个demo,所以没有进行很深入的调整,主要展示侧边栏,大家见谅~
欢迎交流!