python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
程序员文章站
2023-12-16 20:25:04
本文通过将同一个数据集在三种不同的简便项窗口部件中显示。三个窗口的数据得到实时的同步,数据和视图分离。当添加或删除数据行,三个不同的视图均保持同步。数据将保存在本地文件中,...
本文通过将同一个数据集在三种不同的简便项窗口部件中显示。三个窗口的数据得到实时的同步,数据和视图分离。当添加或删除数据行,三个不同的视图均保持同步。数据将保存在本地文件中,而非数据库。对于小型和临时性数据集来说,这些简便窗口部件非常有用,可以用在非单独数据集中-数据自身的显示,编辑和存储。
所使用的数据集:
/home/yrd/eric_workspace/chap14/ships_conv/ships.py
#!/usr/bin/env python3 import platform from pyqt5.qtcore import qdatastream, qfile,qiodevice,qt from pyqt5.qtwidgets import qapplication name, owner, country, description, teu = range(5) magic_number = 0x570c4 file_version = 1 class ship(object): def __init__(self, name, owner, country, teu=0, description=""): self.name = name self.owner = owner self.country = country self.teu = teu self.description = description def __hash__(self): return super(ship, self).__hash__() def __lt__(self, other): return bool(self.name.lower()<other.name.lower()) def __eq__(self, other): return bool(self.name.lower()==other.name.lower()) class shipcontainer(object): def __init__(self, filename=""): self.filename = filename self.dirty = false self.ships = {} self.owners = set() self.countries = set() def ship(self, identity): return self.ships.get(identity) def addship(self, ship): self.ships[id(ship)] = ship self.owners.add(str(ship.owner)) self.countries.add(str(ship.country)) self.dirty = true def removeship(self, ship): del self.ships[id(ship)] del ship self.dirty = true def __len__(self): return len(self.ships) def __iter__(self): for ship in self.ships.values(): yield ship def inorder(self): return sorted(self.ships.values()) def incountryownerorder(self): return sorted(self.ships.values(), key=lambda x: (x.country, x.owner, x.name)) def load(self): exception = none fh = none try: if not self.filename: raise ioerror("no filename specified for loading") fh = qfile(self.filename) if not fh.open(qiodevice.readonly): raise ioerror(str(fh.errorstring())) stream = qdatastream(fh) magic = stream.readint32() if magic != magic_number: raise ioerror("unrecognized file type") fileversion = stream.readint16() if fileversion != file_version: raise ioerror("unrecognized file type version") self.ships = {} while not stream.atend(): name = "" owner = "" country = "" description = "" name=stream.readqstring() owner=stream.readqstring() country=stream.readqstring() description=stream.readqstring() teu = stream.readint32() ship = ship(name, owner, country, teu, description) self.ships[id(ship)] = ship self.owners.add(str(owner)) self.countries.add(str(country)) self.dirty = false except ioerror as e: exception = e finally: if fh is not none: fh.close() if exception is not none: raise exception def save(self): exception = none fh = none try: if not self.filename: raise ioerror("no filename specified for saving") fh = qfile(self.filename) if not fh.open(qiodevice.writeonly): raise ioerror(str(fh.errorstring())) stream = qdatastream(fh) stream.writeint32(magic_number) stream.writeint16(file_version) stream.setversion(qdatastream.qt_5_7) for ship in self.ships.values(): stream.writeqstring(ship.name) stream.writeqstring(ship.owner) stream.writeqstring(ship.country) stream.writeqstring(ship.description) stream.writeint32(ship.teu) self.dirty = false except ioerror as e: exception = e finally: if fh is not none: fh.close() if exception is not none: raise exception def generatefakeships(): for name, owner, country, teu, description in ( ("emma m\u00e6rsk", "m\u00e6rsk line", "denmark", 151687, "<b>w\u00e4rtsil\u00e4-sulzer rta96-c</b> main engine," "<font color=green>109,000 hp</font>"), ("msc pamela", "msc", "liberia", 90449, "draft <font color=green>15m</font>"), ("colombo express", "hapag-lloyd", "germany", 93750, "main engine, <font color=green>93,500 hp</font>"), ("houston express", "norddeutsche reederei", "germany", 95000, "features a <u>twisted leading edge full spade rudder</u>. " "sister of <i>savannah express</i>"), ("savannah express", "norddeutsche reederei", "germany", 95000, "sister of <i>houston express</i>"), ("msc susanna", "msc", "liberia", 90449, ""), ("eleonora m\u00e6rsk", "m\u00e6rsk line", "denmark", 151687, "captain <i>hallam</i>"), ("estelle m\u00e6rsk", "m\u00e6rsk line", "denmark", 151687, "captain <i>wells</i>"), ("evelyn m\u00e6rsk", "m\u00e6rsk line", "denmark", 151687, "captain <i>byrne</i>"), ("georg m\u00e6rsk", "m\u00e6rsk line", "denmark", 97933, ""), ("gerd m\u00e6rsk", "m\u00e6rsk line", "denmark", 97933, ""), ("gjertrud m\u00e6rsk", "m\u00e6rsk line", "denmark", 97933, ""), ("grete m\u00e6rsk", "m\u00e6rsk line", "denmark", 97933, ""), ("gudrun m\u00e6rsk", "m\u00e6rsk line", "denmark", 97933, ""), ("gunvor m\u00e6rsk", "m\u00e6rsk line", "denmark", 97933, ""), ("cscl le havre", "danaos shipping", "cyprus", 107200, ""), ("cscl pusan", "danaos shipping", "cyprus", 107200, "captain <i>watts</i>"), ("xin los angeles", "china shipping container lines (cscl)", "*", 107200, ""), ("xin shanghai", "china shipping container lines (cscl)", "*", 107200, ""), ("cosco beijing", "costamare shipping", "greece", 99833, ""), ("cosco hellas", "costamare shipping", "greece", 99833, ""), ("cosco guangzho", "costamare shipping", "greece", 99833, ""), ("cosco ningbo", "costamare shipping", "greece", 99833, ""), ("cosco yantian", "costamare shipping", "greece", 99833, ""), ("cma cgm fidelio", "cma cgm", "france", 99500, ""), ("cma cgm medea", "cma cgm", "france", 95000, ""), ("cma cgm norma", "cma cgm", "bahamas", 95000, ""), ("cma cgm rigoletto", "cma cgm", "france", 99500, ""), ("arnold m\u00e6rsk", "m\u00e6rsk line", "denmark", 93496, "captain <i>morrell</i>"), ("anna m\u00e6rsk", "m\u00e6rsk line", "denmark", 93496, "captain <i>lockhart</i>"), ("albert m\u00e6rsk", "m\u00e6rsk line", "denmark", 93496, "captain <i>tallow</i>"), ("adrian m\u00e6rsk", "m\u00e6rsk line", "denmark", 93496, "captain <i>g. e. ericson</i>"), ("arthur m\u00e6rsk", "m\u00e6rsk line", "denmark", 93496, ""), ("axel m\u00e6rsk", "m\u00e6rsk line", "denmark", 93496, ""), ("nyk vega", "nippon yusen kaisha", "panama", 97825, ""), ("msc esthi", "msc", "liberia", 99500, ""), ("msc chicago", "offen claus-peter", "liberia", 90449, ""), ("msc bruxelles", "offen claus-peter", "liberia", 90449, ""), ("msc roma", "offen claus-peter", "liberia", 99500, ""), ("msc madeleine", "msc", "liberia", 107551, ""), ("msc ines", "msc", "liberia", 107551, ""), ("hannover bridge", "kawasaki kisen kaisha", "japan", 99500, ""), ("charlotte m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("clementine m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("columbine m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("cornelia m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("chicago express", "hapag-lloyd", "germany", 93750, ""), ("kyoto express", "hapag-lloyd", "germany", 93750, ""), ("clifford m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("sally m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("sine m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("skagen m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("sofie m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("sor\u00f8 m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("sovereing m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("susan m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("svend m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("svendborg m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("a.p. m\u00f8ller", "m\u00e6rsk line", "denmark", 91690, "captain <i>ferraby</i>"), ("caroline m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("carsten m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("chastine m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("cornelius m\u00e6rsk", "m\u00e6rsk line", "denmark", 91690, ""), ("cma cgm otello", "cma cgm", "france", 91400, ""), ("cma cgm tosca", "cma cgm", "france", 91400, ""), ("cma cgm nabucco", "cma cgm", "france", 91400, ""), ("cma cgm la traviata", "cma cgm", "france", 91400, ""), ("cscl europe", "danaos shipping", "cyprus", 90645, ""), ("cscl africa", "seaspan container line", "cyprus", 90645, ""), ("cscl america", "danaos shipping ", "cyprus", 90645, ""), ("cscl asia", "seaspan container line", "*", 90645, ""), ("cscl oceania", "seaspan container line", "*", 90645, "captain <i>baker</i>"), ("m\u00e6rsk seville", "blue star gmbh", "liberia", 94724, ""), ("m\u00e6rsk santana", "blue star gmbh", "liberia", 94724, ""), ("m\u00e6rsk sheerness", "blue star gmbh", "liberia", 94724, ""), ("m\u00e6rsk sarnia", "blue star gmbh", "liberia", 94724, ""), ("m\u00e6rsk sydney", "blue star gmbh", "liberia", 94724, ""), ("msc heidi", "msc", "panama", 95000, ""), ("msc rania", "msc", "panama", 95000, ""), ("msc silvana", "msc", "panama", 95000, ""), ("m\u00e6rsk stralsund", "blue star gmbh", "liberia", 95000, ""), ("m\u00e6rsk saigon", "blue star gmbh", "liberia", 95000, ""), ("m\u00e6rsk seoul", "blue star ship managment gmbh", "germany", 95000, ""), ("m\u00e6rsk surabaya", "offen claus-peter", "germany", 98400, ""), ("cma cgm hugo", "nsb niederelbe", "germany", 90745, ""), ("cma cgm vivaldi", "cma cgm", "bahamas", 90745, ""), ("msc rachele", "nsb niederelbe", "germany", 90745, ""), ("pacific link", "nsb niederelbe", "germany", 90745, ""), ("cma cgm carmen", "e r schiffahrt", "liberia", 89800, ""), ("cma cgm don carlos", "e r schiffahrt", "liberia", 89800, ""), ("cma cgm don giovanni", "e r schiffahrt", "liberia", 89800, ""), ("cma cgm parsifal", "e r schiffahrt", "liberia", 89800, ""), ("cosco china", "e r schiffahrt", "liberia", 91649, ""), ("cosco germany", "e r schiffahrt", "liberia", 89800, ""), ("cosco napoli", "e r schiffahrt", "liberia", 89800, ""), ("ym unison", "yang ming line", "*", 88600, ""), ("ym utmost", "yang ming line", "*", 88600, ""), ("msc lucy", "msc", "panama", 89954, ""), ("msc maeva", "msc", "panama", 89954, ""), ("msc rita", "msc", "panama", 89954, ""), ("msc busan", "offen claus-peter", "panama", 89954, ""), ("msc beijing", "offen claus-peter", "panama", 89954, ""), ("msc toronto", "offen claus-peter", "panama", 89954, ""), ("msc charleston", "offen claus-peter", "panama", 89954, ""), ("msc vittoria", "msc", "panama", 89954, ""), ("ever champion", "nsb niederelbe", "marshall islands", 90449, "captain <i>phillips</i>"), ("ever charming", "nsb niederelbe", "marshall islands", 90449, "captain <i>tonbridge</i>"), ("ever chivalry", "nsb niederelbe", "marshall islands", 90449, ""), ("ever conquest", "nsb niederelbe", "marshall islands", 90449, ""), ("ital contessa", "nsb niederelbe", "marshall islands", 90449, ""), ("lt cortesia", "nsb niederelbe", "marshall islands", 90449, ""), ("oocl asia", "oocl", "*", 89097, ""), ("oocl atlanta", "oocl", "*", 89000, ""), ("oocl europe", "oocl", "*", 89097, ""), ("oocl hamburg", "oocl", "marshall islands", 89097, ""), ("oocl long beach", "oocl", "marshall islands", 89097, ""), ("oocl ningbo", "oocl", "marshall islands", 89097, ""), ("oocl shenzhen", "oocl", "*", 89097, ""), ("oocl tianjin", "oocl", "marshall islands", 89097, ""), ("oocl tokyo", "oocl", "*", 89097, "")): yield ship(name, owner, country, teu, description)
/home/yrd/eric_workspace/chap14/ships_conv/ships-dict.pyw
#!/usr/bin/env python3 import sys from pyqt5.qtcore import qfile, qtimer, qt from pyqt5.qtwidgets import (qapplication, qdialog, qhboxlayout, qlabel, qlistwidget, qlistwidgetitem, qmessagebox, qpushbutton, qsplitter, qtablewidget, qtablewidgetitem, qtreewidget, qtreewidgetitem, qvboxlayout, qwidget) import ships mac = true try: from pyqt5.qtgui import qt_mac_set_native_menubar except importerror: mac = false class mainform(qdialog): def __init__(self, parent=none): super(mainform, self).__init__(parent) listlabel = qlabel("&list") self.listwidget = qlistwidget() listlabel.setbuddy(self.listwidget) tablelabel = qlabel("&table") self.tablewidget = qtablewidget() tablelabel.setbuddy(self.tablewidget) treelabel = qlabel("tre&e") self.treewidget = qtreewidget() treelabel.setbuddy(self.treewidget) addshipbutton = qpushbutton("&add ship") removeshipbutton = qpushbutton("&remove ship") quitbutton = qpushbutton("&quit") if not mac: addshipbutton.setfocuspolicy(qt.nofocus) removeshipbutton.setfocuspolicy(qt.nofocus) quitbutton.setfocuspolicy(qt.nofocus) splitter = qsplitter(qt.horizontal) vbox = qvboxlayout() vbox.addwidget(listlabel) vbox.addwidget(self.listwidget) widget = qwidget() widget.setlayout(vbox) splitter.addwidget(widget) vbox = qvboxlayout() vbox.addwidget(tablelabel) vbox.addwidget(self.tablewidget) widget = qwidget() widget.setlayout(vbox) splitter.addwidget(widget) vbox = qvboxlayout() vbox.addwidget(treelabel) vbox.addwidget(self.treewidget) widget = qwidget() widget.setlayout(vbox) splitter.addwidget(widget) buttonlayout = qhboxlayout() buttonlayout.addwidget(addshipbutton) buttonlayout.addwidget(removeshipbutton) buttonlayout.addstretch() buttonlayout.addwidget(quitbutton) layout = qvboxlayout() layout.addwidget(splitter) layout.addlayout(buttonlayout) self.setlayout(layout) self.tablewidget.itemchanged[qtablewidgetitem].connect(self.tableitemchanged) addshipbutton.clicked.connect(self.addship) removeshipbutton.clicked.connect(self.removeship) quitbutton.clicked.connect(self.accept) self.ships = ships.shipcontainer("ships.dat") self.setwindowtitle("ships (dict)") qtimer.singleshot(0, self.initialload) def initialload(self): if not qfile.exists(self.ships.filename): for ship in ships.generatefakeships(): self.ships.addship(ship) self.ships.dirty = false else: try: self.ships.load() except ioerror as e: qmessagebox.warning(self, "ships - error", "failed to load: {0}".format(e)) self.populatelist() self.populatetable() self.tablewidget.sortitems(0) self.populatetree() def reject(self): self.accept() def accept(self): if (self.ships.dirty and qmessagebox.question(self, "ships - save?", "save unsaved changes?", qmessagebox.yes|qmessagebox.no) == qmessagebox.yes): try: self.ships.save() except ioerror as e: qmessagebox.warning(self, "ships - error", "failed to save: {0}".format(e)) qdialog.accept(self) def populatelist(self, selectedship=none): selected = none self.listwidget.clear() for ship in self.ships.inorder(): item = qlistwidgetitem("{0} of {1}/{2} ({3:,})".format(ship.name,ship.owner,ship.country,int(ship.teu))) self.listwidget.additem(item) if selectedship is not none and selectedship == id(ship): selected = item if selected is not none: selected.setselected(true) self.listwidget.setcurrentitem(selected) def populatetable(self, selectedship=none): selected = none self.tablewidget.clear() self.tablewidget.setsortingenabled(false) self.tablewidget.setrowcount(len(self.ships)) headers = ["name", "owner", "country", "description", "teu"] self.tablewidget.setcolumncount(len(headers)) self.tablewidget.sethorizontalheaderlabels(headers) for row, ship in enumerate(self.ships): item = qtablewidgetitem(ship.name) item.setdata(qt.userrole, id(ship)) if selectedship is not none and selectedship == id(ship): selected = item self.tablewidget.setitem(row, ships.name, item) self.tablewidget.setitem(row, ships.owner, qtablewidgetitem(ship.owner)) self.tablewidget.setitem(row, ships.country, qtablewidgetitem(ship.country)) self.tablewidget.setitem(row, ships.description, qtablewidgetitem(ship.description)) item = qtablewidgetitem("{0:>8}".format(ship.teu)) item.settextalignment(qt.alignright|qt.alignvcenter) self.tablewidget.setitem(row, ships.teu, item) self.tablewidget.setsortingenabled(true) self.tablewidget.resizecolumnstocontents() if selected is not none: selected.setselected(true) self.tablewidget.setcurrentitem(selected) def populatetree(self, selectedship=none): selected = none self.treewidget.clear() self.treewidget.setcolumncount(2) self.treewidget.setheaderlabels(["country/owner/name", "teu"]) self.treewidget.setitemsexpandable(true) parentfromcountry = {} parentfromcountryowner = {} for ship in self.ships.incountryownerorder(): ancestor = parentfromcountry.get(ship.country) if ancestor is none: ancestor = qtreewidgetitem(self.treewidget, [ship.country]) parentfromcountry[ship.country] = ancestor countryowner = ship.country + "/" + ship.owner parent = parentfromcountryowner.get(countryowner) if parent is none: parent = qtreewidgetitem(ancestor, [ship.owner]) parentfromcountryowner[countryowner] = parent item = qtreewidgetitem(parent, [ship.name,"{0}".format(ship.teu)]) item.settextalignment(1, qt.alignright|qt.alignvcenter) if selectedship is not none and selectedship == id(ship): selected = item self.treewidget.expanditem(parent) self.treewidget.expanditem(ancestor) self.treewidget.resizecolumntocontents(0) self.treewidget.resizecolumntocontents(1) if selected is not none: selected.setselected(true) self.treewidget.setcurrentitem(selected) print(parentfromcountry) print(parentfromcountryowner) def addship(self): ship = ships.ship(" unknown", " unknown", " unknown") self.ships.addship(ship) self.populatelist() self.populatetree() self.populatetable(id(ship)) self.tablewidget.setfocus() self.tablewidget.edititem(self.tablewidget.currentitem()) def tableitemchanged(self, item): ship = self.currenttableship() if ship is none: return column = self.tablewidget.currentcolumn() if column == ships.name: ship.name = item.text().strip() elif column == ships.owner: ship.owner = item.text().strip() elif column == ships.country: ship.country = item.text().strip() elif column == ships.description: ship.description = item.text().strip() elif column == ships.teu: ship.teu = item.text() self.ships.dirty = true self.populatelist() self.populatetree() def currenttableship(self): item = self.tablewidget.item(self.tablewidget.currentrow(), 0) if item is none: return none return self.ships.ship( item.data(qt.userrole)) def removeship(self): ship = self.currenttableship() if ship is none: return if (qmessagebox.question(self, "ships - remove", "remove {0} of {1}/{2}?".format(ship.name,ship.owner,ship.country), qmessagebox.yes|qmessagebox.no) == qmessagebox.no): return self.ships.removeship(ship) self.populatelist() self.populatetree() self.populatetable() app = qapplication(sys.argv) form = mainform() form.show() app.exec_()
运行结果:
以上这篇python3+pyqt5 使用三种不同的简便项窗口部件显示数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。