Skip to main content
 Web开发网 » 编程语言 » Python语言

Python快速入门系列:PyQt5 快速开发应用程序实战

2021年11月25日7480百度已收录

这一次介绍用Python结合PyQt5桌面开发一款属于自己的应用程序,直接上代码,如下:

#!/usr/bin/env python

from PyQt5.QtCore import (QFile, QFileInfo, QPoint, QRect, QSettings, QSize,

Qt, QTextStream)

from PyQt5.QtGui import QIcon, QKeySequence

from PyQt5.QtWidgets import (QAction, QApplication, QFileDialog, QMainWindow,

QMessageBox, QTextEdit)

class MainWindow(QMainWindow):

def __init__(self):

super(MainWindow, self).__init__()

self.curFile = ''

self.textEdit = QTextEdit()

self.setCentralWidget(self.textEdit)

self.createActions()

self.createMenus()

self.createToolBars()

self.createStatusBar()

self.readSettings()

self.textEdit.document().contentsChanged.connect(self.documentWasModified)

self.setCurrentFile('')

# 关闭事件

def closeEvent(self, event):

if self.maybeSave():

self.writeSettings()

event.accept()

else:

event.ignore()

# 新建文件事件

def newFile(self):

if self.maybeSave():

self.textEdit.clear()

self.setCurrentFile('')

# 打开文件事件

def open(self):

if self.maybeSave():

fileName, _ = QFileDialog.getOpenFileName(self)

if fileName:

self.loadFile(fileName)

# 保存事件

def save(self):

if self.curFile:

return self.saveFile(self.curFile)

return self.saveAs()

# 另存事件

def saveAs(self):

fileName, _ = QFileDialog.getSaveFileName(self)

if fileName:

return self.saveFile(fileName)

return False

# 关于我们事件

def about(self):

QMessageBox.about(self, "关于PY程序猿",

"<b>PY程序猿</b> 是一个爱设计更爱代码的程序猿。 ")

def documentWasModified(self):

self.setWindowModified(self.textEdit.document().isModified())

# 创建动作

def createActions(self):

root = QFileInfo(__file__).absolutePath()

self.newAct = QAction(QIcon(root + '/images/new.png'), "&新建", self,

shortcut=QKeySequence.New, statusTip="新建一个文件",

triggered=self.newFile)

self.openAct = QAction(QIcon(root + '/images/open.png'), "&打开...",

self, shortcut=QKeySequence.Open,

statusTip="打开一个文件", triggered=self.open)

self.saveAct = QAction(QIcon(root + '/images/save.png'), "&保存", self,

shortcut=QKeySequence.Save,

statusTip="保存一个文件", triggered=self.save)

self.saveAsAct = QAction("另&存...", self,

shortcut=QKeySequence.SaveAs,

statusTip="另存一个新的文件",

triggered=self.saveAs)

self.exitAct = QAction("退出", self, shortcut="Ctrl+Q",

statusTip="退出", triggered=self.close)

self.cutAct = QAction(QIcon(root + '/images/cut.png'), "剪切", self,

shortcut=QKeySequence.Cut,

statusTip="剪切当前选择内容到剪贴板",

triggered=self.textEdit.cut)

self.copyAct = QAction(QIcon(root + '/images/copy.png'), "复制", self,

shortcut=QKeySequence.Copy,

statusTip="复制当前选择内容到剪贴板",

triggered=self.textEdit.copy)

self.pasteAct = QAction(QIcon(root + '/images/paste.png'), "粘贴",

self, shortcut=QKeySequence.Paste,

statusTip="从剪贴板粘贴内容到当前位置",

triggered=self.textEdit.paste)

self.aboutAct = QAction("&关于", self,

statusTip="显示作者信息",

triggered=self.about)

self.cutAct.setEnabled(False)

self.copyAct.setEnabled(False)

self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)

self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)

# 创建菜单

def createMenus(self):

self.fileMenu = self.menuBar().addMenu("文件")

self.fileMenu.addAction(self.newAct)

self.fileMenu.addAction(self.openAct)

self.fileMenu.addAction(self.saveAct)

self.fileMenu.addAction(self.saveAsAct)

self.fileMenu.addSeparator();

self.fileMenu.addAction(self.exitAct)

self.editMenu = self.menuBar().addMenu("编辑")

self.editMenu.addAction(self.cutAct)

self.editMenu.addAction(self.copyAct)

self.editMenu.addAction(self.pasteAct)

self.menuBar().addSeparator()

self.helpMenu = self.menuBar().addMenu("帮助")

self.helpMenu.addAction(self.aboutAct)

# 创建工具栏

def createToolBars(self):

self.fileToolBar = self.addToolBar("File")

self.fileToolBar.addAction(self.newAct)

self.fileToolBar.addAction(self.openAct)

self.fileToolBar.addAction(self.saveAct)

self.editToolBar = self.addToolBar("Edit")

self.editToolBar.addAction(self.cutAct)

self.editToolBar.addAction(self.copyAct)

self.editToolBar.addAction(self.pasteAct)

# 创建状态栏

def createStatusBar(self):

self.statusBar().showMessage("已准备好!")

def readSettings(self):

settings = QSettings("Trolltech", "Application Example")

pos = settings.value("pos", QPoint(200, 200))

size = settings.value("size", QSize(400, 400))

self.resize(size)

self.move(pos)

def writeSettings(self):

settings = QSettings("Trolltech", "Application Example")

settings.setValue("pos", self.pos())

settings.setValue("size", self.size())

def maybeSave(self):

if self.textEdit.document().isModified():

ret = QMessageBox.warning(self, "Application",

"The document has been modified.\nDo you want to save "

"your changes?",

QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

if ret == QMessageBox.Save:

return self.save()

if ret == QMessageBox.Cancel:

return False

return True

def loadFile(self, fileName):

file = QFile(fileName)

if not file.open(QFile.ReadOnly | QFile.Text):

QMessageBox.warning(self, "Application",

"Cannot read file %s:\n%s." % (fileName, file.errorString()))

return

inf = QTextStream(file)

QApplication.setOverrideCursor(Qt.WaitCursor)

self.textEdit.setPlainText(inf.readAll())

QApplication.restoreOverrideCursor()

self.setCurrentFile(fileName)

self.statusBar().showMessage("File loaded", 2000)

def saveFile(self, fileName):

file = QFile(fileName)

if not file.open(QFile.WriteOnly | QFile.Text):

QMessageBox.warning(self, "Application",

"Cannot write file %s:\n%s." % (fileName, file.errorString()))

return False

outf = QTextStream(file)

QApplication.setOverrideCursor(Qt.WaitCursor)

outf << self.textEdit.toPlainText()

QApplication.restoreOverrideCursor()

self.setCurrentFile(fileName);

self.statusBar().showMessage("File saved", 2000)

return True

def setCurrentFile(self, fileName):

self.curFile = fileName

self.textEdit.document().setModified(False)

self.setWindowModified(False)

if self.curFile:

shownName = self.strippedName(self.curFile)

else:

shownName = 'untitled.txt'

self.setWindowTitle("%s[*] - Application" % shownName)

def strippedName(self, fullFileName):

return QFileInfo(fullFileName).fileName()

if __name__ == '__main__':

import sys

app = QApplication(sys.argv)

mainWin = MainWindow()

mainWin.show()

sys.exit(app.exec_())

效果如图:

Python快速入门系列:PyQt5 快速开发应用程序实战  Python应用开发 第1张

评论列表暂无评论
发表评论
微信