0

From Showing attribute table in form using PyQGIS I know how to show a table with all the attributes using this code:

cache = QgsVectorLayerCache(layer, 10000)
model = QgsAttributeTableModel(cache)
model.loadLayer()
table = QTableView()
table.setModel(model)

Now I'm wondering how to show not all the attributes, but only the ones I want or, if it's possible, do the same thing with the classic attribute table.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Lorenzo
  • 1,085
  • 1
  • 6
  • 18
  • You can set a filter expression to show only those records that meet the filter. Are you interested in that? – Germán Carrillo Dec 14 '19 at 15:08
  • Hi thanks! Maybe yes. If, for example, In my attribute table I have three columns: ID, NAME and TABLE and I want to show only ID and TABLE what expression should I use? And how to use it in PyQGIS? – Lorenzo Dec 14 '19 at 15:34
  • Your answer in this question can be another solution to my problem, but I'm not sure that this can work in QGIS 3 because I tried it and nothing happened https://gis.stackexchange.com/questions/215946/hide-column-in-attribute-table-by-using-pyqgis – Lorenzo Dec 14 '19 at 16:45
  • Ah, OK. So, you actually need to hide columns (attributes), not records. Then you can use the answer you mentioned, right. Just tested it using QGIS v3.10 and it worked for me. After running the code snippet, open the attribute table in QGIS (or use iface.showAttributeTable(my_layer)) and you'll see some columns are now hidden. – Germán Carrillo Dec 14 '19 at 18:26
  • Thanks, sorry if I wasn't clear. I have just another problem. When I select another style using layer.loadNamedStyle(selectedStyle) all columns are shown again. Do you know how to fix this? – Lorenzo Dec 14 '19 at 18:42
  • The style is removing the hidden property for the columns. So, you either adjust the style to keep those columns hidden or you call a function that hides them automatically after setting the style. If you agree, I'll mark this question as a duplicate. – Germán Carrillo Dec 14 '19 at 18:48
  • I need to set the style after, but I'll try to adjust the style. Thank you you can sure mark this question as duplicate. – Lorenzo Dec 14 '19 at 18:52

0 Answers0