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
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:
Notes:
- The updated QListView simply adds all currently loaded layers and sets their checkbox to
True
. - The
run()
function I used can be checked to allow the signals to be disconnected from the slots.