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?

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()
| improve this answer | |
  • I let the plugin run its course (loading all the layers) then, in the Python Console, I import PyQt4.QtGui and iface from qgis.utils. Fetch the current layer with cl = iface.mapCanvas().currentLayer(). Check that it's the right layer with cl.name(). Open the attribute table with iface.showAttributeTable(cl), which is showing me the attribute table in the map window. Run the at = [d for d in QApplication.instance().topLevelWidgets() if d.objectName() == u'QgsAttributeTableDialog'], which return a list. This list however is empty. What am I doing wrong here? – user28233 Mar 31 '14 at 12:36
  • Listing the object names of at = [d for d in QApplication.instance().topLevelWidgets()] i.e., without the condition for attribute tables there are around 90 objects but none are attribute tables. – user28233 Mar 31 '14 at 12:48
  • Maybe there is the object name "AttributeTable" in [d.objectName() for d in QApplication.instance().topLevelWidgets()]? – Matthias Kuhn Mar 31 '14 at 21:44
  • Yes. I was digging around using Python introspection Seen here and found that I could use QApplication.instance().allWidgets() to search for u'AttributeTable' With this I could use the 1st code tip I got. I.e., problem solved. – user28233 Apr 1 '14 at 10:01
  • 1
    I found out how to resize all the columns in the attribute table to their contents. Using attrTables[0].findChildren(QTableView)[0].resizeColumnsToContents(). Introspection is very helpful. @Matthias I'm unable to use the topLevelWidgets() to find the AttributeTable. It gives nothing. Perhaps you should include in the updated answer that one should use allWidgets(). – user28233 Apr 1 '14 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.