python3+PyQt5自定义视图详解


Posted in Python onApril 24, 2018

pyqt提供的几个视图类都可以较好工作,包括QLisView,QTableView和QTreeView。但是对于一些难以用现有的方式来呈现数据,这时,可以创建我们自己的视图子类并将其用做模型数据的可视化来解决这一问题。本文通过Python3+pyqt5实现了python Qt GUI 快速编程的16章的例子。

#!/usr/bin/env python3

import gzip
import os
import platform
import sys
from PyQt5.QtCore import (QAbstractTableModel, QDateTime, QModelIndex,
    QSize, QTimer, QVariant, Qt,pyqtSignal)
from PyQt5.QtGui import ( QColor, QCursor, QFont,
    QFontDatabase, 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 = filename
    self.results = []


  def load(self):
    self.beginResetModel()
    exception = None
    fh = None
    try:
      if not self.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 not None:
        raise exception


  def data(self, index, role=Qt.DisplayRole):
    if (not index.isValid() or
      not (0 <= index.row() < len(self.results))):
      return QVariant()
    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:
        #item = QString("%1").arg(item, 0, "f", 2)
        item = "{0:.2f}".format(item)
      return item
    elif role == Qt.TextAlignmentRole:
      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 QVariant(QColor(Qt.red))
    elif (role == Qt.TextColorRole and
       column in (RAWPH, FLOCCULATEDPH)):
      ph = result[column]
      if ph < 7:
        return QVariant(QColor(Qt.red))
      elif ph >= 8:
        return QVariant(QColor(Qt.blue))
      else:
        return QVariant(QColor(Qt.darkGreen))
    return QVariant()


  def headerData(self, section, orientation, 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"
      elif section == CONDUCTIVITY:
        return "\u03BCS/cm"
      elif section == COAGULATION:
        return "mg/L"
      elif section == RAWPH:
        return "Raw Ph"
      elif section == FLOCCULATEDPH:
        return "Floc Ph"
    return int(section + 1)


  def rowCount(self, index=QModelIndex()):
    return len(self.results)


  def columnCount(self, index=QModelIndex()):
    return 8


class WaterQualityView(QWidget):
  clicked = pyqtSignal(QModelIndex)
  FLOWCHARS = (chr(0x21DC), chr(0x21DD), chr(0x21C9))

  def __init__(self, parent=None):
    super(WaterQualityView, self).__init__(parent)
    self.scrollarea = None
    self.model = None
    self.setFocusPolicy(Qt.StrongFocus)
    self.selectedRow = -1
    self.flowfont = self.font()
    size = self.font().pointSize()
    if platform.system() == "Windows":
      fontDb = QFontDatabase()
      for face in [face.toLower() for face in fontDb.families()]:
        if face.contains("unicode"):
          self.flowfont = QFont(face, size)
          break
      else:
        self.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(QModelIndex,QModelIndex)"),
    #    self.setNewSize)
    self.model.dataChanged.connect(self.setNewSize)
    #self.connect(self.model, SIGNAL("modelReset()"), self.setNewSize)
    self.model.modelReset.connect(self.setNewSize)
    self.setNewSize()


  def setNewSize(self):
    self.resize(self.sizeHint())
    self.update()
    self.updateGeometry()


  def minimumSizeHint(self):
    size = self.sizeHint()
    fm = QFontMetrics(self.font())
    size.setHeight(fm.height() * 3)
    return size


  def sizeHint(self):
    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(self.font())
    timestampWidth = fm.width("9999-99-99 99:99 ")
    size = fm.height()
    indicatorSize = int(size * 0.8)
    offset = 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.TextAntialiasing)
    y = 0
    for row in range(self.model.rowCount()):
      x = 0
      if minY <= y <= maxY:
        painter.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.toDouble()[0]
        temperature = float(temperature)
        if temperature < 20:
          color = QColor(0, 0,
              int(255 * (20 - temperature) / 20))
        elif temperature > 25:
          color = QColor(int(255 * temperature / 100), 0, 0)
        else:
          color = QColor(0, int(255 * temperature / 100), 0)
        painter.setPen(Qt.NoPen)
        painter.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 = float(rawPh)
        if rawPh < 7:
          color = QColor(int(255 * rawPh / 10), 0, 0)
        elif rawPh >= 8:
          color = QColor(0, 0, int(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)
        painter.setBrush(color)
        painter.drawEllipse(x, y + offset, indicatorSize,
                  indicatorSize)
        painter.restore()
        painter.save()
        x += size
        flow = self.model.data(
            self.model.index(row, INLETFLOW))
        #flow = flow.toDouble()[0]
        flow = float(flow)
        char = None
        if flow <= 0:
          char = WaterQualityView.FLOWCHARS[0]
        elif flow < 3.6:
          char = WaterQualityView.FLOWCHARS[1]
        elif flow > 4.7:
          char = WaterQualityView.FLOWCHARS[2]
        if char is not None:
          painter.setFont(self.flowfont)
          painter.drawText(x, y + size, char)
        painter.restore()
      y += size
      if y > maxY:
        break


  def mousePressEvent(self, event):
    fm = QFontMetrics(self.font())
    self.selectedRow = event.y() // fm.height()
    self.update()
    #self.emit(SIGNAL("clicked(QModelIndex)"),
    #     self.model.index(self.selectedRow, 0))
    self.clicked.emit(self.model.index(self.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.ensureVisible(0, y)
      self.update()
      #self.emit(SIGNAL("clicked(QModelIndex)"),
      #     self.model.index(self.selectedRow, 0))
      self.clicked.emit(self.model.index(self.selectedRow, 0))
    else:
      QWidget.keyPressEvent(self, event)


class MainForm(QDialog):

  def __init__(self, parent=None):
    super(MainForm, self).__init__(parent)

    self.model = WaterQualityModel(os.path.join(
        os.path.dirname(__file__), "waterdata.csv.gz"))
    self.tableView = QTableView()
    self.tableView.setAlternatingRowColors(True)
    self.tableView.setModel(self.model)
    self.waterView = WaterQualityView()
    self.waterView.setModel(self.model)
    scrollArea = QScrollArea()
    scrollArea.setBackgroundRole(QPalette.Light)
    scrollArea.setWidget(self.waterView)
    self.waterView.scrollarea = scrollArea

    splitter = QSplitter(Qt.Horizontal)
    splitter.addWidget(self.tableView)
    splitter.addWidget(scrollArea)
    splitter.setSizes([600, 250])
    layout = QHBoxLayout()
    layout.addWidget(splitter)
    self.setLayout(layout)

    self.setWindowTitle("Water Quality Data")
    QTimer.singleShot(0, self.initialLoad)


  def initialLoad(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()
    QApplication.processEvents()
    try:
      self.model.load()
    except IOError as e:
      QMessageBox.warning(self, "Water Quality - Error", e)
    else:
      self.tableView.resizeColumnsToContents()
    splash.close()
    QApplication.processEvents()
    QApplication.restoreOverrideCursor()


app = QApplication(sys.argv)
form = MainForm()
form.resize(850, 620)
form.show()
app.exec_()

运行结果:

python3+PyQt5自定义视图详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python入门之三角函数全解【收藏】
Nov 08 Python
浅谈Python实现Apriori算法介绍
Dec 20 Python
Python2.7下安装Scrapy框架步骤教程
Dec 22 Python
python os用法总结
Jun 08 Python
Python快速查找list中相同部分的方法
Jun 27 Python
python实现嵌套列表平铺的两种方法
Nov 08 Python
django-allauth入门学习和使用详解
Jul 03 Python
如何基于Python制作有道翻译小工具
Dec 16 Python
python GUI库图形界面开发之PyQt5不规则窗口实现与显示GIF动画的详细方法与实例
Mar 09 Python
学python需要去培训机构吗
Jul 01 Python
python 如何实现遗传算法
Sep 22 Python
python使用pywinauto驱动微信客户端实现公众号爬虫
May 19 Python
python自动重试第三方包retrying模块的方法
Apr 24 #Python
python3+PyQt5泛型委托详解
Apr 24 #Python
python去除扩展名的实例讲解
Apr 23 #Python
python3 遍历删除特定后缀名文件的方法
Apr 23 #Python
将TensorFlow的模型网络导出为单个文件的方法
Apr 23 #Python
tensorflow1.0学习之模型的保存与恢复(Saver)
Apr 23 #Python
tensorflow 使用flags定义命令行参数的方法
Apr 23 #Python
You might like
冰滴咖啡制作步骤
2021/03/03 冲泡冲煮
PHP 出现乱码和Sessions验证问题的解决方法!
2008/12/06 PHP
将数组写入txt文件 var_export
2009/04/21 PHP
THINKPHP+JS实现缩放图片式截图的实现
2010/03/07 PHP
PHP中通过trigger_error触发PHP错误示例
2015/06/23 PHP
对textarea框的代码调试,而且功能上使用非常方便,酷
2006/06/30 Javascript
javascript学习(二)javascript常见问题总结
2013/01/02 Javascript
js获取html页面节点方法(递归方式)
2013/12/13 Javascript
javascript和jquery修改a标签的href属性
2013/12/16 Javascript
DOM基础教程之模型中的模型节点
2015/01/19 Javascript
常用DOM整理
2015/06/16 Javascript
详解AngularJS中的表达式使用
2015/06/16 Javascript
JavaScript的变量声明提升问题浅析(Hoisting)
2016/11/30 Javascript
bootstrap日历插件datetimepicker使用方法
2016/12/14 Javascript
JavaScript实现音乐自动切换和轮播
2017/11/05 Javascript
Linux Centos7.2下安装nodejs&amp;npm配置全局路径的教程
2018/05/15 NodeJs
mpvue 页面预加载新增preLoad生命周期的两种方式
2019/10/17 Javascript
JS实现的进制转换,浮点数相加,数字判断操作示例
2019/11/09 Javascript
用VsCode编辑TypeScript的实现方法
2020/05/07 Javascript
Java 生成随机字符的示例代码
2021/01/13 Javascript
windows系统下Python环境搭建教程
2017/03/28 Python
Python读取Word(.docx)正文信息的方法
2018/03/15 Python
python实现扫描ip地址的小程序
2019/04/16 Python
OpenCV 轮廓检测的实现方法
2019/07/03 Python
Python assert关键字原理及实例解析
2019/12/13 Python
Python打包模块wheel的使用方法与将python包发布到PyPI的方法详解
2020/02/12 Python
关于老式浏览器兼容HTML5和CSS3的问题
2016/06/01 HTML / CSS
adidas美国官网:adidas US
2016/09/21 全球购物
Kiehl’s科颜氏西班牙官方网站:源自美国的植物护肤品牌
2020/02/22 全球购物
亚马逊新加坡官方网站:Amazon.sg
2020/03/25 全球购物
医学生个人求职信范文
2013/09/24 职场文书
城市创卫标语
2014/06/17 职场文书
商家认证委托书格式
2014/10/16 职场文书
Redis高可用集群redis-cluster详解
2022/03/20 Redis
漫画《尖帽子的魔法工坊》宣布动画化
2022/04/06 日漫
vue2的 router在使用过程中遇到的一些问题
2022/04/13 Vue.js