Findbyattr.py

the modified code of Find By Attribute 0.3 in order to view the selected features - luca76 -, 2010-01-18 07:08 AM

Download (6.27 KB)

 
1
#==============================================================
2
#=================== Find by Attribute ========================
3
#=================== a QGis Plug-In    ========================
4
#==============================================================
5

    
6
# v0.1 by Mauricio de Paulo 
7
# v0.2 by Anita Graser
8
# Update for v0.2 for QGIS 1.0 Preview by Mauricio de Paulo
9
# v0.3 by Anita Graser
10

    
11

    
12
import os,sys
13

    
14
sys.path.append("~/.qgis/python")
15

    
16
from PyQt4.QtCore import *
17
from PyQt4.QtGui import *
18

    
19

    
20
from qgis.core import *
21

    
22
from ui_control import ui_Control
23
import resources
24

    
25
class findbyattr:
26

    
27
    def __init__(self, iface):
28
        self.iface = iface
29
        
30
    def initGui(self):
31
        # create action that will start plugin configuration
32
        self.action = QAction(QIcon(":find.png"), "Find by Attribute", self.iface.mainWindow())
33
        self.action.setWhatsThis("Find by Attribute")
34
        QObject.connect(self.action, SIGNAL("activated()"), self.run)
35
    
36
        # add toolbar button and menu item
37
        self.iface.addToolBarIcon(self.action)
38
        self.iface.addPluginToMenu("&Find by Attribute", self.action)
39

    
40
    def unload(self):
41
        # remove the plugin menu item and icon
42
        self.iface.removePluginMenu("&Find by Attribute",self.action)
43
        self.iface.removeToolBarIcon(self.action)
44
    
45
    def run(self):
46
        # create and show a configuration dialog or something similar
47
        flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMaximizeButtonHint  # QgisGui.ModalDialogFlags
48
        self.pluginGui = ui_Control(self.iface.mainWindow(), flags)
49
        
50
        # insert every signal connection here!
51
        QObject.connect(self.pluginGui.layerComboBox,SIGNAL('currentIndexChanged (int)'),self.readLayerColumns)
52
        QObject.connect(self.pluginGui.buttonBox,SIGNAL("accepted()"),self.findFeatures)
53

    
54
        self.layermap=QgsMapLayerRegistry.instance().mapLayers()
55
        for (name,layer) in self.layermap.iteritems():
56
            self.pluginGui.layerComboBox.addItem(name)
57
        
58
        self.pluginGui.operatorComboBox.addItems(["=",">","<",">=","<=","between"])
59
        
60
        self.pluginGui.show()
61

    
62
    
63
    #Now these are the SLOTS
64
    def updateText(self,args):
65
        print 'got here'
66
    def readLayerColumns(self,args):
67
        print "readLayerColumns"
68
        vectorlayer=self.layermap[self.pluginGui.layerComboBox.currentText()]
69
        provider=vectorlayer.dataProvider()
70
        fieldmap=provider.fields()
71
        self.pluginGui.attributeComboBox.clear()
72
        for (k,attr) in fieldmap.iteritems():
73
            self.pluginGui.attributeComboBox.addItem(attr.name())
74
    
75
    def findFeatures(self):
76
        vectorlayer=self.layermap[self.pluginGui.layerComboBox.currentText()]
77
        column=self.pluginGui.attributeComboBox.currentText()
78
        value=self.pluginGui.lineEdit.text()
79
        provider=vectorlayer.dataProvider()
80
        provider.rewind()
81
        f=QgsFeature()
82
        fieldmap=provider.fields()
83
        for (k,attr) in fieldmap.iteritems():      
84
            if (column==attr.name()): 
85
                 col=k
86
        allAttrs = provider.attributeIndexes()
87
        provider.select(allAttrs)
88
        selection=[]
89
        operator=self.pluginGui.operatorComboBox.currentText()
90

    
91
        if operator not in ("=","between"):
92
            try:
93
              value=float(value)
94
            except:
95
              infoString = QString("Error: Non numeric value!")
96
              QMessageBox.information(self.iface.mainWindow(),"Find by Attribute",infoString)
97
              vectorlayer.setSelectedFeatures([])
98
              return
99

    
100
        # =
101
        if operator == "=":
102
              values=value.split(';') #allows to specify a list of values devided by semi-colons 
103
              while (provider.nextFeature(f)):
104
                fieldmap=f.attributeMap()
105
                if fieldmap[col].toString() in values:
106
                    selection.append(f.id())
107
        # >
108
        elif operator == ">":
109
            while (provider.nextFeature(f)):
110
                fieldmap=f.attributeMap()
111
                try:
112
                    field=float(fieldmap[col].toString())
113
                    if field > value:
114
                        selection.append(f.id())
115
                except:
116
                  print "Error: Non numeric values!"
117
        # <
118
        elif operator == "<":
119
            while (provider.nextFeature(f)):
120
                fieldmap=f.attributeMap()
121
                try:
122
                    field=float(fieldmap[col].toString())
123
                    if field < value:
124
                        selection.append(f.id())
125
                except:
126
                  print "Error: Non numeric values!"
127
        # >=
128
        elif operator == ">=":
129
            while (provider.nextFeature(f)):
130
                fieldmap=f.attributeMap()
131
                try:
132
                    field=float(fieldmap[col].toString())
133
                    if field >= value:
134
                        selection.append(f.id())
135
                except:
136
                  print "Error: Non numeric values!"
137
        # <=
138
        elif operator == "<=":
139
            while (provider.nextFeature(f)):
140
                fieldmap=f.attributeMap()
141
                try:
142
                    field=float(fieldmap[col].toString())
143
                    if field <= value:
144
                        selection.append(f.id())
145
                except:
146
                  print "Error: Non numeric values!"
147
        # between
148
        elif operator == "between":
149
            values=value.split(';')
150
            while (provider.nextFeature(f)):
151
                fieldmap=f.attributeMap()
152
                try:
153
                    field=float(fieldmap[col].toString())
154
                    if field >= float(values[0]) and field <= float(values[1]):
155
                        selection.append(f.id())
156
                except:
157
                  print "Error: Non numeric values!"  
158

    
159

    
160
        vectorlayer.setSelectedFeatures(selection)
161

    
162
        count=len(selection)
163

    
164
        infoString = QString("Found "+str(count)+" features!")
165
        QMessageBox.information(self.iface.mainWindow(),"Find by Attribute",infoString)
166

    
167
        mapCanvas=self.iface.mapCanvas()
168
        mapCanvas.setCurrentLayer(vectorlayer) 
169
        mapCanvas.zoomToSelected() 
170
        mapCanvas.refresh()