如何使用python为QGIS插件在QTableWidget中将选定图层中的选定字段唯一值显示为行标题?

时间:2016-06-18 16:17:35

标签: pyqt4 qt-designer qgis

在Qt Designer中为QGIS插件构建表单,执行以下操作:

用户从组合框中选择了一个图层和一个字段后,该字段的唯一值将在QTableWidget中使用python显示为行标题

1 个答案:

答案 0 :(得分:0)

def showdlg(self):
    # show the dialog - ui file
    self.dlg.show()

    # Get the layers names 
    legendInterface = self.iface.legendInterface()
    listLayerName = [i.name() for i in legendInterface.layers() if i.type() == QgsMapLayer.VectorLayer]

    # Add all these layer names to the layer combobox
    self.dlg.cmbLayer.addItems(listLayerName)

    # When user selects a layer from the layer combobox 
    # insert the corresponding fields names to the field combobox
    self.dlg.cmbLayer.currentIndexChanged[int].connect(self.FieldsNamestoFieldCombo)

    # When user selects a field from the field combobox, 
    # insert the unique values of this field as the table' s rows names
    self.dlg.cmbField.currentIndexChanged[int].connect(self.FieldUniqueValuestoTable)

def FieldsNamestoFieldCombo(self, index):

    # get list of all vector layers in QGIS
    legendInterface = self.iface.legendInterface()
    listLayers = [layer for layer in legendInterface.layers() if layer.type() == QgsMapLayer.VectorLayer]

    # get name of selected layer
    provider = listLayers[index].dataProvider()
    fields = provider.fields()
    listFieldNames = [field.name() for field in fields]

    # clear the combo box comboFieldList
    self.dlg.cmbField.clear()

    # add all these field names to combo box comboFieldList
    self.dlg.cmbField.addItems(listFieldNames)

def FieldUniqueValuestoTable(self, index):
    # Get the selected layer id
    layer_id = getVectorLayerByName(self.dlg.cmbLayer.currentText())

    # Get the selected field name and id
    field = self.dlg.cmbField.currentText()
    field_index = layer_id.fieldNameIndex(field)

    #Get the unique values of the selected field
    un_values = layer_id.uniqueValues(field_index)

    # Count the number of unique values
    un_values_length = len(un_values)

    # Set the table to have as many rows as the number of unique values
    # of the selected field
    self.dlg.tableWidget.setRowCount(un_values_length)

    # Make a new list that holds the unique values as strings
    un_values_string_list = []
    for i in range(un_values_length):
        a = str(un_values[i])
        un_values_string_list.append(a)

# Set the tables rows names to be the unique values
self.dlg.tableWidget.setVerticalHeaderLabels(un_values_string_list)