-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzone_label.py
More file actions
701 lines (602 loc) · 29.7 KB
/
zone_label.py
File metadata and controls
701 lines (602 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ZoneLabel
A QGIS plugin
This plugin allows to manually label rectangular areas ...
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2022-07-08
git sha : $Format:%H$
copyright : (C) 2022 by Andrea Folini
email : andrea.folini@polimi.it
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os.path
from os import path
from qgis.PyQt import QtGui
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QVariant, QSize
from qgis.PyQt.QtGui import QIcon, QColor, QDoubleValidator, QCursor, QPixmap
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QInputDialog
from qgis.core import * # attach main QGIS library
from qgis.utils import *
from qgis.gui import QgsMapToolEmitPoint, QgsMapToolPan
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the DockWidget
from .zone_label_dockwidget import ZoneLabelDockWidget
import os.path
class ZoneLabel:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'ZoneLabel_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Zone Label')
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar(u'ZoneLabel')
self.toolbar.setObjectName(u'ZoneLabel')
#print "** INITIALIZING ZoneLabel"
self.pluginIsActive = False
self.dockwidget = None
self.classification_layer = None
self.mode = 0
self.canvas = self.iface.mapCanvas()
self.defaultTool = None
self.pointTool = QgsMapToolEmitPoint(self.canvas)
green_pointer_image = QPixmap(":/plugins/zone_label/Images/pointer_green.png")
green_pointer_image = green_pointer_image.scaled(QSize(32, 32), Qt.KeepAspectRatio)
red_pointer_image = QPixmap(":/plugins/zone_label/Images/pointer_red.png")
red_pointer_image = red_pointer_image.scaled(QSize(32, 32), Qt.KeepAspectRatio)
self.green_cursor = QCursor(green_pointer_image, 14, 3)
self.red_cursor = QCursor(red_pointer_image, 14, 3)
self.cross_cursor = QCursor(Qt.CrossCursor)
self.active_message = None
self.state_queue = []
self.message_bar = iface.messageBar()
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('ZoneLabel', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/zone_label/zone_label_icon.png'
self.add_action(
icon_path,
text=self.tr(u'Label zones'),
callback=self.run,
parent=self.iface.mainWindow())
#--------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
#print "** CLOSING ZoneLabel"
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
self.dockwidget.select_button.clicked.disconnect(self.select_area)
self.dockwidget.split_button.clicked.disconnect(self.split_mode_set)
self.dockwidget.accept_button.clicked.disconnect(self.accept_mode_set)
self.dockwidget.reject_button.clicked.disconnect(self.reject_mode_set)
self.dockwidget.undo_button.clicked.disconnect(self.undo_action)
self.pointTool.canvasClicked.disconnect(self.action_area)
self.dockwidget.save_button.clicked.disconnect(self.save_layer)
self.canvas.mapToolSet.disconnect(self.check_map_tool)
self.canvas.layersChanged.disconnect(self.reorder_layers)
self.canvas.destinationCrsChanged.disconnect(self.crs_warning)
if self.classification_layer is not None:
QgsProject.instance().removeMapLayer(self.classification_layer.id())
self.classification_layer = None
self.state_queue = []
if self.canvas.mapTool() is self.pointTool:
try:
self.canvas.setMapTool(self.defaultTool)
except TypeError:
self.canvas.unsetMapTool(self.pointTool)
self.defaultTool = None
self.canvas.refresh()
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
self.dockwidget = None
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
#print "** UNLOAD ZoneLabel"
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Zone Label'),
action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
# --------------------------------------------------------------------------
def run(self):
"""Run method that loads and starts the plugin"""
if not self.pluginIsActive:
self.pluginIsActive = True
#print "** STARTING ZoneLabel"
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget is None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = ZoneLabelDockWidget()
# connect to provide cleanup on closing of dockwidget
self.dockwidget.closingPlugin.connect(self.onClosePlugin)
# show the dockwidget
# TODO: fix to allow choice of dock location
self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
self.dockwidget.show()
self.dockwidget.select_button.clicked.connect(self.select_area)
self.dockwidget.split_button.clicked.connect(self.split_mode_set)
self.dockwidget.accept_button.clicked.connect(self.accept_mode_set)
self.dockwidget.reject_button.clicked.connect(self.reject_mode_set)
self.dockwidget.undo_button.clicked.connect(self.undo_action)
self.pointTool.canvasClicked.connect(self.action_area)
self.dockwidget.save_button.clicked.connect(self.save_layer)
self.canvas.mapToolSet.connect(self.check_map_tool)
self.canvas.layersChanged.connect(self.reorder_layers)
self.canvas.destinationCrsChanged.connect(self.crs_warning)
self.disable_mode()
self.dockwidget.undo_button.setEnabled(False)
self.dockwidget.save_button.setEnabled(False)
self.dockwidget.centroid_check.setChecked(True)
self.defaultTool = self.canvas.mapTool()
self.mode = 0
regex_num = QtCore.QRegExp("^(-?)(0|([1-9][0-9]{0,10}))(\\.[0-9]{1,10})?$")
regex_num_pos = QtCore.QRegExp("(0|([1-9][0-9]{0,4}))(\\.[0-9]{1,10})?$")
validator_coord = QtGui.QRegExpValidator(regex_num)
validator_size = QtGui.QRegExpValidator(regex_num_pos)
self.dockwidget.xcenter_box.setValidator(validator_coord)
self.dockwidget.ycenter_box.setValidator(validator_coord)
self.dockwidget.width_box.setValidator(validator_size)
self.dockwidget.height_box.setValidator(validator_size)
def check_map_tool(self, new_tool, old_tool):
if self.mode != 0 and new_tool is not self.pointTool:
self.mode = 0
self.dockwidget.split_button.setChecked(False)
self.dockwidget.accept_button.setChecked(False)
self.dockwidget.reject_button.setChecked(False)
self.dockwidget.mode_label.setText("Active mode:")
if new_tool is not self.pointTool:
self.defaultTool = self.canvas.mapTool()
def disable_mode(self):
self.dockwidget.split_button.setEnabled(False)
self.dockwidget.accept_button.setEnabled(False)
self.dockwidget.reject_button.setEnabled(False)
"""
Mode codes:
0 - Normal mode
1 - Split mode
2 - Accept mode
3 - Reject mode
"""
def enable_mode(self):
self.dockwidget.split_button.setEnabled(True)
self.dockwidget.accept_button.setEnabled(True)
self.dockwidget.reject_button.setEnabled(True)
def split_mode_set(self):
if self.dockwidget.split_button.isChecked():
self.mode = 1
self.dockwidget.accept_button.setChecked(False)
self.dockwidget.reject_button.setChecked(False)
self.dockwidget.mode_label.setText("Active mode: Split")
self.canvas.setMapTool(self.pointTool)
self.pointTool.setCursor(self.cross_cursor)
else:
self.dockwidget.mode_label.setText("Active mode:")
self.mode = 0
try:
self.canvas.setMapTool(self.defaultTool)
except TypeError:
self.canvas.unsetMapTool(self.pointTool)
def accept_mode_set(self):
if self.dockwidget.accept_button.isChecked():
self.mode = 2
self.dockwidget.split_button.setChecked(False)
self.dockwidget.reject_button.setChecked(False)
self.dockwidget.mode_label.setText("Active mode: Accept")
self.canvas.setMapTool(self.pointTool)
self.pointTool.setCursor(self.green_cursor)
else:
self.dockwidget.mode_label.setText("Active mode:")
self.mode = 0
try:
self.canvas.setMapTool(self.defaultTool)
except TypeError:
self.canvas.unsetMapTool(self.pointTool)
def reject_mode_set(self):
if self.dockwidget.reject_button.isChecked():
self.mode = 3
self.dockwidget.split_button.setChecked(False)
self.dockwidget.accept_button.setChecked(False)
self.dockwidget.mode_label.setText("Active mode: Reject")
self.canvas.setMapTool(self.pointTool)
self.pointTool.setCursor(self.red_cursor)
else:
self.dockwidget.mode_label.setText("Active mode:")
self.mode = 0
try:
self.canvas.setMapTool(self.defaultTool)
except TypeError:
self.canvas.unsetMapTool(self.pointTool)
def select_area(self):
if self.dockwidget.centroid_check.isChecked():
# check that crs unit is meters
if not self.canvas.mapSettings().destinationCrs().mapUnits() == QgsUnitTypes.DistanceMeters:
self.message_bar.pushCritical("Error", "The Coordinate Reference System unit of the map must be Meters.")
return
# check that every parameter is filled
if (self.dockwidget.xcenter_box.text() == "" or self.dockwidget.ycenter_box.text() == "" or
self.dockwidget.width_box.text() == "" or self.dockwidget.height_box.text() == ""):
self.message_bar.pushCritical("Error", "All parameters must be filled to select a zone.")
return
if self.classification_layer is not None:
confirm = self.confirm_selection()
if confirm == 0:
return
self.classification_layer = self.create_base_layer()
self.classification_layer.setRenderer(self.create_renderer())
QgsProject.instance().addMapLayer(self.classification_layer)
self.classification_layer.startEditing()
field_index = self.classification_layer.fields().indexFromName("Label")
self.classification_layer.changeAttributeValue(1, field_index, "Not classified")
self.classification_layer.updateFields()
self.classification_layer.commitChanges()
self.classification_layer.triggerRepaint()
self.enable_mode()
self.dockwidget.save_button.setEnabled(True)
elif self.dockwidget.file_check.isChecked():
file_path = self.dockwidget.file_box.filePath()
# check if the path exists
if not path.exists(file_path):
self.message_bar.pushCritical("Error", "The file path does not exist.")
return
# catch errors in the file opening
try:
file_layer = QgsVectorLayer(path=file_path, baseName="classification_layer")
except:
self.message_bar.pushCritical("Error", "An error occurred while opening the file.")
return
# check that the file is a vector
if not file_layer.isValid():
self.message_bar.pushCritical("Error", "The file is not a valid vector layer.")
return
# check that the file is a classification layer
if self.check_file(file_layer) == 0:
self.message_bar.pushCritical("Error", "The file is not a layer from this plugin.")
return
if self.classification_layer is not None:
confirm = self.confirm_selection()
if confirm == 0:
return
self.classification_layer = self.deep_copy_layer(file_layer)
QgsProject.instance().addMapLayer(self.classification_layer)
self.enable_mode()
self.dockwidget.save_button.setEnabled(True)
self.canvas.setExtent(self.classification_layer.extent())
self.classification_layer.setFlags(QgsMapLayer.Private)
def crs_warning(self):
if self.classification_layer is not None:
map_crs = self.canvas.mapSettings().destinationCrs()
layer_crs = self.classification_layer.crs()
if not map_crs.authid() == layer_crs.authid():
self.message_bar.pushWarning("CRS modified", "The new CRS is different from the classification layer "
"CRS. It is advised to select a new area or to go "
"back to the original CRS")
def confirm_selection(self):
res = QMessageBox.question(self.dockwidget, "Confirm selection", "Selecting a new area will overwrite the "
"active classification layer. Continue?")
if res == QMessageBox.Yes:
QgsProject.instance().removeMapLayer(self.classification_layer.id())
self.state_queue = []
self.dockwidget.undo_button.setEnabled(False)
return 1
else:
return 0
def check_file(self, layer):
if not layer.crs().mapUnits() == QgsUnitTypes.DistanceMeters:
return 0
if not layer.geometryType() == QgsWkbTypes.PolygonGeometry:
return 0
fields = layer.fields()
if fields.indexFromName("Label") == -1 or fields.indexFromName("Desc") == -1:
return 0
return 1
def create_base_layer(self):
xcenter = float(self.dockwidget.xcenter_box.text())
ycenter = float(self.dockwidget.ycenter_box.text())
width = float(self.dockwidget.width_box.text()) * 1000
height = float(self.dockwidget.height_box.text()) * 1000
x_min = xcenter - (width / 2)
x_max = xcenter + (width / 2)
y_min = ycenter - (height / 2)
y_max = ycenter + (height / 2)
crs = self.canvas.mapSettings().destinationCrs().authid()
geometry = "Polygon" + "?crs=" + crs
new_layer = QgsVectorLayer(geometry, "classification_layer", "memory")
data_provider = new_layer.dataProvider()
new_feature = QgsFeature()
rectangle = QgsRectangle(x_min, y_min, x_max, y_max)
new_feature.setGeometry(QgsGeometry.fromRect(rectangle))
data_provider.addFeatures([new_feature])
new_layer.updateExtents()
data_provider.addAttributes([QgsField("Label", QVariant.String, len=254)])
data_provider.addAttributes([QgsField("Desc", QVariant.String, len=254)])
new_layer.updateFields()
if width < 400 or height < 400:
self.message_bar.pushWarning("Small area", "The selected area is very small, with a side "
"shorter than 400m.")
return new_layer
def create_renderer(self):
color_classes = []
symbol1 = QgsSymbol.defaultSymbol(2)
symbol1.setColor(QColor(255, 255, 255, 0))
symbol1.symbolLayer(0).setStrokeColor(QColor("black"))
symbol1.symbolLayer(0).setStrokeWidth(0.5)
empty_class = QgsRendererCategory("Not classified", symbol1, "Empty")
color_classes.append(empty_class)
symbol2 = QgsSymbol.defaultSymbol(2)
symbol2.setColor(QColor(14, 233, 37, 150))
symbol2.symbolLayer(0).setStrokeColor(QColor("black"))
symbol2.symbolLayer(0).setStrokeWidth(0.5)
accept_class = QgsRendererCategory("Accepted", symbol2, "Accept")
color_classes.append(accept_class)
symbol3 = QgsSymbol.defaultSymbol(2)
symbol3.setColor(QColor(200, 0, 0, 150))
symbol3.symbolLayer(0).setStrokeColor(QColor("black"))
symbol3.symbolLayer(0).setStrokeWidth(0.5)
reject_class = QgsRendererCategory("Rejected", symbol3, "Reject")
color_classes.append(reject_class)
renderer = QgsCategorizedSymbolRenderer("Label", color_classes)
return renderer
def action_area(self, point, button):
# actions only on left click
if button != Qt.LeftButton:
return
# if no mode is selected ignore map clicks
if self.mode == 0:
return
features = [feat for feat in self.classification_layer.getFeatures()]
geo_pt = QgsGeometry.fromPointXY(point)
map_crs = self.canvas.mapSettings().destinationCrs()
layer_crs = self.classification_layer.crs()
if not map_crs.authid() == layer_crs.authid():
geo_pt.transform(QgsCoordinateTransform(map_crs, layer_crs, QgsProject.instance()))
feat_id = -1
for feat in features:
if geo_pt.within(feat.geometry()):
feat_id = feat.id()
# exit the loop once the features is found
break
# action only if a click is inside a rectangle
if feat_id != -1:
if self.mode == 1:
self.split_area(feat_id)
elif self.mode == 2:
self.accept_area(feat_id)
else:
self.reject_area(feat_id)
def split_area(self, feat_id):
split_feature = self.classification_layer.getFeature(feat_id)
split_rectangle = split_feature.geometry().boundingBox()
x_max = split_rectangle.xMaximum()
x_min = split_rectangle.xMinimum()
y_max = split_rectangle.yMaximum()
y_min = split_rectangle.yMinimum()
rect_height = split_rectangle.height()
rect_width = split_rectangle.width()
x_half = x_min + rect_width/2
y_half = y_min + rect_height/2
top_left_rect = QgsRectangle(x_min, y_half, x_half, y_max)
top_right_rect = QgsRectangle(x_half, y_half, x_max, y_max)
bottom_left_rect = QgsRectangle(x_min, y_min, x_half, y_half)
bottom_right_rect = QgsRectangle(x_half, y_min, x_max, y_half)
layer_fields = self.classification_layer.fields()
top_left_feat = QgsFeature(layer_fields)
top_left_feat.setGeometry(QgsGeometry.fromRect(top_left_rect))
top_left_feat['Label'] = split_feature['Label']
top_left_feat['Desc'] = split_feature['Desc']
top_right_feat = QgsFeature(layer_fields)
top_right_feat.setGeometry(QgsGeometry.fromRect(top_right_rect))
top_right_feat['Label'] = split_feature['Label']
top_right_feat['Desc'] = split_feature['Desc']
bottom_left_feat = QgsFeature(layer_fields)
bottom_left_feat.setGeometry(QgsGeometry.fromRect(bottom_left_rect))
bottom_left_feat['Label'] = split_feature['Label']
bottom_left_feat['Desc'] = split_feature['Desc']
bottom_right_feat = QgsFeature(layer_fields)
bottom_right_feat.setGeometry(QgsGeometry.fromRect(bottom_right_rect))
bottom_right_feat['Label'] = split_feature['Label']
bottom_right_feat['Desc'] = split_feature['Desc']
data_provider = self.classification_layer.dataProvider()
self.save_state()
self.classification_layer.startEditing()
data_provider.addFeatures([top_left_feat, top_right_feat, bottom_left_feat, bottom_right_feat])
self.classification_layer.deleteFeature(feat_id)
self.classification_layer.commitChanges()
self.classification_layer.triggerRepaint()
if rect_width < 800 or rect_height < 800:
self.message_bar.pushWarning("Small area", "The splitted areas are very small, with a side "
"shorter than 400m.")
def accept_area(self, feat_id):
msg_box = QInputDialog(parent=self.dockwidget)
msg_box.setWindowTitle("Accept description")
msg_box.resize(700, 200)
msg_box.setLabelText("Enter the description for this area")
msg_box.setInputMode(QInputDialog.TextInput)
msg_box.textValueChanged.connect(self.max_desc_length)
self.active_message = msg_box
res = self.active_message.exec()
if res:
self.save_state()
self.classification_layer.startEditing()
label_index = self.classification_layer.fields().indexFromName("Label")
desc_index = self.classification_layer.fields().indexFromName("Desc")
self.classification_layer.changeAttributeValue(feat_id, label_index, "Accepted")
self.classification_layer.changeAttributeValue(feat_id, desc_index, msg_box.textValue())
self.classification_layer.commitChanges()
self.classification_layer.triggerRepaint()
self.active_message = None
def reject_area(self, feat_id):
msg_box = QInputDialog(parent=self.dockwidget)
msg_box.setWindowTitle("Accept description")
msg_box.resize(700, 200)
msg_box.setLabelText("Enter the description for this area")
msg_box.setInputMode(QInputDialog.TextInput)
msg_box.textValueChanged.connect(self.max_desc_length)
self.active_message = msg_box
res = self.active_message.exec()
if res:
self.save_state()
self.classification_layer.startEditing()
field_index = self.classification_layer.fields().indexFromName("Label")
desc_index = self.classification_layer.fields().indexFromName("Desc")
self.classification_layer.changeAttributeValue(feat_id, field_index, "Rejected")
self.classification_layer.changeAttributeValue(feat_id, desc_index, msg_box.textValue())
self.classification_layer.commitChanges()
self.classification_layer.triggerRepaint()
self.active_message = None
def max_desc_length(self, text):
if len(text) > 254:
self.active_message.setTextValue(text[:254])
def deep_copy_layer(self, layer):
crs = layer.crs().authid()
geometry = "Polygon" + "?crs=" + crs
fields = layer.dataProvider().fields().toList()
features = [feat for feat in layer.getFeatures()]
copy_layer = QgsVectorLayer(geometry, "classification_layer", "memory")
copy_layer_data = copy_layer.dataProvider()
copy_layer.startEditing()
copy_layer_data.addAttributes(fields)
copy_layer.updateFields()
copy_layer_data.addFeatures(features)
copy_layer.updateExtents()
copy_layer.commitChanges()
copy_layer.setRenderer(self.create_renderer())
return copy_layer
def save_state(self):
state_layer = self.deep_copy_layer(self.classification_layer)
self.state_queue.append(state_layer)
if len(self.state_queue) > 5:
del self.state_queue[0]
self.dockwidget.undo_button.setEnabled(True)
def undo_action(self):
if len(self.state_queue) > 0:
last_state = self.state_queue.pop()
layer_data = self.classification_layer.dataProvider()
state_features = [feat for feat in last_state.getFeatures()]
feat_ids_remove = [feat.id() for feat in self.classification_layer.getFeatures()]
self.classification_layer.startEditing()
self.classification_layer.deleteFeatures(feat_ids_remove)
layer_data.addFeatures(state_features)
self.classification_layer.updateExtents()
self.classification_layer.commitChanges()
self.classification_layer.triggerRepaint()
if len(self.state_queue) == 0:
self.dockwidget.undo_button.setEnabled(False)
def save_layer(self):
layer_name = self.dockwidget.layer_name.text()
if layer_name == "":
self.message_bar.pushCritical("Error", "The layer name cannot be empty.")
return
save_layer = self.deep_copy_layer(self.classification_layer)
save_layer.setName(layer_name)
QgsProject.instance().addMapLayer(save_layer)
def reorder_layers(self):
if self.classification_layer is not None:
layers = self.canvas.layers()
layers = [layer for layer in layers if layer.id() != self.classification_layer.id()]
layers.insert(0, self.classification_layer)
self.canvas.layersChanged.disconnect(self.reorder_layers)
self.canvas.setLayers(layers)
self.canvas.layersChanged.connect(self.reorder_layers)