I want to display the content from a layer in a new view

I have so far a code like below (you should have 2 columns at least, then, just try in the QGIS Python console replacing mylayer_id)

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QTableView
from qgis.gui import QgsAttributeTableModel

layer = QgsMapLayerRegistry.instance().mapLayer(u'mylayer_id')

cache = QgsVectorLayerCache(layer, 10000)
model = QgsAttributeTableModel(cache)
print model.setHeaderData(0, Qt.Horizontal, u"pk")
print model.setHeaderData(1, Qt.Horizontal, u"name")
table = QTableView()

The problem is the fact that header in the view are not updated with model.setHeaderData: it returns false (meaning that the header was not updated) whereas with other models (from Qt), I don't encounter this issue. You may wonder why I make a reference to other Qt models? It's because the setHeaderData method is inherited from Qt QAbstractItemModel.

Is is due to the QGIS cache? How can I solve this issue? Any hints is welcome


Qt models are usually very generic and do not know anything about the data presented within. Therefore they allow the developer to specify all aspects of the data.

The QgsAttributeTable model in contrast knows about the data presented within and reacts dynamically to reflect its properties by automatically returning appropriate headers.

I assume that you do not want the plain "technical" database field names written in the header. The easiest approach is to set field name aliases on the layer, the attribute table model will use these instead of the field name if present.

layer.addAttributeAlias( 0, 'ID' )
layer.addAttributeAlias( 1, 'Name' )

If this is not enough, you will have to subclass the model and reimplement the headerData method or do some tricks to the view instead.

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.