Monday 8 June 2015

pyqgis - Adding attribute list to combobox in QGIS plugin?


I am developing a simple plugin at the moment which contains 3 combo boxes:



  • comboBox_1

  • comboBox_2

  • comboBox_3



Combobox 1 & 2 lists the vector layers available, however I would like the 3rd combobox to list the attribute column that both layers have in common (from the attribute table).


    # run method that performs all the real work
def run(self):
# show the dialog
self.dlg.show()
for layer in self.iface.legendInterface().layers():
if layer.type() == QgsMapLayer.VectorLayer:
self.dlg.comboBox.addItem(layer.name())
self.dlg.comboBox_2.addItem(layer.name())

Answer




You could achieve this based on the QGIS Combo Manager


Just create your own filter for the fields in a subclass of FieldCombo. The following code is untested (literally), so please bear with me if there's a typo or other minor problems, and think of it as a reference.


from qgiscombomanager import *

class MyFieldCombo( FieldCombo ):
def __init__(self, widget, vectorLayerCombo1, vectorLayerCombo2, initField="", options={}):
FieldCombo.__init__(self, widget, vectorLayerCombo1, vectorLayerCombo2, initField, options)
self.vectorLayerCombo1 = vectorLayerCombo1
self.vectorLayerCombo2 = vectorLayerCombo2


# Overrides the filter from FieldCombo. Will be called for every field
# and should return True, if the field should be shown.
def __isFieldValid(self, idx):
if not FieldCombo.__isFieldValid(self, idx):
return False

for f in self.vectorLayerCombo2.pendingFields():
# adjust this line to reflect your idea of "common"
if f.name() == self.vectorLayerCombo1.pendingFields()[idx].name():
return True

return False

# run method that performs all the real work
def run(self):
# show the dialog
self.dlg.show()
self.vlc1 = VectorLayerCombo( self.dlg.comboBox )
self.vlc2 = VectorLayerCombo( self.dlg.comboBox_2 )
self.fc = MyFieldCombo( self.dlg.comboBox_3 )

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...