2

I use this code to initialize QgsAttributeTableView and hide some columns in it in my custom widget:

def __init__(self, layer, canvas, hidden_columns, cache_size=5000, parent=None):
    """Constructor."""
    super(SomeWidget, self).__init__(parent)
    self.setupUi(self)

    self._layer = layer
    self._canvas = canvas
    self._vector_layer_cache = QgsVectorLayerCache(self._layer, cache_size)
    self._attribute_table_model = QgsAttributeTableModel(self._vector_layer_cache)
    self._attribute_table_model.loadLayer()
    self._attribute_table_filter_model = QgsAttributeTableFilterModel(self._canvas, self._attribute_table_model)

    self._attribute_table_view.setModel(self._attribute_table_filter_model)
    self.setHidenColumns(hidden_columns)

def setHidenColumns(self, *args):
    self._config = self._layer.attributeTableConfig()
    columns = self._config.columns()
    for column in columns:
        if column.name in args:
            column.hidden = True
    self._config.setColumns(columns)
    self._attribute_table_view.setAttributeTableConfig(self._config)

But, no matter what, QgsAttributeTableView shows all the columns in the table. I try to apply self._config to self._layer, then add it to legend, open attribute table and everything works as expected (columns are hidden). That shows me that the config with hidden columns is correct. What is wrong with my approach?

2

Apparently, setting table config on QgsAttributeTableView has no effect on column visibility. I have to set the column config on QgsAttributeTableFilterModel. This works for me:

def setHidenColumns(self, *args):
    self._config = self._layer.attributeTableConfig()
    columns = self._config.columns()
    for column in columns:
        if column.name in args:
            column.hidden = True
    self._config.setColumns(columns)
    self._attribute_table_filter_model.setAttributeTableConfig(self._config)

EDIT

After examining source code of QgsDualView, the propper way is to set config on QgsAttributeTableView as well as on QgsAttributeTableFilterModel and QgsVectorLayer itself. So this is final version of my code:

def setHidenColumns(self, *args):
    self._config = self._layer.attributeTableConfig()
    columns = self._config.columns()
    for column in columns:
        if column.name in args:
            column.hidden = True
    self._config.setColumns(columns)
    self._layer.setAttributeTableConfig(self._config)
    self._attribute_table_filter_model.setAttributeTableConfig(self._config)
    self._attribute_table_view.setAttributeTableConfig(self._config)

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.