1

I need a QgsMapLayerComboBox to show only layers whose name contains a specific word. I have no way to know the names or geometry of the layers beforehand - I can only filter them based on whether or not they contain this word.

I thought about using setFilters(), but it looks like it only allows to filter by geometry or layer type, not by layer name. I also read about setExceptedLayerList() - but as I mentionned earlier, I don't know the exact name of the layers I don't want to show in the QgsMapLayerComboBox.

So, is there a way for me to use setExceptedLayerList() with an expression referring to layers whose name does not contain the word I need? Or another method that would allow me to filter the layers in my QgsMapLayerComboBox based on a word in their names?

1

You could use the following logic which excludes the layers not containing the name you define:

name = 'someName'
layer_list = []

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    if name not in layer.name().lower():
        layer_list.append(layer)

self.dockwidget.mMapLayerComboBox.setExceptedLayerList(layer_list)

If you want it to be case-sensitive, remove the .lower() method.

| improve this answer | |

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.