3

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)

2 Answers 2

11

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

1
  • Thanks this looks like exactly what I need - it just makes testing a bit easier. I'll have a look at the wider QWidget objects a bit more too. Aug 5, 2015 at 8:32
2

This is the snipped code of my application (at the main program):

.
.
.
# Create the dialog and keep reference
reload(output_file_dialog)

dlg = OutputFile()      #create Dialog object
dlg.show()              #show Dialog object

dlg.ui.lineEdit.clear()   #clear text in lineEdit object
dlg.ui.pushButton.clicked.connect(dlg.select_output_file)   #send signal if pushButton is clicked

to produce this Dialog:

enter image description here

When I included only three lines of code for creating the QgsMapLayerComboBox object (see next code) and a slightly modifications in the output_file_dialog:

.
.
.
# Create the dialog and keep reference
reload(output_file_dialog)

dlg = OutputFile()      #create Dialog object

win = QgsMapLayerComboBox(dlg)   #create a QgsMapLayerComboBox
win.setFixedWidth(231)
win.move(150, 20)

dlg.show()                 #show Dialog object

dlg.ui.lineEdit.clear()   #clear text in lineEdit object
dlg.ui.pushButton.clicked.connect(dlg.select_output_file)   #send signal if pushButton is clicked

it changed to produce this new Dialog. It was very quick and useful.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.