PyQt5是Qt移植到Python上形成的GUI编程框架,自问世以来受到了越来越多的Python程序员的喜爱,因为其具有如下优秀的特征:
- 基于高性能的Qt的GUI控件集。
- 可跨平台运行于Mac OS、Linux、Windows等主流OS上。
- 使用signal/slot也就是信号/槽机制具有类型安全和Qt对象松散耦合的优点。
- 对Qt库完全封装,Qt里有啥,PyQt5里都有。
- 使用Qt designer进行图形界面设计,并可被编译成python代码,GUI设计效率媲美visual studio,远非 tkinter等需要通过纯代码设计并布局控件的GUI设计过程可比。
- 提供了种类繁多的窗口控件,且外观优雅漂亮。
接下来介绍一下PyQt5中如何编程实现菜单。实现菜单步骤很简单:
1、#创建一个菜单栏
menubar = self.menuBar()
2、#添加菜单
fileMenu = menubar.addMenu('&File')
3、#添加事件
fileMenu.addAction(exitAction)
完整代码如下:
import sys
from PyQt5.QtCore import QFileInfo
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication,QFileDialog
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.showWindow()
def showWindow(self):
root = QFileInfo(__file__).absolutePath()
openFileAction=QAction(QIcon(root+'/images/open.png'),'&Oen',self)
openFileAction.setShortcut('Ctrl+O')
openFileAction.setStatusTip('open file')
openFileAction.triggered.connect(self.openFile)
exitAction = QAction(QIcon(root+'/images/exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
self.statusBar()
#创建一个菜单栏
menubar = self.menuBar()
#添加菜单
fileMenu = menubar.addMenu('&File')
#添加事件
fileMenu.addAction(openFileAction)
fileMenu.addAction(exitAction)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('菜单展示')
self.show()
def openFile(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
if fname[0]:
f = open(fname[0], 'r')
with f:
data = f.read()
self.textEdit.setText(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_()) 运行结果截图:
作者:LiPF