It's possible to do that using TableView
and re-implemented QAbstractTableModel
. Instead of TableWidget.setColumn(col, array_items)
, You will call TableWidget.model().setColumn(col, array_items)
. In principle to have it working with TableWidget, You have to re-implement QTableWidget
class, but I found that unnecessary.
In my example I used pandas DataFrame as a data holder. You can set and get data using column name.
Here is fully working example:
import sys
import typing
import pandas as pd
from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QWidget, QGridLayout, QPushButton
class TableModel(QAbstractTableModel):
def __init__(self, table_data, parent=None):
super().__init__(parent)
self.table_data = table_data
def rowCount(self, parent: QModelIndex = ...) -> int:
return self.table_data.shape[0]
def columnCount(self, parent: QModelIndex = ...) -> int:
return self.table_data.shape[1]
def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
if role == Qt.DisplayRole:
return str(self.table_data.loc[index.row()][index.column()])
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return str(self.table_data.columns[section])
def setColumn(self, col, array_items):
"""Set column data"""
self.table_data[col] = array_items
# Notify table, that data has been changed
self.dataChanged.emit(QModelIndex(), QModelIndex())
def getColumn(self, col):
"""Get column data"""
return self.table_data[col]
if __name__ == "__main__":
app = QApplication(sys.argv)
win = QMainWindow()
widget = QWidget()
layout = QGridLayout()
widget.setLayout(layout)
table_data = pd.DataFrame(data={'col1': [1, 2, 3, 4, 5, 6, 7, 8], 'col2': [1, 2, 3, 4, 5, 6, 7, 8]})
table = QTableView()
table.setModel(TableModel(table_data=table_data))
layout.addWidget(table)
button = QPushButton("Set col1")
button.clicked.connect(lambda: table.model().setColumn("col1", [8, 7, 6, 5, 4, 3, 2, 1]))
button_2 = QPushButton("Read col1")
button_2.clicked.connect(lambda: print(table.model().getColumn("col1")))
layout.addWidget(button)
layout.addWidget(button_2)
win.setCentralWidget(widget)
win.show()
app.exec()