1

I am creating dynamic labels and line edit boxes based on the number of fields in the shapefile and populating the lineedit boxes using the feature attributes using the below code. Each lineedit box has the field name as object name.

I need to know how to read the current value of each dynamically created lineedit boxes.

    def addLayerNames(self):
     for i in reversed(range(self.dlg.verticalLayout.count())):
        self.dlg.verticalLayout.itemAt(i).widget().setParent(None)
     layers = QgsMapLayerRegistry.instance().mapLayers().values()
     layer_list = []
     for layer in layers:
        if layer.type() == QgsMapLayer.VectorLayer:
            layer_list.append(layer.name())
     self.dlg.comboBox.addItems(layer_list)
     selectedLayerIndex = self.dlg.comboBox.currentIndex()
     selectedLayer = layers[selectedLayerIndex]
     fields = selectedLayer.pendingFields()
     fieldnames = [field.name() for field in fields]
     for i,field in enumerate(fieldnames):
        self.labels = QLabel()
        self.linedit = QLineEdit()
        self.labels.setText(field)
        self.linedit.setFixedWidth(100)
        self.dlg.verticalLayout.addWidget(self.labels)
        self.dlg.verticalLayout.addWidget(self.linedit)
        request = QgsFeatureRequest().setFilterFid(0)
        layer.setSelectedFeatures([0])
        self.iface.actionZoomToSelected().trigger()
        feat = layer.getFeatures(request).next()
        self.linedit.setText(str(feat[i]))
        self.linedit.setObjectName(field)
        self.dlg.pushButton.setEnabled(False)
3

The example can be reduced to

for i, field in enumerate(fieldnames):
    self.lineedit = QLineEdit()
    self.lineedit.setText(str(feat[i]))

Each new QLineEdit is assigned to the same variable self.lineedit. Each time a new lineedit is created, the reference to the old one is lost.

One solution to overcome this problem is to save them in a list

self.lineedits = list()
for i, field in enumerate(fieldnames):
    lineedit = QLineEdit()
    lineedit.setText(str(feat[i]))
    self.lineedits.append(lineedit)

Note: This is a generic programming question, unrelated to PyQGIS

0

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.