7

I am creating a plugin in QGIS where I want to read a Vector layer --> Select attribute column --> list unique values within the chosen attribute column in the selected attribute from the column.

I have been successful with the two first steps, but not with the third.

This is the code used so far, but I cannot get further than this.

self.layerComboManagerPoint = QgsMapLayerComboBox(self.dlg.comboBoxVector)
self.layerComboManagerPoint.setCurrentIndex(-1)
self.layerComboManagerPoint.setFilters(QgsMapLayerProxyModel.PolygonLayer)
self.layerComboManagerPoint.setFixedWidth(175)

self.layerComboManagerPointField = QgsFieldComboBox(self.dlg.comboBoxField)
self.layerComboManagerPointField.setFilters(QgsFieldProxyModel.AllTypes) 
self.layerComboManagerPoint.layerChanged.connect(self.layerComboManagerPointField.setLayer)

I have tried googling, but I might just not have a reasonable word to google on.

enter image description here

9

Add the highlighted lines to your script:

self.layerComboManagerPoint = QgsMapLayerComboBox(self.dlg.comboBoxVector)
self.layerComboManagerPoint.setCurrentIndex(-1)
self.layerComboManagerPoint.setFilters(QgsMapLayerProxyModel.PolygonLayer)
self.layerComboManagerPoint.setFixedWidth(175)

self.layerComboManagerPointField = QgsFieldComboBox(self.dlg.comboBoxField)
self.layerComboManagerPointField.setFilters(QgsFieldProxyModel.AllTypes) 
self.layerComboManagerPoint.layerChanged.connect(self.layerComboManagerPointField.setLayer)


################## ADD THESE LINES #########################
def field_changed(field):
    # get current layer
    layer = self.layerComboManagerPoint.currentLayer()
    # get index of the field
    i = layer.fields().indexOf(field)
    # get unique values
    unique_values = layer.uniqueValues(i)    
    # remove all values from comboBoxAttribute
    self.dlg.comboBoxAttribute.clear()    
    # add unique values
    self.dlg.comboBoxAttribute.addItems(unique_values)    

self.layerComboManagerPointField.fieldChanged.connect(field_changed)    
#############################################################

I didn't test it.

2
  • OK, it works fine, however, I also now understand that I need to be able to read other types than 'string'. I tried self.dlg.comboBoxAttributesetFilters(QgsMapLayerProxyModel.AllTypes) But with no luck. Do you have any solution to this too?
    – gusbacos
    May 24 at 8:57
  • @gusbacos Comments are used to ask for clarification or to point out problems in the post. If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. May 24 at 10:54

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.