Suppose I have the following dataframe:
df = {'Banana': {0: 1, 1: 2, 2: 5}, 'Apple': {0: 3, 1: 4, 2: 3}, 'Elderberry': {0: 5, 1: 4, 2: 1},
'Clementine': {0: 4, 1: 7, 2: 0}, 'Fig': {0: 1, 1: 9, 2: 3}}
Banana Apple Elderberry Clementine Fig
0 1 3 5 4 1
1 2 4 4 7 9
2 5 3 1 0 3
Which is passed to QAbstractTableModel
and displayed with QTableView
:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import Qt
import pandas as pd
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, model):
super().__init__()
self.model = model
self.table = QtWidgets.QTableView()
self.table.setModel(self.model)
self.setCentralWidget(self.table)
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def rowCount(self, index):
return self._data.shape[0]
def columnCount(self, index):
return self._data.shape[1]
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._data.columns[section])
if orientation == Qt.Vertical:
return str(self._data.index[section])
def data(self, index, role):
row = index.row()
column = index.column()
column_name = self._data.columns[column]
value = self._data.iloc[row, column]
if role == Qt.DisplayRole:
print(str(value))
return str(value)
app = QtWidgets.QApplication(sys.argv)
df = {'Banana': {0: 1, 1: 2, 2: 5}, 'Apple': {0: 3, 1: 4, 2: 3}, 'Elderberry': {0: 5, 1: 4, 2: 1}, 'Clementine': {0: 4, 1: 7, 2: 0}, 'Fig': {0: 1, 1: 9, 2: 3}}
data_model = TableModel(df)
window1 = MainWindow(data_model)
window1.resize(800, 400)
window1.show()
sys.exit(app.exec_())
I now want to create a separate window using QListView
, to display a list of df
column names, allowing me to specify which columns I want to appear in the above QTableView
. Like this:
If I uncheck a column in QListView
, I want that column to be removed from the QTableView
. Similarly if I check a column, that column should be added to the table view. The purpose of the list view is essentially to allow the user to specify which columns should appear in the table.
What is the best way of doing this? I imagine I could create a QListWidget
and use signals to update the QTableView
. However I am a bit reluctant to do this, as I imagine it could get very messy.
Is it therefore best practice to use QListView
, so that both widgets reference the same data model, and automatically talk to each other like this?