Once I needed something similar and what I did was this:
To set the column auto-size behavior:
def focusChanged(old, new):
if isinstance(new, QTableView) and new.parent().parent().parent().parent().objectName().startswith('QgsAttributeTableDialog'):
header = new.horizontalHeader()
header.setSectionResizeMode(QHeaderView.ResizeToContents)
columns = [new.columnWidth(column) for column in range(header.count())]
header.setSectionResizeMode(QHeaderView.Interactive)
for id, width in enumerate(columns):
new.setColumnWidth(id, width)
app = QgsApplication.instance()
app.focusChanged.connect(focusChanged)
To unset it:
app.focusChanged.disconnect(focusChanged)
I couldn't find any signal that's send when an attribute table is open, so all what I found was the focusChanged
signal, so you'll need to focus the dialog to trigger the column auto-size. I took many ideas from this post.