Qt.TopToolBarArea, self.toolBar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "TXT阅读器"))
MainWindow.setStatusTip(_translate("MainWindow", "TXT阅读器"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
import resource_rc
代码中包含一些累赘的信息,这是因为在QtDesigner中,如果你设置布局后又删除,在ui文件中还会保存这些信息。
找到resource.qrc文件,右键,External Tools->qrtTopy,将resource.qrc文件转换为py文件,可以看到在项目根目录下生成了resource_rc.py文件。
在创建一个main.py文件,调用UIReader.py文件,运行显示主窗口。
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from QtDesigner.UI.UIReader import Ui_MainWindow
class MyMainWindow(QMainWindow, Ui_MainWindow): # 继承 QMainWindow 类和 Ui_MainWindow 界面类
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent) # 初始化父类
self.setupUi(self) # 继承 Ui_MainWindow 界面类
if __name__ == '__main__':
app = QApplication(sys.argv) # 在 QApplication 方法中使用,创建应用程序对象
myWin = MyMainWindow() # 实例化 MyMainWindow 类,创建主窗口
myWin.show() # 在桌面显示控件 myWin
sys.exit(app.exec_()) # 结束进程,退出程序
虽然窗口图标有了,但是最小化图标还没有,在main.py文件添加ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
,发现图标显示出来了。
(2)菜单栏
在菜单栏添加一个文件菜单,建立两个子菜单,打开文件和打开最近的文件,为其添加图标。
注意子菜单栏名称不能直接输入中文,要在右边属性栏里更改。
在打开最近的文件里,再添加子菜单,注意其类从QAction变更为QMenu。
添加了一个子菜单后再删除,其类从QAction变更为了QMenu。
添加设置菜单栏,设置字体和颜色。
设置背景图片。
恢复默认设置。
然后是退出按钮。
因为QMenu类不能绑定动作,所以要建一个子菜单,为其绑定动作,可以添加快捷键,右边找到shortcut,按Ctrl+Q,快捷键设置完成。
右下角,信号和槽,绑定动作。
完成!编译完后运行。
UIReader.py的代码如下:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UIReader.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1280, 720)
MainWindow.setMinimumSize(QtCore.QSize(1280, 720))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icon/reader.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1280, 26))
self.menubar.setObjectName("menubar")
self.files = QtWidgets.QMenu(self.menubar)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(":/icon/files.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.files.setIcon(icon1)
self.files.setObjectName("files")
self.lastfile = QtWidgets.QMenu(self.files)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(":/icon/file_last.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.lastfile