pyrcc5将resources.qrc转换成py文件
需要通过pyrcc5将resources.qrc转换成py文件,并在主程序引入。
pyrcc5 -o resources_rc.py resources.qrc
用python3+PyQt5改写Python Qt GUI快速编程的第6章实例主窗口
- 标签:
- python /
- qt /
- gui /
- pyqt
本文是对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:returnif 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:returnif 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.translateNewImageDlg.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,QVariant
from PyQt5.QtWidgets import QDialog,QApplication,QColorDialog
from 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.redfor 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 = colorself.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, Qt
from PyQt5.QtWidgets import QAction, QApplication, QDialog,QLabel, QTextBrowser, QToolBar, QVBoxLayout
from PyQt5.QtGui import QIcon,QKeySequence
import 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 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()
- 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,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 = Falseself.filename = Noneself.mirroredvertically = Falseself.mirroredhorizontally = Falseself.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 = Noneself.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 Menuself.fileMenu = self.menuBar().addMenu("&File")self.fileMenuActions = (fileNewAction, fileOpenAction,fileSaveAction, fileSaveAsAction, None, filePrintAction,fileQuitAction)self.fileMenu.aboutToShow.connect(self.updateFileMenu)#edit MenueditMenu = self.menuBar().addMenu("&Edit")self.addActions(editMenu, (editInvertAction,editSwapRedAndBlueAction, editZoomAction,editResizeAction)) #mirrorMenumirrorMenu = editMenu.addMenu(QIcon(":/editmirror.png"),"&Mirror")self.addActions(mirrorMenu, (editUnMirrorAction,editMirrorHorizontalAction, editMirrorVerticalAction)) #help MenuhelpMenu = self.menuBar().addMenu("&Help")self.addActions(helpMenu, (helpAboutAction, helpHelpAction)) #tool barfileToolbar = 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 actiondef 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.filenamerecentFiles = []#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 Falseelif reply == QMessageBox.Yes:return self.fileSave()return True def fileNew(self):if not self.okToContinue():returndialog = 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 = Noneself.dirty = Trueself.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():returndir = (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 Trueif 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 = Falsereturn Trueelse:self.updateStatus("Failed to save {0}".format(self.filename))return Falsedef fileSaveAs(self):if self.image.isNull():return Truefname = 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 = fnamereturn self.fileSave()return False def filePrint(self):if self.image.isNull():returnif 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():returnelse:returnprint(fname)if fname:self.filename = Noneimage = 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 = imageself.filename = fnameself.showImage()self.dirty = Falseself.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:returnif 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():returnself.image.invertPixels()self.showImage()self.dirty = Trueself.updateStatus("Inverted" if on else "Uninverted")def editSwapRedAndBlue(self, on):if self.image.isNull():returnself.image = self.image.rgbSwapped()self.showImage()self.dirty = Trueself.updateStatus(("Swapped Red and Blue"if on else "Unswapped Red and Blue"))def editZoom(self):if self.image.isNull():returnpercent, 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():returnif self.mirroredhorizontally:self.editMirrorHorizontal(False)if self.mirroredvertically:self.editMirrorVertical(False)def editMirrorHorizontal(self, on):if self.image.isNull():returnself.image = self.image.mirrored(True, False)self.showImage()self.mirroredhorizontally = not self.mirroredhorizontallyself.dirty = Trueself.updateStatus(("Mirrored Horizontally"if on else "Unmirrored Horizontally"))def editMirrorVertical(self, on):if self.image.isNull():returnself.image = self.image.mirrored(False, True)self.showImage()self.mirroredvertically = not self.mirroredverticallyself.dirty = Trueself.updateStatus(("Mirrored Vertically"if on else "Unmirrored Vertically")) def editResize(self):if self.image.isNull():returnform = resizedlg.ResizeDlg(self.image.width(),self.image.height(), self)if form.exec_():width, height = form.result()if (width == self.image.width() andheight == self.image.height()):self.statusBar().showMessage("Resized to the same size",5000)else:self.image = self.image.scaled(width, height)self.showImage()self.dirty = Truesize = "{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 performsimple 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():returnif percent is None:percent = self.zoomSpinBox.value()factor = percent / 100.0width = self.image.width() * factorheight = self.image.height() * factorimage = 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文件相关推荐
- 一、软件界面的设计——QT设计师换背景,一些按钮学习心得,转换成py文件遇到的问题
文章目录 前言 一.Qt设计师 1.使用部件 2.资源读入 二.转换成.py 1.转换工具 2.注意 前言 结合石油通信这门课,基于单片机课程.用了CC2530单片机,用了温湿度传感器,MQ-2传感器 ...
- Python 中 PyQt5 + pycharm 调用 Qt Designer,将.ui文件转换成 .py 文件
From:https://blog.csdn.net/qq_40666028/article/details/81069878 基于Qt Designer 和 pyuic 开发 UI 界面的方法:ht ...
- python 图片转换成py文件
python 图片转换成py文件 app.png 图片转为py文件.py import base64def pic_to_py(path_):"""将图像文件转换为py文 ...
- 如何将qt的.ui文件转换成.py文件(pycharm+pyuic5+Qtdesigner)以及遇到的问题(自己的记录不是教程)
注意:本篇博客不是教程,我只是把自己整个过程记录了下来,其中遇到一些问题,如果出现相同问题可进行参考. 目录 一.安装pyqt5 二.创建两个 external tool 1.Qtdesigner 2 ...
- pycharm中将ui文件转换成py文件
方法一:直接使用命令行 python -m PyQt5.uic.pyuic xx.ui -o xx.py 方法二:直接使用命令 先进到C:\python\pkgs\pyqt-5.9.2-py37h65 ...
- 云炬Qtpy5开发与实战笔记 3PyCharm添加PyUIC扩展——将.ui文件转换成.py文件
将pyuic加入pycharm扩展工具中 (Arguments参数: -m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py) 然 ...
- 如何将ipynb文件转换转换为py文件?
在git上抓到了ipynb文件如何转换成.py文件并运行? step1:pip install jupyter step2:在cmd中跳到ipynb文件路径下,运行jupyter notebook,运 ...
- 将Qt Designer的ui文件转成.py文件
一.在该工程下新建ui_py.py import os import os.path dir = './' # 文件所在的路径 # 找出路径下所有的.ui文件 def UiFile():list = ...
- python转化成excel_python转换excel成py文件
python转换excel成py文件 文件结构如下: originExcelFolder放用来转换的excel文件. targetPyFolder用来存放最后生产的py文件. setting.py用来 ...
最新文章
- GET POST 区别详解
- 这样保养让你皮肤变水嫩 - 健康程序员,至尚生活!
- JAva面试题(微信分享)
- 一口气搞懂「链表」,就靠这20+张图了
- 【paper】BlazeFace: Sub-millisecond Neural Face Detection on Mobile GPUs
- python编程格式化输出_Python的三种格式化输出
- CentOS7环境下搭建ElasticSearch
- 项目升级到Delphi 2010总结
- 2019PASS发布以来第一次更新,快点击查看!
- 多个视频ts文件合并
- 电脑中如何打开进程管理器?
- gradle 使用 exclude 解决jar包冲突
- 【大连理工大学】计算机专业选修:深度学习2020期末复习
- 计算机软件职称高校四川,四川省人社厅:今年部分高校职称自主评审
- BZOJ2815: [ZJOI2012]灾难(支配树)
- 海贼C语言,C语言程序设计(海贼现场课)
- 怎么用visio绘制出一半实线,一半虚线的椭圆,并填充颜色
- 小程序传值对象数值到另一个页面大小限制
- 网易云音乐与阿里音乐牵手!后版权时代,在线音乐拼什么?
- “顶梁柱”落地青川,救助一个人,撑起一个家,换你稳稳的幸福!
热门文章
- 怎么样去提升网站长尾词在百度搜狗360的排名?
- pdf转ppt在线转换
- mysql 分库分表策略_【数据库】分库分表策略
- 【前端之路】通过css让移动端与pc端自适应
- 上海泰泽投资咨询有限公司(日本VE协会上海办事处)与江苏省外专局签订战略合作协议
- mysql定时任务每天凌晨三点钟醒来_常常凌晨三四点醒来是怎么回事?遇到这事要警惕了...
- A股-入门-弱市中如何把握超跌股的机会
- Prophet学习(五)季节性、假日效应和回归因子
- Arduino Mind+编程 轮询读取多个软串口数据的方法讨论
- signature=d208b1bb0cb69ace8714b67c8fb41881,The mechanics of cemented carbonate sands.