文章目录
- 写在前面
- 一、文件(JSON/TXT/PD)查看和打印
-
- [1.1 页面效果](#1.1 页面效果)
- [1.2 项目目录结构](#1.2 项目目录结构)
- 1.3项目源码
-
- [1.3.1 main-app.py](#1.3.1 main-app.py)
- [1.3.2 _03_documentviewer\main.py](#1.3.2 _03_documentviewer\main.py)
- [1.3.3 _03_documentviewer\mainwindow.py](#1.3.3 _03_documentviewer\mainwindow.py)
- [1.3.4 _03_documentviewer\abstractviewer.py](#1.3.4 _03_documentviewer\abstractviewer.py)
- [1.3.5 _03_documentviewer\ui_mainwindow.py](#1.3.5 _03_documentviewer\ui_mainwindow.py)
写在前面
这是一个展示PySide6小例子的系列专题,建议创建单独的虚拟环境演示复现。截止本例,所需依赖如下:
bash
PySide6==6.7.2
PySide6_Addons==6.7.2
PySide6_Essentials==6.7.2
setuptools==72.1.0
shiboken6==6.7.2
wheel==0.43.0
建议复制到 requirements.txt
中,然后按下列步骤进行:
- 下载并安装MiniConda
- 创建虚拟环境
- 激活虚拟环境
- 安装依赖
bash
conda create -n Pyside6-demos python=3.12 -y
conda activate pyside6-demos
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
当然您也可以使用您熟悉的工具和步骤,来实现同样的效果,我只是按个人习惯给您一点建议。
本系列的第一篇文章有比较详细的分解步骤,详见:https://blog.csdn.net/yuetaope/article/details/141051884。
注意:本主题具有连续性,如果您发现本文中的代码因缺少资源跑不起来,请到前面的博文中复制相应的文件。
一、文件(JSON/TXT/PD)查看和打印
1.1 页面效果
1.2 项目目录结构
1.3项目源码
1.3.1 main-app.py
python
import sys
import importlib
from PySide6.QtWidgets import (QMainWindow, QApplication, QGridLayout,
QPushButton, QTabWidget, QVBoxLayout, QWidget)
from utils import apple_like_stylesheet
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 获取屏幕尺寸
self.screen_width = self.screen().size().width()
self.screen_height = self.screen().size().height()
self.W = 800
self.H = 600
self.X = (self.screen_width - self.W) / 2 # 左右居中
self.Y = 50
# 设置窗口标题和大小
self.setWindowTitle('西音东岳工作室 pyside6 Demos')
self.setGeometry(self.X, self.Y, self.W, self.H)
# 加载样式表
self.setStyleSheet(apple_like_stylesheet())
# 设置中心部件
central_widget = QWidget()
self.setCentralWidget(central_widget)
# 布局
self.main_layout = QVBoxLayout(central_widget)
# 添加组件
self.add_widgets_to_main_layout()
def add_widgets_to_main_layout(self):
""" 添加组件到主布局 """
page_tab = self.create_itemview_tabwidget()
self.main_layout.addWidget(page_tab)
def create_itemview_tabwidget(self):
""" 创建Tab标签 """
result = QTabWidget()
# 字典值列表的三个字符串遵循:包(__init__.py) -> py文件 -> app类
self.tab1_btn_dict = {
'常用小部件库': ['_02_widget_gallery', 'widget_gallery', 'WidgetGallery'],
'文件(JSON/TXT/PD)查看和打印': ['_03_documentviewer', 'mainwindow', 'MainWindow'],
}
# 调用函数,创建tab页
tab1 = self.create_tab_items()
# 添加tab页
result.addTab(tab1, " Qt通用 ")
return result
def create_tab_items(self):
""" 创建tab部件 """
tab1_btn_dict = self.tab1_btn_dict
tab_w = QWidget()
# 创建网格布局
pdf_btn_layout = QGridLayout()
# 设置tab部件为网格布局
tab_w.setLayout(pdf_btn_layout)
for i, item in enumerate(tab1_btn_dict):
# 创建按钮,并设置文字
button = QPushButton(item)
# 连接到点击槽函数
button.clicked.connect(self.btn_clicked)
# 每行4个按钮
pdf_btn_layout.addWidget(button, i//4, i % 4)
return tab_w
def btn_clicked(self):
tab1_btn_dict = self.tab1_btn_dict
# 获取点击的父组件
sender = self.sender()
# 从按钮字典中,根据点击按钮的文字获取 模块、包和类
package, module, app_class = tab1_btn_dict[sender.text()]
# 调用函数,执行相应的模块
self.import_and_run_sub_app(package, module, app_class)
def import_and_run_sub_app(self, package, module, app_class):
""" 动态导入模块,实例化app类,达到动态调用的目的 三个参数:包(__init__.py) -> py文件 -> app类 """
# 动态导入模块
module = importlib.import_module(f"{package}.{module}")
# 将导入的模块中的类实例化,并赋值给self.m变量
self.m = getattr(module, app_class)()
# 显示子窗口
self.m.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
1.3.2 _03_documentviewer\main.py
python
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
"""PySide6 port of the Qt Document Viewer demo from Qt v6.x"""
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QCoreApplication
from mainwindow import MainWindow
DESCRIPTION = "A viewer for JSON, PDF and text files"
if __name__ == "__main__":
app = QApplication([])
QCoreApplication.setOrganizationName("QtExamples")
QCoreApplication.setApplicationName("DocumentViewer")
QCoreApplication.setApplicationVersion("1.0")
arg_parser = ArgumentParser(description=DESCRIPTION,
formatter_class=RawTextHelpFormatter)
arg_parser.add_argument("file", type=str, nargs="?",
help="JSON, PDF or text file to open")
args = arg_parser.parse_args()
fileName = args.file
w = MainWindow()
w.show()
if args.file and not w.openFile(args.file):
sys.exit(-1)
sys.exit(app.exec())
1.3.3 _03_documentviewer\mainwindow.py
python
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from PySide6.QtWidgets import (QDialog, QFileDialog, QMainWindow, QMessageBox)
from PySide6.QtCore import (QDir, QFile, QFileInfo, QSettings, Slot)
from _03_documentviewer.ui_mainwindow import Ui_MainWindow
from _03_documentviewer.viewerfactory import ViewerFactory
from _03_documentviewer.recentfiles import RecentFiles
from _03_documentviewer.recentfilemenu import RecentFileMenu
settingsDir = "WorkingDir"
settingsMainWindow = "MainWindow"
settingsViewers = "Viewers"
settingsFiles = "RecentFiles"
ABOUT_TEXT = """A Widgets application to display and print JSON,
text and PDF files. Demonstrates various features to use
in widget applications: Using QSettings, query and save
user preferences, manage file histories and control cursor
behavior when hovering over widgets.
"""
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self._currentDir = QDir()
self._viewer = None
self._recentFiles = RecentFiles()
self.ui.setupUi(self)
self.ui.actionOpen.triggered.connect(self.onActionOpenTriggered)
self.ui.actionAbout.triggered.connect(self.onActionAboutTriggered)
self.ui.actionAboutQt.triggered.connect(self.onActionAboutQtTriggered)
self._recentFiles = RecentFiles(self.ui.actionRecent)
self._recentFiles.countChanged.connect(self._recentFilesCountChanged)
self.readSettings()
self._factory = ViewerFactory(self.ui.viewArea, self)
viewers = ", ".join(self._factory.viewerNames())
self.statusBar().showMessage(f'Available viewers: {viewers}')
menu = RecentFileMenu(self, self._recentFiles)
self.ui.actionRecent.setMenu(menu)
menu.fileOpened.connect(self.openFile)
button = self.ui.mainToolBar.widgetForAction(self.ui.actionRecent)
if button:
self.ui.actionRecent.triggered.connect(button.showMenu)
@Slot(int)
def _recentFilesCountChanged(self, count):
self.ui.actionRecent.setText(f"{count} recent files")
def closeEvent(self, event):
self.saveSettings()
@Slot(int)
def onActionOpenTriggered(self):
fileDialog = QFileDialog(self, "Open Document",
self._currentDir.absolutePath())
while (fileDialog.exec() == QDialog.Accepted
and not self.openFile(fileDialog.selectedFiles()[0])):
pass
@Slot(str)
def openFile(self, fileName):
file = QFile(fileName)
if not file.exists():
nf = QDir.toNativeSeparators(fileName)
self.statusBar().showMessage(f"File {nf} could not be opened")
return False
fileInfo = QFileInfo(file)
self._currentDir = fileInfo.dir()
self._recentFiles.addFile(fileInfo.absoluteFilePath())
# If a viewer is already open, clean it up and save its settings
self.resetViewer()
self._viewer = self._factory.viewer(file)
if not self._viewer:
nf = QDir.toNativeSeparators(fileName)
self.statusBar().showMessage(f"File {nf} can't be opened.")
return False
self.ui.actionPrint.setEnabled(self._viewer.hasContent())
self._viewer.printingEnabledChanged.connect(
self.ui.actionPrint.setEnabled)
self.ui.actionPrint.triggered.connect(self._viewer.print_)
self._viewer.showMessage.connect(self.statusBar().showMessage)
self._viewer.initViewer(self.ui.actionBack, self.ui.actionForward,
self.ui.menuHelp.menuAction(),
self.ui.tabWidget)
self.restoreViewerSettings()
self.ui.scrollArea.setWidget(self._viewer.widget())
return True
@Slot()
def onActionAboutTriggered(self):
viewerNames = ", ".join(self._factory.viewerNames())
mimeTypes = '\n'.join(self._factory.supportedMimeTypes())
text = ABOUT_TEXT
text += f"\nThis version has loaded the following plugins:\n{
viewerNames}\n"
text += f"\n\nIt supports the following mime types:\n{mimeTypes}"
defaultViewer = self._factory.defaultViewer()
if defaultViewer:
n = defaultViewer.viewerName()
text += f"\n\nOther mime types will be displayed with {n}."
QMessageBox.about(self, "About Document Viewer Demo", text)
@Slot()
def onActionAboutQtTriggered(self):
QMessageBox.aboutQt(self)
def readSettings(self):
settings = QSettings()
# Restore working directory
if settings.contains(settingsDir):
self._currentDir = QDir(settings.value(settingsDir))
else:
self._currentDir = QDir.current()
# Restore QMainWindow state
if settings.contains(settingsMainWindow):
mainWindowState = settings.value(settingsMainWindow)
self.restoreState(mainWindowState)
# Restore recent files
self._recentFiles.restoreFromSettings(settings, settingsFiles)
def saveSettings(self):
settings = QSettings()
# Save working directory
settings.setValue(settingsDir, self._currentDir.absolutePath())
# Save QMainWindow state
settings.setValue(settingsMainWindow, self.saveState())
# Save recent files
self._recentFiles.saveSettings(settings, settingsFiles)
settings.sync()
def saveViewerSettings(self):
if not self._viewer:
return
settings = QSettings()
settings.beginGroup(settingsViewers)
settings.setValue(self._viewer.viewerName(), self._viewer.saveState())
settings.endGroup()
settings.sync()
def resetViewer(self):
if not self._viewer:
return
self.saveViewerSettings()
self._viewer.cleanup()
def restoreViewerSettings(self):
if not self._viewer:
return
settings = QSettings()
settings.beginGroup(settingsViewers)
viewerSettings = settings.value(self._viewer.viewerName())
settings.endGroup()
if viewerSettings:
self._viewer.restoreState(viewerSettings)
1.3.4 _03_documentviewer\abstractviewer.py
python
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from PySide6.QtCore import QObject
from PySide6.QtWidgets import (QDialog, QMenu)
from PySide6.QtCore import Signal, Slot
from PySide6.QtPrintSupport import QPrinter, QPrintDialog
MENU_NAME = "qtFileMenu"
class AbstractViewer(QObject):
uiInitialized = Signal()
printingEnabledChanged = Signal(bool)
showMessage = Signal(str, int)
documentLoaded = Signal(str)
def __init__(self):
super().__init__()
self._file = None
self._widget = None
self._menus = []
self._toolBars = []
self._printingEnabled = False
self._actions = []
self._fileMenu = None
def __del__(self):
self.cleanup()
def viewerName(self):
return ""
def saveState(self):
return False
def restoreState(self, state):
return False
def supportedMimeTypes():
return []
def init(self, file, widget, mainWindow):
self._file = file
self._widget = widget
self._uiAssets_mainWindow = mainWindow
def isEmpty(self):
return not self.hasContent()
def isPrintingEnabled(self):
return self._printingEnabled
def hasContent(self):
return False
def supportsOverview(self):
return False
def isModified(self):
return False
def saveDocument(self):
return False
def saveDocumentAs(self):
return False
def actions(self):
return self._actions
def widget(self):
return self._widget
def menus(self):
return self._menus
def mainWindow(self):
return self._uiAssets_mainWindow
def statusBar(self):
return self.mainWindow().statusBar()
def menuBar(self):
return self.mainWindow().menuBar()
def maybeEnablePrinting(self):
self.maybeSetPrintingEnabled(True)
def disablePrinting(self):
self.maybeSetPrintingEnabled(False)
def isDefaultViewer(self):
return False
def viewer(self):
return self
def statusMessage(self, message, type="", timeout=8000):
msg = self.viewerName()
if type:
msg += "/" + type
msg += ": " + message
self.showMessage.emit(msg, timeout)
def addToolBar(self, title):
bar = self.mainWindow().addToolBar(title)
name = title.replace(' ', '')
bar.setObjectName(name)
self._toolBars.append(bar)
return bar
def addMenu(self, title):
menu = QMenu(title, self.menuBar())
menu.setObjectName(title)
self.menuBar().insertMenu(self._uiAssets_help, menu)
self._menus.append(menu)
return menu
def cleanup(self):
# delete all objects created by the viewer which need to be displayed
# and therefore parented on MainWindow
if self._file:
self._file = None
self._menus.clear()
self._toolBars.clear()
def fileMenu(self):
if self._fileMenu:
return self._fileMenu
menus = self.mainWindow().findChildren(QMenu)
for menu in menus:
if menu.objectName() == MENU_NAME:
self._fileMenu = menu
return self._fileMenu
self._fileMenu = self.addMenu("File")
self._fileMenu.setObjectName(MENU_NAME)
return self._fileMenu
@Slot()
def print_(self):
type = "Printing"
if not self.hasContent():
self.statusMessage("No content to print.", type)
return
printer = QPrinter(QPrinter.HighResolution)
dlg = QPrintDialog(printer, self.mainWindow())
dlg.setWindowTitle("Print Document")
if dlg.exec() == QDialog.Accepted:
self.printDocument(printer)
else:
self.statusMessage("Printing canceled!", type)
return
state = printer.printerState()
message = self.viewerName() + " :"
if state == QPrinter.PrinterState.Aborted:
message += "Printing aborted."
elif state == QPrinter.PrinterState.Active:
message += "Printing active."
elif state == QPrinter.PrinterState.Idle:
message += "Printing completed."
elif state == QPrinter.PrinterState.Error:
message += "Printing error."
self.statusMessage(message, type)
def maybeSetPrintingEnabled(self, enabled):
if enabled == self._printingEnabled:
return
self._printingEnabled = enabled
self.printingEnabledChanged.emit(enabled)
def initViewer(self, back, forward, help, tabs):
self._uiAssets_back = back
self._uiAssets_forward = forward
self._uiAssets_help = help
self._uiAssets_tabs = tabs
# Tabs can be populated individually by the viewer, if it
# supports overview
tabs.clear()
tabs.setVisible(self.supportsOverview())
self.uiInitialized.emit()
1.3.5 _03_documentviewer\ui_mainwindow.py
python
# -*- coding: utf-8 -*-
################################################################################
# Form generated from reading UI file 'mainwindow.ui'
##
# Created by: Qt User Interface Compiler version 6.5.3
##
# WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QAction, QBrush, QColor, QConicalGradient,
QCursor, QFont, QFontDatabase, QGradient,
QIcon, QImage, QKeySequence, QLinearGradient,
QPainter, QPalette, QPixmap, QRadialGradient,
QTransform)
from PySide6.QtWidgets import (QApplication, QMainWindow, QMenu, QMenuBar,
QScrollArea, QSizePolicy, QSplitter, QStatusBar,
QTabWidget, QToolBar, QVBoxLayout, QWidget)
import _03_documentviewer.rc_documentviewer
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(983, 602)
icon = QIcon()
icon.addFile(u":/demos/documentviewer/images/qt-logo.png",
QSize(), QIcon.Normal, QIcon.Off)
MainWindow.setWindowIcon(icon)
self.actionOpen = QAction(MainWindow)
self.actionOpen.setObjectName(u"actionOpen")
icon1 = QIcon()
icon1.addFile(u":/demos/documentviewer/images/open.png",
QSize(), QIcon.Normal, QIcon.Off)
self.actionOpen.setIcon(icon1)
self.actionAbout = QAction(MainWindow)
self.actionAbout.setObjectName(u"actionAbout")
icon2 = QIcon()
iconThemeName = u"help-about"
if QIcon.hasThemeIcon(iconThemeName):
icon2 = QIcon.fromTheme(iconThemeName)
else:
icon2.addFile(u":/demos/documentviewer/images/help-about.svgz",
QSize(), QIcon.Normal, QIcon.Off)
self.actionAbout.setIcon(icon2)
self.actionForward = QAction(MainWindow)
self.actionForward.setObjectName(u"actionForward")
icon3 = QIcon()
icon3.addFile(u":/demos/documentviewer/images/go-next.svgz",
QSize(), QIcon.Normal, QIcon.Off)
self.actionForward.setIcon(icon3)
self.actionBack = QAction(MainWindow)
self.actionBack.setObjectName(u"actionBack")
icon4 = QIcon()
icon4.addFile(u":/demos/documentviewer/images/go-previous.svgz",
QSize(), QIcon.Normal, QIcon.Off)
self.actionBack.setIcon(icon4)
self.actionPrint = QAction(MainWindow)
self.actionPrint.setObjectName(u"actionPrint")
self.actionPrint.setEnabled(False)
icon5 = QIcon()
iconThemeName = u"document-print"
if QIcon.hasThemeIcon(iconThemeName):
icon5 = QIcon.fromTheme(iconThemeName)
else:
icon5.addFile(u":/demos/documentviewer/images/print2x.png",
QSize(), QIcon.Normal, QIcon.Off)
self.actionPrint.setIcon(icon5)
self.actionAboutQt = QAction(MainWindow)
self.actionAboutQt.setObjectName(u"actionAboutQt")
icon6 = QIcon()
icon6.addFile(u":/demos/documentviewer/images/qt-logo.png",
QSize(), QIcon.Normal, QIcon.Off)
icon6.addFile(u":/demos/documentviewer/images/qt-logo.png",
QSize(), QIcon.Normal, QIcon.On)
self.actionAboutQt.setIcon(icon6)
self.actionRecent = QAction(MainWindow)
self.actionRecent.setObjectName(u"actionRecent")
icon7 = QIcon()
icon7.addFile(u":/demos/documentviewer/images/document-open-recent.svgz",
QSize(), QIcon.Normal, QIcon.Off)
self.actionRecent.setIcon(icon7)
self.actionQuit = QAction(MainWindow)
self.actionQuit.setObjectName(u"actionQuit")
icon8 = QIcon()
iconThemeName = u"application-exit"
if QIcon.hasThemeIcon(iconThemeName):
icon8 = QIcon.fromTheme(iconThemeName)
else:
icon8.addFile(u".", QSize(), QIcon.Normal, QIcon.Off)
self.actionQuit.setIcon(icon8)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.centralwidget.setEnabled(True)
self.verticalLayout = QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(u"verticalLayout")
self.viewArea = QWidget(self.centralwidget)
self.viewArea.setObjectName(u"viewArea")
self.verticalLayout_2 = QVBoxLayout(self.viewArea)
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.splitter = QSplitter(self.viewArea)
self.splitter.setObjectName(u"splitter")
self.splitter.setOrientation(Qt.Horizontal)
self.tabWidget = QTabWidget(self.splitter)
self.tabWidget.setObjectName(u"tabWidget")
self.tabWidget.setTabPosition(QTabWidget.West)
self.bookmarkTab = QWidget()
self.bookmarkTab.setObjectName(u"bookmarkTab")
self.tabWidget.addTab(self.bookmarkTab, "")
self.pagesTab = QWidget()
self.pagesTab.setObjectName(u"pagesTab")
self.tabWidget.addTab(self.pagesTab, "")
self.splitter.addWidget(self.tabWidget)
self.scrollArea = QScrollArea(self.splitter)
self.scrollArea.setObjectName(u"scrollArea")
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setMinimumSize(QSize(800, 0))
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget()
self.scrollAreaWidgetContents.setObjectName(
u"scrollAreaWidgetContents")
self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 798, 479))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.splitter.addWidget(self.scrollArea)
self.verticalLayout_2.addWidget(self.splitter)
self.verticalLayout.addWidget(self.viewArea)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setObjectName(u"menubar")
self.menubar.setGeometry(QRect(0, 0, 983, 23))
self.qtFileMenu = QMenu(self.menubar)
self.qtFileMenu.setObjectName(u"qtFileMenu")
self.menuHelp = QMenu(self.menubar)
self.menuHelp.setObjectName(u"menuHelp")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
MainWindow.setStatusBar(self.statusbar)
self.mainToolBar = QToolBar(MainWindow)
self.mainToolBar.setObjectName(u"mainToolBar")
MainWindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)
self.menubar.addAction(self.qtFileMenu.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.qtFileMenu.addAction(self.actionOpen)
self.qtFileMenu.addAction(self.actionRecent)
self.qtFileMenu.addAction(self.actionPrint)
self.qtFileMenu.addAction(self.actionQuit)
self.menuHelp.addAction(self.actionAbout)
self.menuHelp.addAction(self.actionAboutQt)
self.mainToolBar.addAction(self.actionOpen)
self.mainToolBar.addAction(self.actionRecent)
self.mainToolBar.addAction(self.actionPrint)
self.mainToolBar.addSeparator()
self.mainToolBar.addAction(self.actionBack)
self.mainToolBar.addAction(self.actionForward)
self.mainToolBar.addSeparator()
self.retranslateUi(MainWindow)
self.actionQuit.triggered.connect(MainWindow.close)
self.tabWidget.setCurrentIndex(0)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate(
"MainWindow", u"文件浏览器", None))
self.actionOpen.setText(
QCoreApplication.translate("MainWindow", u"打开", None))
# if QT_CONFIG(shortcut)
self.actionOpen.setShortcut(
QCoreApplication.translate("MainWindow", u"Ctrl+O", None))
# endif // QT_CONFIG(shortcut)
self.actionAbout.setText(QCoreApplication.translate(
"MainWindow", u"关于文档浏览器", None))
# if QT_CONFIG(tooltip)
self.actionAbout.setToolTip(QCoreApplication.translate(
"MainWindow", u"显示关于文档浏览器的信息.", None))
# endif // QT_CONFIG(tooltip)
# if QT_CONFIG(shortcut)
self.actionAbout.setShortcut(
QCoreApplication.translate("MainWindow", u"Ctrl+H", None))
# endif // QT_CONFIG(shortcut)
self.actionForward.setText(QCoreApplication.translate(
"MainWindow", u"向前", None))
# if QT_CONFIG(tooltip)
self.actionForward.setToolTip(QCoreApplication.translate(
"MainWindow", u"向前一步", None))
# endif // QT_CONFIG(tooltip)
# if QT_CONFIG(shortcut)
self.actionForward.setShortcut(
QCoreApplication.translate("MainWindow", u"Right", None))
# endif // QT_CONFIG(shortcut)
self.actionBack.setText(QCoreApplication.translate(
"MainWindow", u"回退", None))
# if QT_CONFIG(tooltip)
self.actionBack.setToolTip(QCoreApplication.translate(
"MainWindow", u"回退一步", None))
# endif // QT_CONFIG(tooltip)
# if QT_CONFIG(shortcut)
self.actionBack.setShortcut(
QCoreApplication.translate("MainWindow", u"Left", None))
# endif // QT_CONFIG(shortcut)
self.actionPrint.setText(
QCoreApplication.translate("MainWindow", u"打印", None))
# if QT_CONFIG(tooltip)
self.actionPrint.setToolTip(QCoreApplication.translate(
"MainWindow", u"打印当前文件", None))
# endif // QT_CONFIG(tooltip)
# if QT_CONFIG(shortcut)
self.actionPrint.setShortcut(
QCoreApplication.translate("MainWindow", u"Ctrl+P", None))
# endif // QT_CONFIG(shortcut)
self.actionAboutQt.setText(
QCoreApplication.translate("MainWindow", u"关于 Qt", None))
# if QT_CONFIG(tooltip)
self.actionAboutQt.setToolTip(QCoreApplication.translate(
"MainWindow", u"显示QT许可信息", None))
# endif // QT_CONFIG(tooltip)
# if QT_CONFIG(shortcut)
self.actionAboutQt.setShortcut(
QCoreApplication.translate("MainWindow", u"Ctrl+I", None))
# endif // QT_CONFIG(shortcut)
self.actionRecent.setText(QCoreApplication.translate(
"MainWindow", u"最近打开...", None))
# if QT_CONFIG(shortcut)
self.actionRecent.setShortcut(
QCoreApplication.translate("MainWindow", u"Meta+R", None))
# endif // QT_CONFIG(shortcut)
self.actionQuit.setText(
QCoreApplication.translate("MainWindow", u"退出", None))
# if QT_CONFIG(tooltip)
self.actionQuit.setToolTip(QCoreApplication.translate(
"MainWindow", u"Quit the application", None))
# endif // QT_CONFIG(tooltip)
# if QT_CONFIG(shortcut)
self.actionQuit.setShortcut(
QCoreApplication.translate("MainWindow", u"Ctrl+Q", None))
# endif // QT_CONFIG(shortcut)
"""
这段代码的作用是:使用 QTabWidget 的 setTabText 方法,通过 indexOf() 方法找到名为 self.bookmarkTab 的页面的索引,然后调用 QCoreApplication.translate() 方法来获取翻译后的文本(如果没有启用国际化,它将返回原始文本),并将其设置为该页面的选项卡标题。这种用法在 Qt 应用程序中非常常见,特别是在需要本地化应用程序时,可以通过改变翻译文件来支持不同的语言,而不需要修改代码。
"""
self.tabWidget.setTabText(self.tabWidget.indexOf(
self.bookmarkTab), QCoreApplication.translate("MainWindow", u"Pages", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(
self.pagesTab), QCoreApplication.translate("MainWindow", u"Bookmarks", None))
self.qtFileMenu.setTitle(
QCoreApplication.translate("MainWindow", u"文件", None))
self.menuHelp.setTitle(
QCoreApplication.translate("MainWindow", u"帮助", None))
self.mainToolBar.setWindowTitle(
QCoreApplication.translate("MainWindow", u"工具栏", None))
# retranslateUi