pyrcc5将resources.qrc转换成py文件
来源:互联网 发布:win7麦克风加强软件 编辑:程序博客网 时间:2024/05/15 01:01
pyrcc5 -o resources_rc.py resources.qrc
用python3+PyQt5改写Python Qt GUI快速编程的第6章实例主窗口
本文是对Python Qt GUI快速编程的第6章的例子MainWindow改写成python3+PyQt5的编码。改动中,本人发现了不少的坑要改动,下文大概列出一些需要更改的重点,并且附上改动后的代码,代码在Python3.5+PyQt5.7的环境下运行并测试正常。请大家参考学习。
此实例有以下程序:
/home/yrd/eric_workspace/charter6/Ui_newimagedlg.py
/home/yrd/eric_workspace/charter6/newimagedlg.py
/home/yrd/eric_workspace/charter6/helpform.py
/home/yrd/eric_workspace/charter6/resizedlg.py
/home/yrd/eric_workspace/charter6/mainwindow.py
资源文件:
/home/yrd/eric_workspace/charter6/resources.qrc
/home/yrd/eric_workspace/charter6/images
/home/yrd/eric_workspace/charter6/help
可在网路上寻找作者这本书的的代码资源获得资源文件。
重点内容:
1,因为settings.value(“RecentFiles”)本身就是list类型,故
self.recentFiles = settings.value(“RecentFiles”).toStringList()
改动为
self.recentFiles=settings.value(“RecentFiles”)
2,类型转换问题
self.restoreGeometry( settings.value("MainWindow/Geometry").toByteArray())self.restoreState(settings.value("MainWindow/State").toByteArray())
- 1
- 2
- 3
改动为
self.restoreGeometry( QByteArray(settings.value("MainWindow/Geometry")))self.restoreState(QByteArray(settings.value("MainWindow/State")))
- 1
- 2
- 3
3,引入库的问题,有很多,只列一个例子:
from PyQt5.QtPrintSupport import QPrinter,QPrintDialog
4,实例中的坑,QFileDialog.getSaveFileName和QFileDialog.getOpenFileName所返回的结果是一个tupple。第一为文件名,第二个为文件类型。
fname,tpye = QFileDialog.getSaveFileName(self, "Image Changer - Save Image", fname, "Image files ({0})".format(" ".join(formats)))fname,tpye = QFileDialog.getOpenFileName(self, "Image Changer - Choose Image", dir, "Image files ({0})".format(" ".join(formats)))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
5,PyQt5开发中应该以python的字符串类型取代Qstring类型。self.recentFiles是list类型,故用append或insert而非prepend。
def addRecentFile(self, fname): if fname is None: return if not self.recentFiles.contains(fname): self.recentFiles.prepend(QString(fname)) while self.recentFiles.count() > 9: self.recentFiles.takeLast()改成 def addRecentFile(self, fname): if fname is None: return if fname not in self.recentFiles: self.recentFiles.insert(0,fname) while len(self.recentFiles) > 9: self.recentFiles.pop()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
6,信号槽的问题,现举个例子:
self.connect(action, SIGNAL(“triggered()”),self.loadFile)
改成
action.triggered[bool].connect(self.loadFile)
槽self.loadFile根据实际情况也做了些变动。
需要通过pyrcc5将resources.qrc转换成py文件,并在主程序引入。
pyrcc5 -o resources_rc.py resources.qrc
/home/yrd/eric_workspace/charter6/resources.qrc
<!DOCTYPE RCC><RCC version="1.0"><qresource><file alias="filenew.png">images/filenew.png</file><file alias="fileopen.png">images/fileopen.png</file><file alias="filesave.png">images/filesave.png</file><file alias="filesaveas.png">images/filesaveas.png</file><file alias="fileprint.png">images/fileprint.png</file><file alias="filequit.png">images/filequit.png</file><file alias="editinvert.png">images/editinvert.png</file><file alias="editswap.png">images/editswap.png</file><file alias="editzoom.png">images/editzoom.png</file><file alias="editmirror.png">images/editmirror.png</file><file alias="editunmirror.png">images/editunmirror.png</file><file alias="editmirrorhoriz.png">images/editmirrorhoriz.png</file><file alias="editmirrorvert.png">images/editmirrorvert.png</file><file alias="back.png">images/back.png</file><file alias="home.png">images/home.png</file><file alias="icon.png">images/icon.png</file><file>help/editmenu.html</file><file>help/filemenu.html</file><file>help/index.html</file></qresource></RCC>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
/home/yrd/eric_workspace/charter6/Ui_newimagedlg.py
# -*- coding: utf-8 -*-from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_NewImageDlg(object): def setupUi(self, NewImageDlg): NewImageDlg.setObjectName("NewImageDlg") NewImageDlg.resize(287, 214) self.gridlayout = QtWidgets.QGridLayout(NewImageDlg) self.gridlayout.setContentsMargins(9, 9, 9, 9) self.gridlayout.setSpacing(6) self.gridlayout.setObjectName("gridlayout") self.buttonBox = QtWidgets.QDialogButtonBox(NewImageDlg) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.gridlayout.addWidget(self.buttonBox, 5, 1, 1, 2) spacerItem = QtWidgets.QSpacerItem(269, 16, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.gridlayout.addItem(spacerItem, 4, 0, 1, 3) self.colorLabel = QtWidgets.QLabel(NewImageDlg) self.colorLabel.setFrameShape(QtWidgets.QFrame.StyledPanel) self.colorLabel.setFrameShadow(QtWidgets.QFrame.Raised) self.colorLabel.setText("") self.colorLabel.setScaledContents(True) self.colorLabel.setObjectName("colorLabel") self.gridlayout.addWidget(self.colorLabel, 3, 1, 1, 1) self.label_3 = QtWidgets.QLabel(NewImageDlg) self.label_3.setObjectName("label_3") self.gridlayout.addWidget(self.label_3, 3, 0, 1, 1) self.colorButton = QtWidgets.QPushButton(NewImageDlg) self.colorButton.setObjectName("colorButton") self.gridlayout.addWidget(self.colorButton, 3, 2, 1, 1) self.brushComboBox = QtWidgets.QComboBox(NewImageDlg) self.brushComboBox.setObjectName("brushComboBox") self.gridlayout.addWidget(self.brushComboBox, 2, 1, 1, 2) self.label_4 = QtWidgets.QLabel(NewImageDlg) self.label_4.setObjectName("label_4") self.gridlayout.addWidget(self.label_4, 2, 0, 1, 1) self.label = QtWidgets.QLabel(NewImageDlg) self.label.setObjectName("label") self.gridlayout.addWidget(self.label, 0, 0, 1, 1) self.label_2 = QtWidgets.QLabel(NewImageDlg) self.label_2.setObjectName("label_2") self.gridlayout.addWidget(self.label_2, 1, 0, 1, 1) self.heightSpinBox = QtWidgets.QSpinBox(NewImageDlg) self.heightSpinBox.setAlignment(QtCore.Qt.AlignRight) self.heightSpinBox.setMinimum(8) self.heightSpinBox.setMaximum(512) self.heightSpinBox.setSingleStep(4) self.heightSpinBox.setProperty("value", 64) self.heightSpinBox.setObjectName("heightSpinBox") self.gridlayout.addWidget(self.heightSpinBox, 1, 1, 1, 1) self.widthSpinBox = QtWidgets.QSpinBox(NewImageDlg) self.widthSpinBox.setAlignment(QtCore.Qt.AlignRight) self.widthSpinBox.setMinimum(8) self.widthSpinBox.setMaximum(512) self.widthSpinBox.setSingleStep(4) self.widthSpinBox.setProperty("value", 64) self.widthSpinBox.setObjectName("widthSpinBox") self.gridlayout.addWidget(self.widthSpinBox, 0, 1, 1, 1) self.label_4.setBuddy(self.brushComboBox) self.label.setBuddy(self.widthSpinBox) self.label_2.setBuddy(self.heightSpinBox) self.retranslateUi(NewImageDlg) self.buttonBox.accepted.connect(NewImageDlg.accept) self.buttonBox.rejected.connect(NewImageDlg.reject) QtCore.QMetaObject.connectSlotsByName(NewImageDlg) NewImageDlg.setTabOrder(self.widthSpinBox, self.heightSpinBox) NewImageDlg.setTabOrder(self.heightSpinBox, self.brushComboBox) NewImageDlg.setTabOrder(self.brushComboBox, self.colorButton) NewImageDlg.setTabOrder(self.colorButton, self.buttonBox) def retranslateUi(self, NewImageDlg): _translate = QtCore.QCoreApplication.translate NewImageDlg.setWindowTitle(_translate("NewImageDlg", "Image Chooser - New Image")) self.label_3.setText(_translate("NewImageDlg", "Color")) self.colorButton.setText(_translate("NewImageDlg", "&Color...")) self.label_4.setText(_translate("NewImageDlg", "&Brush pattern:")) self.label.setText(_translate("NewImageDlg", "&Width:")) self.label_2.setText(_translate("NewImageDlg", "&Height:")) self.heightSpinBox.setSuffix(_translate("NewImageDlg", " px")) self.widthSpinBox.setSuffix(_translate("NewImageDlg", " px"))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
/home/yrd/eric_workspace/charter6/newimagedlg.py
# -*- coding: utf-8 -*-"""Module implementing NewImageDlg."""from PyQt5.QtCore import pyqtSlot,Qt,QVariantfrom PyQt5.QtWidgets import QDialog,QApplication,QColorDialogfrom PyQt5.QtGui import QPixmap,QBrush,QPainterfrom Ui_newimagedlg import Ui_NewImageDlgclass NewImageDlg(QDialog, Ui_NewImageDlg): """ Class documentation goes here. """ def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(NewImageDlg, self).__init__(parent) self.setupUi(self) self.color = Qt.red for value, text in ( (Qt.SolidPattern, "Solid"), (Qt.Dense1Pattern, "Dense #1"), (Qt.Dense2Pattern, "Dense #2"), (Qt.Dense3Pattern, "Dense #3"), (Qt.Dense4Pattern, "Dense #4"), (Qt.Dense5Pattern, "Dense #5"), (Qt.Dense6Pattern, "Dense #6"), (Qt.Dense7Pattern, "Dense #7"), (Qt.HorPattern, "Horizontal"), (Qt.VerPattern, "Vertical"), (Qt.CrossPattern, "Cross"), (Qt.BDiagPattern, "Backward Diagonal"), (Qt.FDiagPattern, "Forward Diagonal"), (Qt.DiagCrossPattern, "Diagonal Cross")): self.brushComboBox.addItem(text, QVariant(value)) self.colorButton.clicked.connect(self.getColor) self.brushComboBox.activated.connect(self.setColor) self.setColor() self.widthSpinBox.setFocus() def getColor(self): color = QColorDialog.getColor(Qt.black, self) if color.isValid(): self.color = color self.setColor() def setColor(self): pixmap = self._makePixmap(60, 30) self.colorLabel.setPixmap(pixmap) def image(self): pixmap = self._makePixmap(self.widthSpinBox.value(), self.heightSpinBox.value()) return QPixmap.toImage(pixmap) def _makePixmap(self, width, height): pixmap = QPixmap(width, height) style = self.brushComboBox.itemData( self.brushComboBox.currentIndex()) brush = QBrush(self.color, Qt.BrushStyle(style)) painter = QPainter(pixmap) painter.fillRect(pixmap.rect(), Qt.white) painter.fillRect(pixmap.rect(), brush) return pixmap
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
/home/yrd/eric_workspace/charter6/helpform.py
# -*- coding: utf-8 -*-from PyQt5.QtCore import QUrl, Qtfrom PyQt5.QtWidgets import QAction, QApplication, QDialog,QLabel, QTextBrowser, QToolBar, QVBoxLayoutfrom PyQt5.QtGui import QIcon,QKeySequenceimport resources_rcclass HelpForm(QDialog): def __init__(self, page, parent=None): super(HelpForm, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) self.setAttribute(Qt.WA_GroupLeader) backAction = QAction(QIcon(":/back.png"), "&Back", self) backAction.setShortcut(QKeySequence.Back) homeAction = QAction(QIcon(":/home.png"), "&Home", self) homeAction.setShortcut("Home") self.pageLabel = QLabel() toolBar = QToolBar() toolBar.addAction(backAction) toolBar.addAction(homeAction) toolBar.addWidget(self.pageLabel) self.textBrowser = QTextBrowser() layout = QVBoxLayout() layout.addWidget(toolBar) layout.addWidget(self.textBrowser, 1) self.setLayout(layout) backAction.triggered.connect(self.tbackward) homeAction.triggered.connect(self.thome) self.textBrowser.sourceChanged.connect(self.updatePageTitle) self.textBrowser.setSearchPaths([":/help"]) self.textBrowser.setSource(QUrl(page)) self.resize(400, 600) self.setWindowTitle("{0} Help".format( QApplication.applicationName())) def updatePageTitle(self): self.pageLabel.setText(self.textBrowser.documentTitle()) def tbackward(self): self.textBrowser.backward() def thome(self): self.textBrowser.home()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
/home/yrd/eric_workspace/charter6/resizedlg.py
# -*- coding: utf-8 -*-from PyQt5.QtCore import Qtfrom PyQt5.QtWidgets import (QApplication, QDialog, QDialogButtonBox, QGridLayout, QLabel, QSpinBox)class ResizeDlg(QDialog): def __init__(self, width, height, parent=None): super(ResizeDlg, self).__init__(parent) widthLabel = QLabel("&Width:") self.widthSpinBox = QSpinBox() widthLabel.setBuddy(self.widthSpinBox) self.widthSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.widthSpinBox.setRange(4, width * 4) self.widthSpinBox.setValue(width) heightLabel = QLabel("&Height:") self.heightSpinBox = QSpinBox() heightLabel.setBuddy(self.heightSpinBox) self.heightSpinBox.setAlignment(Qt.AlignRight| Qt.AlignVCenter) self.heightSpinBox.setRange(4, height * 4) self.heightSpinBox.setValue(height) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) layout = QGridLayout() layout.addWidget(widthLabel, 0, 0) layout.addWidget(self.widthSpinBox, 0, 1) layout.addWidget(heightLabel, 1, 0) layout.addWidget(self.heightSpinBox, 1, 1) layout.addWidget(buttonBox, 2, 0, 1, 2) self.setLayout(layout) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) self.setWindowTitle("Image Changer - Resize") def result(self): return self.widthSpinBox.value(), self.heightSpinBox.value()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
/home/yrd/eric_workspace/charter6/mainwindow.py
# -*- coding: utf-8 -*-"""Module implementing MainWindow."""from PyQt5.QtCore import pyqtSlot,Qt,PYQT_VERSION_STR,QT_VERSION_STR,QSettings,QTimer,QFile, QFileInfo,QByteArray,QVariantfrom PyQt5.QtWidgets import QMainWindow,QDockWidget,QLabel,QDockWidget,QListWidget,QApplication,\ QFrame,QAction,QActionGroup,QMessageBox,QSpinBox,QFileDialog,QInputDialogfrom PyQt5.QtGui import QImage,QIcon,QKeySequence,QPixmap,QImageReader,QImageWriter,QPainterfrom PyQt5.QtPrintSupport import QPrinter,QPrintDialogimport helpformimport newimagedlgimport resizedlgimport platformimport sysimport resources_rcimport os__version__ = "1.0.0"class MainWindow(QMainWindow): """ Class documentation goes here. """ def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(MainWindow, self).__init__(parent) self.image = QImage() self.dirty = False self.filename = None self.mirroredvertically = False self.mirroredhorizontally = False self.imageLabel = QLabel() self.imageLabel.setMinimumSize(200, 200) self.imageLabel.setAlignment(Qt.AlignCenter) self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu) self.setCentralWidget(self.imageLabel) logDockWidget = QDockWidget("Log", self) logDockWidget.setObjectName("LogDockWidget") logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea| Qt.RightDockWidgetArea) self.listWidget = QListWidget() logDockWidget.setWidget(self.listWidget) self.addDockWidget(Qt.RightDockWidgetArea, logDockWidget) self.printer = None self.sizeLabel = QLabel() self.sizeLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken) status = self.statusBar() status.setSizeGripEnabled(False) status.addPermanentWidget(self.sizeLabel) status.showMessage("Ready", 5000)#clearMessage() fileNewAction = self.createAction("&New...", self.fileNew, QKeySequence.New, "filenew", "Create an image file") fileOpenAction = self.createAction("&Open...", self.fileOpen, QKeySequence.Open, "fileopen", "Open an existing image file") fileSaveAction = self.createAction("&Save", self.fileSave, QKeySequence.Save, "filesave", "Save the image") fileSaveAsAction = self.createAction("Save &As...", self.fileSaveAs, icon="filesaveas", tip="Save the image using a new name") filePrintAction = self.createAction("&Print", self.filePrint, QKeySequence.Print, "fileprint", "Print the image") fileQuitAction = self.createAction("&Quit", self.close, "Ctrl+Q", "filequit", "Close the application") editInvertAction = self.createAction("&Invert", self.editInvert, "Ctrl+I", "editinvert", "Invert the image's colors", True, "toggled(bool)") editSwapRedAndBlueAction = self.createAction("Sw&ap Red and Blue", self.editSwapRedAndBlue, "Ctrl+A", "editswap", "Swap the image's red and blue color components", True, "toggled(bool)") editZoomAction = self.createAction("&Zoom...", self.editZoom, "Alt+Z", "editzoom", "Zoom the image") editResizeAction = self.createAction("&Resize...", self.editResize, "Ctrl+R", "editresize", "Resize the image") mirrorGroup = QActionGroup(self) editUnMirrorAction = self.createAction("&Unmirror", self.editUnMirror, "Ctrl+U", "editunmirror", "Unmirror the image", True, "toggled(bool)") mirrorGroup.addAction(editUnMirrorAction) editMirrorHorizontalAction = self.createAction( "Mirror &Horizontally", self.editMirrorHorizontal, "Ctrl+H", "editmirrorhoriz", "Horizontally mirror the image", True, "toggled(bool)") mirrorGroup.addAction(editMirrorHorizontalAction) editMirrorVerticalAction = self.createAction( "Mirror &Vertically", self.editMirrorVertical, "Ctrl+V", "editmirrorvert", "Vertically mirror the image", True, "toggled(bool)") mirrorGroup.addAction(editMirrorVerticalAction) editUnMirrorAction.setChecked(True) helpAboutAction = self.createAction("&About Image Changer", self.helpAbout) helpHelpAction = self.createAction("&Help", self.helpHelp, QKeySequence.HelpContents) #file Menu self.fileMenu = self.menuBar().addMenu("&File") self.fileMenuActions = (fileNewAction, fileOpenAction, fileSaveAction, fileSaveAsAction, None, filePrintAction, fileQuitAction) self.fileMenu.aboutToShow.connect(self.updateFileMenu) #edit Menu editMenu = self.menuBar().addMenu("&Edit") self.addActions(editMenu, (editInvertAction, editSwapRedAndBlueAction, editZoomAction,editResizeAction)) #mirrorMenu mirrorMenu = editMenu.addMenu(QIcon(":/editmirror.png"), "&Mirror") self.addActions(mirrorMenu, (editUnMirrorAction, editMirrorHorizontalAction, editMirrorVerticalAction)) #help Menu helpMenu = self.menuBar().addMenu("&Help") self.addActions(helpMenu, (helpAboutAction, helpHelpAction)) #tool bar fileToolbar = self.addToolBar("File") fileToolbar.setObjectName("FileToolBar") self.addActions(fileToolbar, (fileNewAction, fileOpenAction, fileSaveAsAction)) editToolbar = self.addToolBar("Edit") editToolbar.setObjectName("EditToolBar") self.addActions(editToolbar, (editInvertAction, editSwapRedAndBlueAction, editUnMirrorAction, editMirrorVerticalAction, editMirrorHorizontalAction)) self.zoomSpinBox = QSpinBox() self.zoomSpinBox.setRange(1, 400) self.zoomSpinBox.setSuffix(" %") self.zoomSpinBox.setValue(100) self.zoomSpinBox.setToolTip("Zoom the image") self.zoomSpinBox.setStatusTip(self.zoomSpinBox.toolTip()) self.zoomSpinBox.setFocusPolicy(Qt.NoFocus) self.zoomSpinBox.valueChanged[int].connect(self.showImage) editToolbar.addWidget(self.zoomSpinBox) self.addActions(self.imageLabel, (editInvertAction, editSwapRedAndBlueAction, editUnMirrorAction, editMirrorVerticalAction, editMirrorHorizontalAction)) self.resetableActions = ((editInvertAction, False), (editSwapRedAndBlueAction, False), (editUnMirrorAction, True)) settings = QSettings("MyCompany", "MyApp") self.recentFiles=settings.value("RecentFiles") #self.recentFiles = [] self.restoreGeometry( QByteArray(settings.value("MainWindow/Geometry"))) self.restoreState(QByteArray(settings.value("MainWindow/State"))) self.setWindowTitle("Image Changer") self.updateFileMenu() QTimer.singleShot(0, self.loadInitialFile) def createAction(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/{0}.png".format(icon))) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None and signal=="triggered()": action.triggered.connect(slot) if slot is not None and signal=="toggled(bool)": action.toggled[bool].connect(slot) if checkable: action.setCheckable(True) return action def addActions(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) def updateFileMenu(self): self.fileMenu.clear() self.addActions(self.fileMenu, self.fileMenuActions[:-1]) current = self.filename recentFiles = [] #self.recentFiles=[] for fname in self.recentFiles: if fname != current and QFile.exists(fname): #recentFiles.insert(0,fname) recentFiles.append(fname) if recentFiles: self.fileMenu.addSeparator() for i, fname in enumerate(recentFiles): action = QAction(QIcon(":/icon.png"), "&{0} {1}".format(i + 1, QFileInfo( fname).fileName()), self) action.setData(QVariant(fname)) action.triggered[bool].connect(self.loadFile) self.fileMenu.addAction(action) self.fileMenu.addSeparator() self.fileMenu.addAction(self.fileMenuActions[-1]) def okToContinue(self): if self.dirty: reply = QMessageBox.question(self, "Image Changer - Unsaved Changes", "Save unsaved changes?", QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel) if reply == QMessageBox.Cancel: return False elif reply == QMessageBox.Yes: return self.fileSave() return True def fileNew(self): if not self.okToContinue(): return dialog = newimagedlg.NewImageDlg(self) if dialog.exec_(): self.addRecentFile(self.filename) self.image = QImage() for action, check in self.resetableActions: action.setChecked(check) self.image = dialog.image() self.filename = None self.dirty = True self.showImage() self.sizeLabel.setText("{0} x {1}".format(self.image.width(), self.image.height())) self.updateStatus("Created new image") def fileOpen(self): if not self.okToContinue(): return dir = (os.path.dirname(self.filename) if self.filename is not None else ".") formats = (["*.{0}".format(format.data().decode("ascii").lower()) for format in QImageReader.supportedImageFormats()]) fname,tpye = QFileDialog.getOpenFileName(self, "Image Changer - Choose Image", dir, "Image files ({0})".format(" ".join(formats))) if fname: self.loadFile(True,fname) def fileSave(self): if self.image.isNull(): return True if self.filename is None: return self.fileSaveAs() else: if self.image.save(self.filename, None): self.updateStatus("Saved as {0}".format(self.filename)) self.dirty = False return True else: self.updateStatus("Failed to save {0}".format( self.filename)) return False def fileSaveAs(self): if self.image.isNull(): return True fname = self.filename if self.filename is not None else "." formats = (["*.{0}".format(format.data().decode("ascii").lower()) for format in QImageWriter.supportedImageFormats()]) fname,tpye = QFileDialog.getSaveFileName(self, "Image Changer - Save Image", fname, "Image files ({0})".format(" ".join(formats))) if fname: if "." not in fname: fname += ".png" self.addRecentFile(fname) self.filename = fname return self.fileSave() return False def filePrint(self): if self.image.isNull(): return if self.printer is None: self.printer = QPrinter(QPrinter.HighResolution) self.printer.setPageSize(QPrinter.Letter) form = QPrintDialog(self.printer, self) if form.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.drawImage(0, 0, self.image) def loadFile(self,actiontrigger=False,fname=None): if fname is None: action = self.sender() if isinstance(action, QAction): fname = str(action.data()) if not self.okToContinue(): return else: return print(fname) if fname: self.filename = None image = QImage(fname) if image.isNull(): message = "Failed to read {0}".format(fname) else: self.addRecentFile(fname) self.image = QImage() for action, check in self.resetableActions: action.setChecked(check) self.image = image self.filename = fname self.showImage() self.dirty = False self.sizeLabel.setText("{0} x {1}".format( image.width(), image.height())) message = "Loaded {0}".format(os.path.basename(fname)) self.updateStatus(message) def loadInitialFile(self): settings = QSettings() fname = str(settings.value("LastFile")) if fname and QFile.exists(fname): self.loadFile(fname) def addRecentFile(self, fname): if fname is None: return if fname not in self.recentFiles: self.recentFiles.insert(0,fname) while len(self.recentFiles) > 9: self.recentFiles.pop() def updateStatus(self, message): self.statusBar().showMessage(message, 5000) self.listWidget.addItem(message) if self.filename is not None: self.setWindowTitle("Image Changer - {0}[*]".format( os.path.basename(self.filename))) elif not self.image.isNull(): self.setWindowTitle("Image Changer - Unnamed[*]") else: self.setWindowTitle("Image Changer[*]") self.setWindowModified(self.dirty) def editInvert(self, on): if self.image.isNull(): return self.image.invertPixels() self.showImage() self.dirty = True self.updateStatus("Inverted" if on else "Uninverted") def editSwapRedAndBlue(self, on): if self.image.isNull(): return self.image = self.image.rgbSwapped() self.showImage() self.dirty = True self.updateStatus(("Swapped Red and Blue" if on else "Unswapped Red and Blue")) def editZoom(self): if self.image.isNull(): return percent, ok = QInputDialog.getInt(self, "Image Changer - Zoom", "Percent:", self.zoomSpinBox.value(), 1, 400) if ok: self.zoomSpinBox.setValue(percent) def editUnMirror(self, on): if self.image.isNull(): return if self.mirroredhorizontally: self.editMirrorHorizontal(False) if self.mirroredvertically: self.editMirrorVertical(False) def editMirrorHorizontal(self, on): if self.image.isNull(): return self.image = self.image.mirrored(True, False) self.showImage() self.mirroredhorizontally = not self.mirroredhorizontally self.dirty = True self.updateStatus(("Mirrored Horizontally" if on else "Unmirrored Horizontally")) def editMirrorVertical(self, on): if self.image.isNull(): return self.image = self.image.mirrored(False, True) self.showImage() self.mirroredvertically = not self.mirroredvertically self.dirty = True self.updateStatus(("Mirrored Vertically" if on else "Unmirrored Vertically")) def editResize(self): if self.image.isNull(): return form = resizedlg.ResizeDlg(self.image.width(), self.image.height(), self) if form.exec_(): width, height = form.result() if (width == self.image.width() and height == self.image.height()): self.statusBar().showMessage("Resized to the same size", 5000) else: self.image = self.image.scaled(width, height) self.showImage() self.dirty = True size = "{0} x {1}".format(self.image.width(), self.image.height()) self.sizeLabel.setText(size) self.updateStatus("Resized to {0}".format(size)) def helpAbout(self): QMessageBox.about(self, "About Image Changer", """<b>Image Changer</b> v {0} <p>Copyright © 2008-9 Qtrac Ltd. All rights reserved. <p>This application can be used to perform simple image manipulations. <p>Python {1} - Qt {2} - PyQt {3} on {4}""".format( __version__, platform.python_version(), QT_VERSION_STR, PYQT_VERSION_STR, platform.system())) def helpHelp(self): form = helpform.HelpForm("index.html", self) form.show() def showImage(self, percent=None): if self.image.isNull(): return if percent is None: percent = self.zoomSpinBox.value() factor = percent / 100.0 width = self.image.width() * factor height = self.image.height() * factor image = self.image.scaled(width, height, Qt.KeepAspectRatio) self.imageLabel.setPixmap(QPixmap.fromImage(image)) def closeEvent(self, event): if self.okToContinue(): settings = QSettings("MyCompany", "MyApp") settings.setValue("LastFile", self.filename) settings.setValue("RecentFiles", self.recentFiles) settings.setValue("MainWindow/Geometry",self.saveGeometry()) settings.setValue("MainWindow/State", self.saveState()) else: event.ignore()if __name__ == "__main__": app = QApplication(sys.argv) form = MainWindow() form.show() app.exec_()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
运行结果:
- pyrcc5将resources.qrc转换成py文件
- python3.5 将py文件转换成EXE文件
- python在Windows下将.py转换成.exe文件
- python将py文件转换为pyc
- python将py文件转换为pyc
- RESOURCES = spreadsheet.qrc
- 将py文件打包成exe文件
- .ui文件转换成.py文件
- python py文件转换成pyc文件
- Windows下采用PyInstall将py文件转换成exe可执行文件
- Windows下采用PyInstall将py文件转换成exe可执行文件
- 用PyInstaller将依赖Dlib库的python文件(.py)转换成exe可执行文件
- pyinstaller--将py文件转化成exe
- ipython笔记转换成py文件
- 将.py转换为.exe
- 利用cx_Freeze将py文件打包成exe文件
- 利用cx_Freeze将py文件打包成exe文件
- 利用cx_Freeze将py文件打包成exe文件
- PHP接收二进制流并生成文件
- Java中异常处理方法总结
- 无状态服务 VS 有状态服务
- Elastic-Job之简单Job
- Android 如何查看界面层数和界面所属组件信息
- pyrcc5将resources.qrc转换成py文件
- js判断是pc端还是移动端
- 面经整理-数据库
- vs2010上运行c++程序时显示错误无法打开.exe进行写入
- 万物皆对象-《Think in java》第二章
- [原创] 树莓派使用多个联通4G上网卡
- opencv找直线及直线交点
- Java并发---- Executor并发框架--ThreadToolExecutor类详解(execute方法,关闭方法)
- 文章标题