from PyQt5.QtWidgets import QApplication, QTableView, QDialog, QPushButton, QVBoxLayout
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex
import pandas as pd

class DataFrameModel(QAbstractTableModel):
    def __init__(self, df):
        super(DataFrameModel, self).__init__()
        self._df = df

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            value = self._df.iloc[index.row(), index.column()]
            return str(value)
        return None

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

    def columnCount(self, index=QModelIndex()):
        return len(self._df.columns)

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole:
            self._df.iloc[index.row(), index.column()] = value
            self.dataChanged.emit(index, index, [Qt.DisplayRole])
            return True
        return False

    def flags(self, index):
        return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable

    def emitDataChanged(self):
        top_left = self.index(0, 0)
        bottom_right = self.index(self.rowCount() - 1, self.columnCount() - 1)
        self.dataChanged.emit(top_left, bottom_right, [Qt.DisplayRole])

class MyDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.table = QTableView()

        # Create a pandas DataFrame
        data = {
            'A': [1, 4, 7],
            'B': [2, 5, 8],
            'C': [3, 6, 9]
        }
        df = pd.DataFrame(data)
        self.model = DataFrameModel(df)
        self.table.setModel(self.model)

        # Add a button to update data
        self.update_button = QPushButton("Update Data")
        self.update_button.clicked.connect(self.update_data)

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        layout.addWidget(self.update_button)

        self.setLayout(layout)

    def update_data(self):
        # Modify the data in the DataFrame
        #self.model._df.at[0, 'A'] = 99
        #self.model._df.at[1, 'B'] = 88
        #self.model._df.at[2, 'C'] = 77

        data = {
            'A': [1111, 4, 7],
            'B': [2, 5, 8],
            'C': [3, 6, 9]
        }
        new_df = pd.DataFrame(data)

        self.model._df = new_df 
        # Emit dataChanged on all cells
        self.model.emitDataChanged()

if __name__ == '__main__':
    app = QApplication([])
    dialog = MyDialog()
    dialog.show()
    app.exec_()
