from PyQt5 import QtCore
from ui_files.pandas_table import Ui_PandasTV
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
[docs]class PandasTV:
def __init__(self, parent):
self.w_Pandas = QWidget()
self.pandasUI = Ui_PandasTV()
self.pandasUI.setupUi(self.w_Pandas)
# # Create main window object
# self.win = parent
# self.main_control = parent
# self.main_ui = parent.ppUI
[docs]class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, df = pd.DataFrame(), parent=None):
QtCore.QAbstractTableModel.__init__(self, parent=parent)
self._df = df
[docs] def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if orientation == QtCore.Qt.Horizontal:
try:
return self._df.columns.tolist()[section]
except (IndexError, ):
return QtCore.QVariant()
elif orientation == QtCore.Qt.Vertical:
try:
# return self.df.index.tolist()
return self._df.index.tolist()[section]
except (IndexError, ):
return QtCore.QVariant()
[docs] def data(self, index, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if not index.isValid():
return QtCore.QVariant()
return QtCore.QVariant(str(self._df.iloc[index.row(), index.column()]))
[docs] def setData(self, index, value, role):
row = self._df.index[index.row()]
col = self._df.columns[index.column()]
if hasattr(value, 'toPyObject'):
# PyQt4 gets a QVariant
value = value.toPyObject()
else:
# PySide gets an unicode
dtype = self._df[col].dtype
if dtype != object:
value = None if value == '' else dtype.type(value)
self._df.set_value(row, col, value)
return True
[docs] def rowCount(self, parent=QtCore.QModelIndex()):
return len(self._df.index)
[docs] def columnCount(self, parent=QtCore.QModelIndex()):
return len(self._df.columns)
[docs] def sort(self, column, order):
colname = self._df.columns.tolist()[column]
self.layoutAboutToBeChanged.emit()
self._df.sort_values(colname, ascending= order == QtCore.Qt.AscendingOrder, inplace=True)
self._df.reset_index(inplace=True, drop=True)
self.layoutChanged.emit()
# if __name__ == "__main__":
# import sys
# app = QtWidgets.QApplication(sys.argv)
# w = PandasWidget()
# w.w_Pandas.show()
# sys.exit(app.exec_())