PYTHON3+PYQT5 Customizing views

Source: Internet
Author: User
This article is mainly for you to introduce the PYTHON3+PYQT5 custom view of the relevant information, with a certain reference value, interested in small partners can refer to

Several view classes provided by PYQT can work well, including Qlisview,qtableview and Qtreeview. But for some difficult to present data in existing ways, you can create our own view subclasses and use them as a visualization of model data to solve this problem. In this paper, 16 chapters of the Python Qt GUI rapid programming are implemented by PYTHON3+PYQT5.

#!/usr/bin/env python3import gzipimport osimport platformimport sysfrom pyqt5.qtcore import (QAbstractTableModel, Qdatetime, Qmodelindex, Qsize, Qtimer, Qvariant, qt,pyqtsignal) from Pyqt5.qtgui import (Qcolor, Qcursor, QFont, QFo Ntdatabase, Qfontmetrics, Qpainter, Qpalette, Qpixmap) from pyqt5.qtwidgets import Qapplication,qdialog,qhboxlayout, Qlabel, Qmessagebox,qscrollarea, Qsplitter, Qtableview,qwidget (TIMESTAMP, temperature, Inletflow, TURBIDITY, Conductivity, coagulation, rawph, FLOCCULATEDPH) = Range (8) Timestampformat = "Yyyy-mm-dd hh:mm" class Waterqualitymodel ( Qabstracttablemodel): Def __init__ (self, filename): Super (Waterqualitymodel, self). __init__ () Self.filename = Filen Ame self.results = [] def load (self): Self.beginresetmodel () exception = None fh = None Try:if not s Elf.filename:raise IOError ("No filename specified for loading") Self.results = [] Line_data = Gzip.open ( Self.filename). Read () for line in Line_data.decodE ("UTF8"). Splitlines (): Parts = Line.rstrip (). Split (",") date = Qdatetime.fromstring (Parts[0] + ": 00",        Qt.isodate) result = [Date] for part in Parts[1:]: Result.append (float (part))         Self.results.append (Result) except (IOError, valueerror) as E:exception = e finally:if fh is not None: Fh.close () Self.endresetmodel () If exception is isn't none:raise exception def data (self, index, Role=qt.displayrole): if (not index.isvalid () or not (0 <= index.row () < Len (self.results)): Return QV Ariant () column = Index.column () result = Self.results[index.row ()] if role = = Qt.DisplayRole:item = Result [column] If column = = TIMESTAMP: #item = item.tostring (Timestampformat) Item=item else: #it EM = QString ("%1"). Arg (item, 0, "F", 2) item = "{0:.2f}". Format (item) return item elif role = = Qt.textalign Mentrole:if column ! = Timestamp:return qvariant (int (qt.alignright| Qt.alignvcenter)) return qvariant (int (qt.alignleft| qt.alignvcenter)) elif role = = qt.textcolorrole and column = Inletflow:if Result[column] < 0:return Q Variant (Qcolor (qt.red)) elif (role = = qt.textcolorrole and column in (RAWPH, FLOCCULATEDPH)): ph = Result[co Lumn] If ph < 7:return qvariant (Qcolor (qt.red)) elif ph >= 8:return qvariant (Qcolor (Qt.blu e)) Else:return qvariant (Qcolor (Qt.darkgreen)) return qvariant () def headerdata (self, section, Orientatio N, Role=qt.displayrole): if role = = Qt.TextAlignmentRole:if Orientation = = Qt.Horizontal:return Qvariant ( Int (qt.aligncenter)) return qvariant (int (qt.alignright|  Qt.alignvcenter)) if role! = Qt.DisplayRole:return Qvariant () if orientation = = Qt.Horizontal:if section = = Timestamp:return "TIMESTAMP" elif section = = Temperature:return "\u00b0"+" C "elif section = = Inletflow:return" Inflow "elif section = = Turbidity:return" NTU "Eli F section = = Conductivity:return "\u03bcs/cm" elif sections = = Coagulation:return "mg/l" elif sec tion = = Rawph:return "Raw Ph" elif section = = Flocculatedph:return "Floc Ph" return int (sections + 1) def rowCount (self, Index=qmodelindex ()): Return Len (self.results) def columnCount (self, Index=qmodelindex ()): R Eturn 8class Waterqualityview (qwidget): clicked = Pyqtsignal (qmodelindex) Flowchars = (Chr (0X21DC), Chr (0X21DD), Chr (0x2 1C9)) def __init__ (self, Parent=none): Super (Waterqualityview, self). __init__ (parent) Self.scrollarea = None sel F.model = None self.setfocuspolicy (qt.strongfocus) Self.selectedrow = 1 Self.flowfont = Self.font () size = SE  Lf.font (). Pointsize () if platform.system () = = "Windows": Fontdb = Qfontdatabase () for Face in [Face.tolower () For Fontdb.famiLies ()]: If Face.contains ("Unicode"): Self.flowfont = Qfont (face, size) break else:s Elf.flowfont = Qfont ("symbol", size) Waterqualityview.flowchars = (Chr (0xAC), Chr (0xAE), Chr ( 0xDE) def setmodel (self, model): Self.model = Model #self. Connect (Self.model, # SIGNAL ("DataChanged (Qmodelin Dex,qmodelindex) "), # Self.setnewsize) self.model.dataChanged.connect (self.setnewsize) #self. Connect (Self.mode L, SIGNAL ("Modelreset ()"), Self.setnewsize) Self.model.modelReset.connect (self.setnewsize) self.setnewsize () def SE Tnewsize (self): Self.resize (Self.sizehint ()) self.update () self.updategeometry () def minimumsizehint (self): s ize = self.sizehint () fm = Qfontmetrics (Self.font ()) Size.setheight (Fm.height () * 3) return size def sizehint (SE           LF): fm = Qfontmetrics (Self.font ()) size = Fm.height () return qsize (Fm.width ("9999-99-99 99:99") + (Size * 4), (SIZE/4) + (size * Self.model.rowCount ()) def paintevent (Self, event): If Self.model is none:return fm = qfontmetrics (sel F.font ()) Timestampwidth = Fm.width ("9999-99-99 99:99") size = Fm.height () indicatorsize = int (size * 0.8) of fset = Int (1.5 * (size-indicatorsize)) Miny = Event.rect (). Y () Maxy = Miny + event.rect (). Height () + size Miny -= size painter = Qpainter (self) painter.setrenderhint (qpainter.antialiasing) painter.setrenderhint (qpainter.text antialiasing) y = 0 for row in range (Self.model.rowCount ()): x = 0 if miny <= y <= maxy:pain Ter.save () Painter.setpen (Self.palette (). Color (Qpalette.text)) if row = = Self.selectedRow:painter. FillRect (x, y + (offset * 0.8), self.width (), size, Self.palette (). Highlight ()) Painter.setpen (self. Palette (). Color (qpalette.highlightedtext)) #timestamp = Self.model.data (#self. Model.index (row, TIMESTAMP)). ToDateTime () timestamp = Self.model.data (Self.model.index (row, timestamp)) Painter.drawtext (x, y + size,        Timestamp.tostring (Timestampformat)) #print (timestamp.tostring (Timestampformat)) x + = Timestampwidth Temperature = Self.model.data (Self.model.index (row, temperature)) #temperature = Temperature.todo              Uble () [0] temperature = float (temperature) if temperature < 20:color = Qcolor (0, 0, Int (255 * (20-temperature)/)) Elif temperature > 25:color = qcolor (int (255 * temperature/100 ), 0, 0) else:color = qcolor (0, int (255 * temperature/100), 0) Painter.setpen (qt.nopen) p Ainter.setbrush (color) painter.drawellipse (x, y + offset, indicatorsize, indicatorsize) x + = Size RAWPH = Self.model.data (Self.model.index (row, rawph)) #rawPh = rawph.todouble () [0] rawph = Flo at (RAWPH) if RawPH < 7:color = Qcolor (int (255 * RAWPH/10), 0, 0) elif rawph >= 8:color = qcolor (0, 0, in        T (255 * RAWPH/10)) Else:color = Qcolor (0, int (255 * RAWPH/10), 0) Painter.setbrush (color) Painter.drawellipse (x, y + offset, indicatorsize, indicatorsize) x + = size FLOCPH = Self . Model.data (Self.model.index (row, FLOCCULATEDPH)) #flocPh = flocph.todouble () [0] flocph = float (          FLOCPH) If flocph < 7:color = Qcolor (int (255 * FLOCPH/10), 0, 0) elif flocph >= 8: color = Qcolor (0, 0, int (255 * FLOCPH/10)) Else:color = Qcolor (0, int (255 * FLOCPH/10), 0) p Ainter.setbrush (color) painter.drawellipse (x, y + offset, indicatorsize, indicatorsize) Pai Nter.restore () Painter.save () x + = Size flow = Self.model.data (Self.model.index (Row, INLE Tflow)) #flow = fLow.todouble () [0] flow = float (flow) char = None if flow <= 0:char = Waterqualityview.fl Owchars[0] Elif Flow < 3.6:char = Waterqualityview.flowchars[1] Elif flow > 4.7:ch AR = waterqualityview.flowchars[2] If char is not None:painter.setFont (Self.flowfont) painter.dr Awtext (x, y + size, char) painter.restore () y + = size if y > Maxy:break def mousepressevent (s Elf, event): fm = Qfontmetrics (Self.font ()) Self.selectedrow = Event.y ()//Fm.height () self.update () #self. em It (SIGNAL ("clicked (Qmodelindex)"), # Self.model.index (self.selectedrow, 0)) Self.clicked.emit (Self.model.index (s Elf.selectedrow, 0)) def keypressevent (Self, event): If Self.model is None:return row =-1 if Event.key () = = Qt.Key_Up:row = Max (0, self.selectedrow-1) elif event.key () = = Qt.Key_Down:row = Min (self.selectedrow + 1, Self.model.rowCount()-1) if row! =-1 and row! = Self.selectedRow:self.selectedRow = Row If Self.scrollarea is not None: FM = Qfontmetrics (Self.font ()) y = fm.height () * Self.selectedrow print (y) Self.scrollarea.ensureV Isible (0, y) self.update () #self. Emit (SIGNAL ("clicked (Qmodelindex)"), # Self.model.index (Self.selectedr ow, 0)) Self.clicked.emit (Self.model.index (self.selectedrow, 0)) else:QWidget.keyPressEvent (self, event) Clas S MainForm (qdialog): Def __init__ (self, Parent=none): Super (MainForm, self). __init__ (parent) Self.model = waterqual Itymodel (Os.path.join (Os.path.dirname (__file__), "waterdata.csv.gz")) Self.tableview = Qtableview () self.tab Leview.setalternatingrowcolors (True) Self.tableView.setModel (self.model) Self.waterview = Waterqualityview () Self . Waterview.setmodel (Self.model) Scrollarea = Qscrollarea () scrollarea.setbackgroundrole (QPalette.Light) scrollAre A.setwidget (Self.waterviEW) Self.waterView.scrollarea = Scrollarea Splitter = qsplitter (qt.horizontal) splitter.addwidget (Self.tableview) Splitter.addwidget (Scrollarea) splitter.setsizes ([+]) layout = Qhboxlayout () layout.addwidget (splitter ) self.setlayout (layout) self.setwindowtitle ("Water quality Data") qtimer.singleshot (0, self.initialload) def in Itialload (self): Qapplication.setoverridecursor (Qcursor (qt.waitcursor)) Splash = Qlabel (self) pixmap = qpixmap (os     . Path.join (Os.path.dirname (__file__), "iss013-e-14802.jpg")) #print (Os.path.join (Os.path.dirname (__file__), #  "Iss013-e-14802.jpg")) Splash.setpixmap (pixmap) splash.setwindowflags (qt.splashscreen) Splash.move (self.x () + ((Self.width ()-pixmap.width ())/2), SELF.Y () + ((Self.height ()-pixmap.height ())/2)) Splash.show () Q Application.processevents () try:self.model.load () except IOError as e:qmessagebox.warning (self, "water Q Uality-error ", E) ELse:self.tableView.resizeColumnsToContents () Splash.close () qapplication.processevents () Qapplication.resto Reoverridecursor () app = Qapplication (sys.argv) Form = MainForm () form.resize (850, 620) form.show () app.exec_ ()

Operation Result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.