数据可视化 第4章
第4章 添加表格QTableView
1.添加table_model.py,里面子类化QAbstractTableModel,实现自定义table model
from PySide2.QtCore import Qt, QAbstractTableModel, QModelIndex
from PySide2.QtGui import QColor
#实现CustromTableModel类
class CustomTableModel(QAbstractTableModel):
def __init__(self, data=None):
QAbstractTableModel.__init__(self)
self.load_data(data)
def load_data(self, data):
self.input_datas = data[0].values
self.input_magnitudes = data[1].values
self.column_count = 2
self.row_count = len(self.input_magnitudes)
def rowCount(self, parent=QModelIndex()):
return self.row_count
def columnCount(self, parent=QModelIndex()):
return self.column_count
def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return ("Date", "Magnitude")[section]
else:
return "{}".format(section)
def data(self, index, role=Qt.DisplayRole):
column = index.column()
row = index.row()
if role == Qt.DisplayRole:
if column == 0:
raw_data = self.input_datas[row]
data = "{}".format(raw_data.toPython())
return data[:-3]
elif column == 1:
return "{:.2f}".format(self.input_magnitudes[row])
elif role == Qt.BackgroundRole:
return QColor(Qt.white)
elif role == Qt.TextAlignmentRole:
return Qt.AlignRight
return None
2.添加main_widget.py,使用QTableView+TableModel显示表格,设置widget布局,自适应窗口
from PySide2.QtWidgets import (QHBoxLayout, QHeaderView, QSizePolicy, QTableView, QWidget)
from table_model import *
#含TableView的窗口类
class Widget(QWidget):
def __init__(self, data):
QWidget.__init__(self)
#获取model
self.model = CustomTableModel(data)
#创建QTableView
self.table_view = QTableView()
self.table_view.setModel(self.model)
#QTableView 表头自适应以及拉伸
self.horizontal_header = self.table_view.horizontalHeader()
self.vertical_header = self.table_view.verticalHeader()
self.horizontal_header.setSectionResizeMode(QHeaderView.ResizeToContents)
self.vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
self.horizontal_header.setStretchLastSection(True)
#布局
self.main_layout = QHBoxLayout()
size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
#应用size策略
size.setHorizontalStretch(1)
self.table_view.setSizePolicy(size)
self.main_layout.addWidget(self.table_view)
#应用布局
self.setLayout(self.main_layout)
3.添加main_window.py,在主窗口里使用定制好的widget
from PySide2.QtCore import Slot, qApp
from PySide2.QtGui import QKeySequence
from PySide2.QtWidgets import QMainWindow, QAction, QApplication
#主窗口
class MainWindow(QMainWindow):
def __init__(self, widget):
QMainWindow.__init__(self)
self.setWindowTitle("地震信息")
self.setCentralWidget(widget)
# Menu
self.menu = self.menuBar()
self.file_menu = self.menu.addMenu("文件")
# Exit QAction
exit_action = QAction("退出", self)
exit_action.setShortcut(QKeySequence.Quit)
exit_action.triggered.connect(self.close)
self.file_menu.addAction(exit_action)
# Status Bar
self.status = self.statusBar()
self.status.showMessage("数据加载和绘制")
# Window dimensions
geometry = qApp.desktop().availableGeometry(self)
self.setFixedSize(geometry.width() * 0.6, geometry.height() * 0.4)
4.添加chapter4.py,这是我们要运行的py文件,读取命令行参数,解析csv文件,将data数据传递给窗口显示
import sys, argparse
import pandas as pd
from PySide2.QtCore import QDateTime, QTimeZone
from main_widget import Widget
from main_window import MainWindow
from PySide2.QtWidgets import QApplication
def transform_date(utc, timezone=None):
utc_fmt = "yyyy-MM-ddTHH:mm:ss.zzzZ"
new_date = QDateTime().fromString(utc, utc_fmt)
# print (new_date.toString(utc_fmt))
if timezone:
new_date.setTimeZone(timezone)
return new_date
def read_data(fname):
df = pd.read_csv(fname)
#移除错误的mag
df = df.drop(df[df.mag < 0].index)
magnitudes = df["mag"]
#本地时区
timezone = QTimeZone(b"Asia/Beijing")
#将时间戳转换为本地时区
times = df["time"].apply(lambda x: transform_date(x, timezone))
return times, magnitudes
if __name__ == "__main__":
options = argparse.ArgumentParser()
options.description = "窗口显示csv信息"
options.add_argument("-f", "--file", type=str, required=True, help="CSV文件路径")
args = options.parse_args()
data = read_data(args.file)
# print (data)
#qt 应用
app = QApplication(sys.argv)
widget = Widget(data)
window = MainWindow(widget)
window.show()
sys.exit(app.exec_())
5.运行效果