2016-06-18 6 views

답변

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)