3

I want to have a list of filtered layers (like only raster or vector ones) the user can select from like we have in QgsProcessingParameterMultipleLayers

enter image description here

yet without Processing algorithm script (in normal QDialog window)?

4

You can use a QListWidget with checkable items.

Example:

class LayerListWidget(QListWidget):
    def __init__(self, parent=None):
        QListWidget.__init__(self)
        self.populate()
        
    def populate(self):
        layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsMapLayerType.VectorLayer]
        items = [f'{i.name()} [{i.crs().authid()}]' for i in layers]
        for s in items:
            i = QListWidgetItem(s)
            i.setFlags(i.flags() | Qt.ItemIsUserCheckable)
            i.setCheckState(Qt.Unchecked)
            self.addItem(i)
            
    def checked_layers(self):
        checked_items_text = []
        for n in range(self.count()):
            i = self.item(n)
            if i.checkState() == Qt.Checked:
                checked_items_text.append(i.text())
        layer_names = [t.split(' ')[0] for t in checked_items_text]
        layers = [l for l in QgsProject.instance().mapLayers().values() if isinstance(l, QgsVectorLayer) and l.name() in layer_names]
        return layers

class MainDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setGeometry(300, 300, 500, 350)
        self.layout = QVBoxLayout()
        self.layer_list_widget = LayerListWidget(self)
        self.btn = QPushButton('Get checked layers', self)
        self.te = QTextEdit(self)
        self.layout.addWidget(self.layer_list_widget)
        self.layout.addWidget(self.btn)
        self.layout.addWidget(self.te)
        self.setLayout(self.layout)
        self.btn.clicked.connect(self.get_layers)
    
    def get_layers(self):
        self.te.setText(str(self.layer_list_widget.checked_layers()))

w = MainDialog()
w.show()

Results:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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