2

I want to create check boxes inside a listview in my plugin dynamically based on the number of layers loaded in QGIS. I would like to know is there any similar existing plugin in QGIS so that I may refer the code and try implementing in mine.

1 Answer 1

1

Late post but I implemented something similar recently so thought to share it. You could create a QListView by defining a new function in your plugin. For example:

def refresh_listView(self):
    qListView = self.dockwidget.listView
    model = QStandardItemModel()

    for layer in QgsMapLayerRegistry.instance().mapLayers().values():   
        item = QStandardItem(layer.name())
        check = Qt.Checked
        item.setCheckState(check)
        item.setCheckable(True)
        model.appendRow(item)

    qListView.setModel(model)

Then in your run() function, you could connect the function slot to a signal so that whenever a layer is added/removed, the QListView will be updated:

 def run(self, checked):
    self.refresh_listView()

    if checked:
        QgsMapLayerRegistry.instance().layersAdded.connect(self.refresh_listView)
        QgsMapLayerRegistry.instance().layersRemoved.connect(self.refresh_listView)
    else:
        QgsMapLayerRegistry.instance().layersAdded.disconnect(self.refresh_listView)
        QgsMapLayerRegistry.instance().layersRemoved.disconnect(self.refresh_listView)

Example:

QlistView example

Notes:

  1. The updated QListView simply adds all currently loaded layers and sets their checkbox to True.
  2. The run() function I used can be checked to allow the signals to be disconnected from the slots.

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.