6

I build a plugin. It has a lot of comboboxes (QgsMapLayerComboBox). They are all empty when no project is loaded. When I open a project in QGIS, a layer is automatically shown in all comboboxes. All is the same layer.

I don't want a layer is selected. How can I avoid that?

A sample form and script for QGIS Python Editor:

enter image description here

from qgis.PyQt.QtCore import * 
from qgis.PyQt.QtGui import * 
from qgis.PyQt.QtWidgets import * 
  
class Window(QMainWindow):
  
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(250, 250, 300, 100)
        self.setWindowTitle("Test")
        
        cb1 = QgsMapLayerComboBox(self)
        cb2 = QgsMapLayerComboBox(self)

        layout = QVBoxLayout()
        layout.addWidget(cb1)
        layout.addWidget(cb2)
        
        contents = QWidget()
        contents.setLayout(layout)
        self.setCentralWidget(contents)

window = Window()
window.setWindowFlags(window.windowFlags() | Qt.WindowStaysOnTopHint)  
window.show()
1
  • I believe you can set the selected layer to None. I don't remember the name of the method but it something like .setCurrentLayer(). The QgsMapLayerComboBox also has an option to allow an empty entry, that must be enabled too.
    – Matt
    Commented Jan 16, 2022 at 20:52

1 Answer 1

5

Use this for all QgsMapLayerComboBox.

maplayercombobox.setAllowEmptyLayer(True)
maplayercombobox.setCurrentIndex(0)

If you set an index after using setAllowEmptyLayer(True), since combobox has a selected item (empty item), any layer is not automatically shown in the comboboxes when you load a project.


It can be cumbersome to set those for each combobox. Instead, find all QgsMapLayerComboBox of the widget and use the commands above inside a for loop.

for cb in self.findChildren(QgsMapLayerComboBox):
    cb.setAllowEmptyLayer(True)
    cb.setCurrentIndex(0)
2
  • This has solved my problem too. Is there a way to set the visible text in the ComboBox to "Select" instead of the default blank?
    – WillH
    Commented Nov 7, 2022 at 8:33
  • setCurrentIndex() seems to have been removed from the API - but still works...?
    – songololo
    Commented Jan 11, 2023 at 14:53

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.