[GIS] How to prompt for layer selection from python console in QGIS

pyqgispythonqgis

During script development it's useful to use the QGIS python console to test the same script on different layers. Currently I've been hardcoding layer strings and just swapping out but it isn't particularly refined!

Ideally I want to prompt keyboard input or throw up a mini gui combo box.

Can anyone provide example code or signpost to some relevant documentation please. (or suggest an alternative approach)

Best Answer

You'll want to use a QgsMapLayerComboBox. If you're just after quick and dirty, you can show the combobox alone in a window using:

w=qgis.gui.QgsMapLayerComboBox()
w.show()

Then, you can retrieve the selected layer with:

w.currentLayer()

You can also filter the displayed layers by calling something like

w.setFilters( qgis.gui.QgsMapLayerProxyModel.PointLayer | qgis.gui.QgsMapLayerProxyModel.LineLayer )

and use the options shown here