[GIS] Adjusting attribute table view column width using PyQGIS

attribute-tabledimensionspyqgiswidth

I'm programmatically opening the Attribute table via Python through a plugin. All of the columns have a default width, but some of the data that I'm using do not fit.

Default column width

It's not enough to be able to click the column separator to make the column re-size to fit the data as there are several columns and several layers.

Can I, through Python, change this in any way, or is my only option to create my own table in Qt?

Best Answer

from PyQt4.QtGui import QApplication, QTableView

# Get a list of all open attribute table dialogs
attrTables = [d for d in QApplication.instance().allWidgets() if d.objectName() == u'QgsAttributeTableDialog' or d.objectName() == u'AttributeTable' ]
# Set the column width for the first column in the first dialog to 200
attrTables[0].findChildren(QTableView)[0].setColumnWidth( 0, 200 )
# or instead set the width to match the contents maximum size
# attrTables[0].findChildren(QTableView)[0].resizeColumnsToContents()
Related Question