4

I am making a plugin in QGIS which involves the use of QgsFieldComboBox, what I want to do is that the combo box only shows fields with data type of string (or to show fields with data type of integer, etc). Does anyone have any code example? comboBox.setLayer(layer) comboBox.setFilters(???)

Also, setFilters() takes QgsFieldProxyModel filters as parameter but when I do: from qgis.core import QgsFieldProxyModel

It gives me an error saying that ImportError: cannot import name QgsFieldProxyModel

  • 1
    Because is from qgis.gui import QgsFieldProxyModel; related to last error. – xunilk Jul 12 '17 at 1:50
  • In QGIS 3 QgsFieldProxyModel is imported from qgis.core – Matt Needle Jan 2 at 11:06
6

I assume that you are fairly experienced making plugins and you know where put different code lines in __init__, initGui, etc functions of your plugin. So, next code works at Python Console and you should adapt it for your plugin structure:

from qgis.gui import QgsMapLayerComboBox
from qgis.gui import QgsFieldComboBox
from qgis.gui import QgsFieldProxyModel

def select_layer_fields(vlayer):
    wcbF.setLayer(vlayer)
    field = wcbF.setLayer(vlayer)

wcbL = QgsMapLayerComboBox()
wcbL.move(600,200)
wcbL.setMinimumWidth(203)
wcbL.show()

wcbF = QgsFieldComboBox()
wcbF.move(600,300)
wcbF.setMinimumWidth(203)
wcbF.setFilters(QgsFieldProxyModel.String) #All, Date, Double, Int, LongLong, Numeric, String, Time
wcbF.show()

vlayer = wcbL.currentLayer()                      #run method
wcbF.setLayer(vlayer)                             #run method
wcbL.layerChanged.connect(select_layer_fields)    #run method

I tried it out with a point and polygon layers of next images. They have only one field with data type of string in its attributes tables. Observe that filter QgsFieldProxyModel.String allows, in each case, that the QgsFieldComboBox object only shows one field with data type of string (as expected). As line commentary, you have all other possibilities for filters (Double, Int, etc).

When point layer is selected:

enter image description here

When polygon layer is selected:

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.