python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序
程序员文章站
2024-03-31 09:02:46
本文通过python3+pyqt5实现《python qt gui 快速编程》这本书的page designer应用程序,采用qgraphicsview,qgraphics...
本文通过python3+pyqt5实现《python qt gui 快速编程》这本书的page designer应用程序,采用qgraphicsview,qgraphicsscene,qgraphicsitem,这个程序包含有多个文本,图片和框的页面。有些图形类在pyqt5已过时,所以本代码改动幅度比较大。主要的类或方法的改变如下:
qmatrix==>qtransform
setmatrix==>settransform
rotate ==> setrotation
本例中,由于event.delta()已过时,还重写了wheelevent方法:
def wheelevent(self, event): #factor = 1.41 ** (-event.delta() / 240.0) #factor = 1.41 ** (-abs(event.startx()-event.y()) / 240.0) factor = event.angledelta().y()/120.0 if event.angledelta().y()/120.0 > 0: factor=2 else: factor=0.5 self.scale(factor, factor)
为了保持代码可读行,增加了一个类:
class graphicspixmapitem(qgraphicspixmapitem): #add by yangrongdong def __init__(self,pixmap): super(qgraphicspixmapitem, self).__init__(pixmap)
本例中还有包含菜单的按钮:
if text == "&align": menu = qmenu(self) for text, arg in ( ("align &left", qt.alignleft), ("align &right", qt.alignright), ("align &top", qt.aligntop), ("align &bottom", qt.alignbottom)): wrapper = functools.partial(self.setalignment, arg) self.wrapped.append(wrapper) menu.addaction(text, wrapper) button.setmenu(menu)
本例中还针对qstyleoptiongraphicsitem.levelofdetail已过时,改写如下:
option.levelofdetailfromtransform(self.transform())
下面为完整的代码:
#!/usr/bin/env python3 import functools import random import sys from pyqt5.qtcore import (qbytearray, qdatastream, qfile, qfileinfo, qiodevice, qpoint, qpointf, qrectf, qt) from pyqt5.qtwidgets import (qapplication, qdialog, qdialogbuttonbox, qfiledialog, qfontcombobox, qgraphicsitem, qgraphicspixmapitem, qgraphicsscene, qgraphicstextitem, qgraphicsview, qgridlayout, qhboxlayout, qlabel, qmenu, qmessagebox,qpushbutton, qspinbox, qstyle, qtextedit, qvboxlayout) from pyqt5.qtgui import qfont,qcursor,qfontmetrics,qtransform,qpainter,qpen,qpixmap from pyqt5.qtprintsupport import qprinter,qprintdialog mac = true try: from pyqt5.qtgui import qt_mac_set_native_menubar except importerror: mac = false #pagesize = (595, 842) # a4 in points pagesize = (612, 792) # us letter in points pointsize = 10 magicnumber = 0x70616765 fileversion = 1 dirty = false class textitemdlg(qdialog): def __init__(self, item=none, position=none, scene=none, parent=none): super(qdialog, self).__init__(parent) self.item = item self.position = position self.scene = scene self.editor = qtextedit() self.editor.setacceptrichtext(false) self.editor.settabchangesfocus(true) editorlabel = qlabel("&text:") editorlabel.setbuddy(self.editor) self.fontcombobox = qfontcombobox() self.fontcombobox.setcurrentfont(qfont("times", pointsize)) fontlabel = qlabel("&font:") fontlabel.setbuddy(self.fontcombobox) self.fontspinbox = qspinbox() self.fontspinbox.setalignment(qt.alignright|qt.alignvcenter) self.fontspinbox.setrange(6, 280) self.fontspinbox.setvalue(pointsize) fontsizelabel = qlabel("&size:") fontsizelabel.setbuddy(self.fontspinbox) self.buttonbox = qdialogbuttonbox(qdialogbuttonbox.ok| qdialogbuttonbox.cancel) self.buttonbox.button(qdialogbuttonbox.ok).setenabled(false) if self.item is not none: self.editor.setplaintext(self.item.toplaintext()) self.fontcombobox.setcurrentfont(self.item.font()) self.fontspinbox.setvalue(self.item.font().pointsize()) layout = qgridlayout() layout.addwidget(editorlabel, 0, 0) layout.addwidget(self.editor, 1, 0, 1, 6) layout.addwidget(fontlabel, 2, 0) layout.addwidget(self.fontcombobox, 2, 1, 1, 2) layout.addwidget(fontsizelabel, 2, 3) layout.addwidget(self.fontspinbox, 2, 4, 1, 2) layout.addwidget(self.buttonbox, 3, 0, 1, 6) self.setlayout(layout) self.fontcombobox.currentfontchanged.connect(self.updateui) self.fontspinbox.valuechanged.connect(self.updateui) self.editor.textchanged.connect(self.updateui) self.buttonbox.accepted.connect(self.accept) self.buttonbox.rejected.connect(self.reject) self.setwindowtitle("page designer - {0} text item".format( "add" if self.item is none else "edit")) self.updateui() def updateui(self): font = self.fontcombobox.currentfont() font.setpointsize(self.fontspinbox.value()) self.editor.document().setdefaultfont(font) self.buttonbox.button(qdialogbuttonbox.ok).setenabled( bool(self.editor.toplaintext())) def accept(self): if self.item is none: self.item = textitem("", self.position, self.scene) font = self.fontcombobox.currentfont() font.setpointsize(self.fontspinbox.value()) self.item.setfont(font) self.item.setplaintext(self.editor.toplaintext()) self.item.update() global dirty dirty = true qdialog.accept(self) class textitem(qgraphicstextitem): def __init__(self, text, position, scene, font=qfont("times", pointsize), matrix=qtransform()): super(textitem, self).__init__(text) self.setflags(qgraphicsitem.itemisselectable| qgraphicsitem.itemismovable) self.setfont(font) self.setpos(position) self.settransform(matrix) scene.clearselection() scene.additem(self) self.setselected(true) global dirty dirty = true def parentwidget(self): return self.scene().views()[0] def itemchange(self, change, variant): if change != qgraphicsitem.itemselectedchange: global dirty dirty = true return qgraphicstextitem.itemchange(self, change, variant) def mousedoubleclickevent(self, event): dialog = textitemdlg(self, self.parentwidget()) dialog.exec_() class graphicspixmapitem(qgraphicspixmapitem): #add by yangrongdong def __init__(self,pixmap): super(qgraphicspixmapitem, self).__init__(pixmap) class boxitem(qgraphicsitem): def __init__(self, position, scene, style=qt.solidline, rect=none, matrix=qtransform()): super(boxitem, self).__init__() self.setflags(qgraphicsitem.itemisselectable| qgraphicsitem.itemismovable| qgraphicsitem.itemisfocusable) if rect is none: rect = qrectf(-10 * pointsize, -pointsize, 20 * pointsize, 2 * pointsize) self.rect = rect self.style = style self.setpos(position) self.settransform(matrix) scene.clearselection() scene.additem(self) self.setselected(true) self.setfocus() global dirty dirty = true def parentwidget(self): return self.scene().views()[0] def boundingrect(self): return self.rect.adjusted(-2, -2, 2, 2) def paint(self, painter, option, widget): pen = qpen(self.style) pen.setcolor(qt.black) pen.setwidth(1) if option.state & qstyle.state_selected: pen.setcolor(qt.blue) painter.setpen(pen) painter.drawrect(self.rect) def itemchange(self, change, variant): if change != qgraphicsitem.itemselectedchange: global dirty dirty = true return qgraphicsitem.itemchange(self, change, variant) def contextmenuevent(self, event): wrapped = [] menu = qmenu(self.parentwidget()) for text, param in ( ("&solid", qt.solidline), ("&dashed", qt.dashline), ("d&otted", qt.dotline), ("d&ashdotted", qt.dashdotline), ("dashdo&tdotted", qt.dashdotdotline)): wrapper = functools.partial(self.setstyle, param) wrapped.append(wrapper) menu.addaction(text, wrapper) menu.exec_(event.screenpos()) def setstyle(self, style): self.style = style self.update() global dirty dirty = true def keypressevent(self, event): factor = pointsize / 4 changed = false if event.modifiers() & qt.shiftmodifier: if event.key() == qt.key_left: self.rect.setright(self.rect.right() - factor) changed = true elif event.key() == qt.key_right: self.rect.setright(self.rect.right() + factor) changed = true elif event.key() == qt.key_up: self.rect.setbottom(self.rect.bottom() - factor) changed = true elif event.key() == qt.key_down: self.rect.setbottom(self.rect.bottom() + factor) changed = true if changed: self.update() global dirty dirty = true else: qgraphicsitem.keypressevent(self, event) class graphicsview(qgraphicsview): def __init__(self, parent=none): super(graphicsview, self).__init__(parent) self.setdragmode(qgraphicsview.rubberbanddrag) self.setrenderhint(qpainter.antialiasing) self.setrenderhint(qpainter.textantialiasing) def wheelevent(self, event): #factor = 1.41 ** (-event.delta() / 240.0) factor = event.angledelta().y()/120.0 if event.angledelta().y()/120.0 > 0: factor=2 else: factor=0.5 self.scale(factor, factor) class mainform(qdialog): def __init__(self, parent=none): super(mainform, self).__init__(parent) self.filename = "" self.copieditem = qbytearray() self.pasteoffset = 5 self.prevpoint = qpoint() self.addoffset = 5 self.borders = [] self.printer = qprinter(qprinter.highresolution) self.printer.setpagesize(qprinter.letter) self.view = graphicsview() self.scene = qgraphicsscene(self) self.scene.setscenerect(0, 0, pagesize[0], pagesize[1]) self.addborders() self.view.setscene(self.scene) self.wrapped = [] # needed to keep wrappers alive buttonlayout = qvboxlayout() for text, slot in ( ("add &text", self.addtext), ("add &box", self.addbox), ("add pi&xmap", self.addpixmap), ("&align", none), ("©", self.copy), ("c&ut", self.cut), ("&paste", self.paste), ("&delete...", self.delete), ("&rotate", self.rotate), ("pri&nt...", self.print_), ("&open...", self.open), ("&save", self.save), ("&quit", self.accept)): button = qpushbutton(text) if not mac: button.setfocuspolicy(qt.nofocus) if slot is not none: button.clicked.connect(slot) if text == "&align": menu = qmenu(self) for text, arg in ( ("align &left", qt.alignleft), ("align &right", qt.alignright), ("align &top", qt.aligntop), ("align &bottom", qt.alignbottom)): wrapper = functools.partial(self.setalignment, arg) self.wrapped.append(wrapper) menu.addaction(text, wrapper) button.setmenu(menu) if text == "pri&nt...": buttonlayout.addstretch(5) if text == "&quit": buttonlayout.addstretch(1) buttonlayout.addwidget(button) buttonlayout.addstretch() layout = qhboxlayout() layout.addwidget(self.view, 1) layout.addlayout(buttonlayout) self.setlayout(layout) fm = qfontmetrics(self.font()) self.resize(self.scene.width() + fm.width(" delete... ") + 50, self.scene.height() + 50) self.setwindowtitle("page designer") def addborders(self): self.borders = [] rect = qrectf(0, 0, pagesize[0], pagesize[1]) self.borders.append(self.scene.addrect(rect, qt.yellow)) margin = 5.25 * pointsize self.borders.append(self.scene.addrect( rect.adjusted(margin, margin, -margin, -margin), qt.yellow)) def removeborders(self): while self.borders: item = self.borders.pop() self.scene.removeitem(item) del item def reject(self): self.accept() def accept(self): self.offersave() qdialog.accept(self) def offersave(self): if (dirty and qmessagebox.question(self, "page designer - unsaved changes", "save unsaved changes?", qmessagebox.yes|qmessagebox.no) == qmessagebox.yes): self.save() def position(self): point = self.mapfromglobal(qcursor.pos()) if not self.view.geometry().contains(point): coord = random.randint(36, 144) point = qpoint(coord, coord) else: if point == self.prevpoint: point += qpoint(self.addoffset, self.addoffset) self.addoffset += 5 else: self.addoffset = 5 self.prevpoint = point return self.view.maptoscene(point) def addtext(self): dialog = textitemdlg(position=self.position(), scene=self.scene, parent=self) dialog.exec_() def addbox(self): boxitem(self.position(), self.scene) def addpixmap(self): path = (qfileinfo(self.filename).path() if self.filename else ".") fname,filetype = qfiledialog.getopenfilename(self, "page designer - add pixmap", path, "pixmap files (*.bmp *.jpg *.png *.xpm)") if not fname: return self.createpixmapitem(qpixmap(fname), self.position()) def createpixmapitem(self, pixmap, position, matrix=qtransform()): item = graphicspixmapitem(pixmap) item.setflags(qgraphicsitem.itemisselectable| qgraphicsitem.itemismovable) item.setpos(position) item.settransform(matrix) self.scene.clearselection() self.scene.additem(item) item.setselected(true) global dirty dirty = true return item def selecteditem(self): items = self.scene.selecteditems() if len(items) == 1: return items[0] return none def copy(self): item = self.selecteditem() if item is none: return self.copieditem.clear() self.pasteoffset = 5 stream = qdatastream(self.copieditem, qiodevice.writeonly) self.writeitemtostream(stream, item) def cut(self): item = self.selecteditem() if item is none: return self.copy() self.scene.removeitem(item) del item def paste(self): if self.copieditem.isempty(): return stream = qdatastream(self.copieditem, qiodevice.readonly) self.readitemfromstream(stream, self.pasteoffset) self.pasteoffset += 5 def setalignment(self, alignment): # items are returned in arbitrary order items = self.scene.selecteditems() if len(items) <= 1: return # gather coordinate data leftxs, rightxs, topys, bottomys = [], [], [], [] for item in items: rect = item.sceneboundingrect() leftxs.append(rect.x()) rightxs.append(rect.x() + rect.width()) topys.append(rect.y()) bottomys.append(rect.y() + rect.height()) # perform alignment if alignment == qt.alignleft: xalignment = min(leftxs) for i, item in enumerate(items): item.moveby(xalignment - leftxs[i], 0) elif alignment == qt.alignright: xalignment = max(rightxs) for i, item in enumerate(items): item.moveby(xalignment - rightxs[i], 0) elif alignment == qt.aligntop: yalignment = min(topys) for i, item in enumerate(items): item.moveby(0, yalignment - topys[i]) elif alignment == qt.alignbottom: yalignment = max(bottomys) for i, item in enumerate(items): item.moveby(0, yalignment - bottomys[i]) global dirty dirty = true def rotate(self): for item in self.scene.selecteditems(): item.setrotation(item.rotation()+30) def delete(self): items = self.scene.selecteditems() if (len(items) and qmessagebox.question(self, "page designer - delete", "delete {0} item{1}?".format(len(items), "s" if len(items) != 1 else ""), qmessagebox.yes|qmessagebox.no) == qmessagebox.yes): while items: item = items.pop() self.scene.removeitem(item) del item global dirty dirty = true def print_(self): dialog = qprintdialog(self.printer) if dialog.exec_(): painter = qpainter(self.printer) painter.setrenderhint(qpainter.antialiasing) painter.setrenderhint(qpainter.textantialiasing) self.scene.clearselection() self.removeborders() self.scene.render(painter) self.addborders() def open(self): self.offersave() path = (qfileinfo(self.filename).path() if self.filename else ".") fname,filetype = qfiledialog.getopenfilename(self, "page designer - open", path, "page designer files (*.pgd)") if not fname: return self.filename = fname fh = none try: fh = qfile(self.filename) if not fh.open(qiodevice.readonly): raise ioerror(str(fh.errorstring())) items = self.scene.items() while items: item = items.pop() self.scene.removeitem(item) del item self.addborders() stream = qdatastream(fh) stream.setversion(qdatastream.qt_5_7) magic = stream.readint32() if magic != magicnumber: raise ioerror("not a valid .pgd file") fileversion = stream.readint16() if fileversion != fileversion: raise ioerror("unrecognised .pgd file version") while not fh.atend(): self.readitemfromstream(stream) except ioerror as e: qmessagebox.warning(self, "page designer -- open error", "failed to open {0}: {1}".format(self.filename, e)) finally: if fh is not none: fh.close() global dirty dirty = false def save(self): if not self.filename: path = "." fname,filetype = qfiledialog.getsavefilename(self, "page designer - save as", path, "page designer files (*.pgd)") if not fname: return self.filename = fname fh = none try: fh = qfile(self.filename) if not fh.open(qiodevice.writeonly): raise ioerror(str(fh.errorstring())) self.scene.clearselection() stream = qdatastream(fh) stream.setversion(qdatastream.qt_5_7) stream.writeint32(magicnumber) stream.writeint16(fileversion) for item in self.scene.items(): self.writeitemtostream(stream, item) except ioerror as e: qmessagebox.warning(self, "page designer -- save error", "failed to save {0}: {1}".format(self.filename, e)) finally: if fh is not none: fh.close() global dirty dirty = false def readitemfromstream(self, stream, offset=0): type = "" position = qpointf() matrix = qtransform() rotateangle=0#add by yangrongdong type=stream.readqstring() stream >> position >> matrix if offset: position += qpointf(offset, offset) if type == "text": text = "" font = qfont() text=stream.readqstring() stream >> font rotateangle=stream.readfloat() tx=textitem(text, position, self.scene, font, matrix) tx.setrotation(rotateangle) elif type == "box": rect = qrectf() stream >> rect style = qt.penstyle(stream.readint16()) rotateangle=stream.readfloat() bx=boxitem(position, self.scene, style, rect, matrix) bx.setrotation(rotateangle) elif type == "pixmap": pixmap = qpixmap() stream >> pixmap rotateangle=stream.readfloat() px=self.createpixmapitem(pixmap, position, matrix) px.setrotation(rotateangle) def writeitemtostream(self, stream, item): if isinstance(item, textitem): stream.writeqstring("text") stream<<item.pos()<< item.transform() stream.writeqstring(item.toplaintext()) stream<< item.font() stream.writefloat(item.rotation())#add by yangrongdong elif isinstance(item, graphicspixmapitem): stream.writeqstring("pixmap") stream << item.pos() << item.transform() << item.pixmap() stream.writefloat(item.rotation())#add by yangrongdong elif isinstance(item, boxitem): stream.writeqstring("box") stream<< item.pos() << item.transform() << item.rect stream.writeint16(item.style) stream.writefloat(item.rotation())#add by yangrongdong app = qapplication(sys.argv) form = mainform() rect = qapplication.desktop().availablegeometry() form.resize(int(rect.width() * 0.6), int(rect.height() * 0.9)) form.show() app.exec_()
运行结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 二项式反演/minmax容斥初探
下一篇: java设计模式--代理模式