I'm currently working on a user interface for my Python program with PyQt5 and feel a little lost. I hope you could help me.
The output of my program is a dataframe like in this example.
df = pd.DataFrame({'A': ['AAAAAAAA11111111', 'xyz', 'xyz'],
'B': ['BBBBBBBB11111111', 'xyz', 'xyz'],
'C': ['CCCCCCCC11111111', 'xyz', 'xyz'],
'D': ['CCCCCCCC11111111', 'xyz', 'xyz']})
My goal is to display this dataframe in a user interface. The columns should dynamically adapt to the size of the user interface (as in the grid layout).
Since there are already many contributions to the topic, I have already looked at some examples. Like this one for example.
#https://www.youtube.com/watch?v=hJEQEECZSH0
import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtCore import QAbstractTableModel, Qt
df = pd.DataFrame({'A': ['AAAAAAAA11111111', 'xyz', 'xyz'],
'B': ['BBBBBBBB11111111', 'xyz', 'xyz'],
'C': ['CCCCCCCC11111111', 'xyz', 'xyz'],
'D': ['CCCCCCCC11111111', 'xyz', 'xyz']})
class pandasModel(QAbstractTableModel):
def __init__(self, data):
QAbstractTableModel.__init__(self)
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parent=None):
return self._data.shape[1]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
return None
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
return None
if __name__ == '__main__':
app = QApplication(sys.argv)
model = pandasModel(df)
view = QTableView()
view.setModel(model)
view.resize(800, 600)
view.show()
sys.exit(app.exec_())
The program works, but I don't understand how I can dynamically adjust the width of the columns to the width of the user interface.
I would be very grateful for a few tips.