pyrcc5 -o resources_rc.py resources.qrc
本文是对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())
改动为
self.restoreGeometry(
QByteArray(settings.value("MainWindow/Geometry")))
self.restoreState(QByteArray(settings.value("MainWindow/State")))
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)))
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()
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
version="1.0">
<file alias="filenew.png">images/filenew.pngfile>
<file alias="fileopen.png">images/fileopen.pngfile>
<file alias="filesave.png">images/filesave.pngfile>
<file alias="filesaveas.png">images/filesaveas.pngfile>
<file alias="fileprint.png">images/fileprint.pngfile>
<file alias="filequit.png">images/filequit.pngfile>
<file alias="editinvert.png">images/editinvert.pngfile>
<file alias="editswap.png">images/editswap.pngfile>
<file alias="editzoom.png">images/editzoom.pngfile>
<file alias="editmirror.png">images/editmirror.pngfile>
<file alias="editunmirror.png">images/editunmirror.pngfile>
<file alias="editmirrorhoriz.png">images/editmirrorhoriz.pngfile>
<file alias="editmirrorvert.png">images/editmirrorvert.pngfile>
<file alias="back.png">images/back.pngfile>
<file alias="home.png">images/home.pngfile>
<file alias="icon.png">images/icon.pngfile>
<file>help/editmenu.htmlfile>
<file>help/filemenu.htmlfile>
<file>help/index.htmlfile>
/home/yrd/eric_workspace/charter6/Ui_newimagedlg.py
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class 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"))
/home/yrd/eric_workspace/charter6/newimagedlg.py
# -*- coding: utf-8 -*-
"""
Module implementing NewImageDlg.
"""
from PyQt5.QtCore import pyqtSlot,Qt,QVariant
from PyQt5.QtWidgets import QDialog,QApplication,QColorDialog
from PyQt5.QtGui import QPixmap,QBrush,QPainter
from Ui_newimagedlg import Ui_NewImageDlg
class 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
/home/yrd/eric_workspace/charter6/helpform.py
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtWidgets import QAction, QApplication, QDialog,QLabel, QTextBrowser, QToolBar, QVBoxLayout
from PyQt5.QtGui import QIcon,QKeySequence
import resources_rc
class 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()
/home/yrd/eric_workspace/charter6/resizedlg.py
# -*- coding: utf-8 -*-
from PyQt5.QtCore import Qt
from 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()
/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,QVariant
from PyQt5.QtWidgets import QMainWindow,QDockWidget,QLabel,QDockWidget,QListWidget,QApplication,\
QFrame,QAction,QActionGroup,QMessageBox,QSpinBox,QFileDialog,QInputDialog
from PyQt5.QtGui import QImage,QIcon,QKeySequence,QPixmap,QImageReader,QImageWriter,QPainter
from PyQt5.QtPrintSupport import QPrinter,QPrintDialog
import helpform
import newimagedlg
import resizedlg
import platform
import sys
import resources_rc
import 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",
"""Image Changer v {0}
Copyright © 2008-9 Qtrac Ltd.
All rights reserved.
This application can be used to perform
simple image manipulations.
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_()