forked from minorua/Qgis2threejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
propertypages.py
761 lines (621 loc) · 28.1 KB
/
propertypages.py
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Qgis2threejs
A QGIS plugin
export terrain data, map canvas image and vector data to web browser
-------------------
begin : 2014-03-27
copyright : (C) 2014 Minoru Akagi
email : akaginch@gmail.com
***************************************************************************/
/***************************************************************************
* *
* 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
import re
from PyQt4.QtCore import Qt, SIGNAL, QDir, QSettings, QPoint
from PyQt4.QtGui import QCheckBox, QColor, QColorDialog, QComboBox, QFileDialog, QLineEdit, QMessageBox, QRadioButton, QSlider, QSpinBox, QToolTip, QWidget
from qgis.core import QGis, QgsMapLayer, QgsMapLayerRegistry, QgsRectangle
from ui.ui_worldproperties import Ui_WorldPropertiesWidget
from ui.ui_controlsproperties import Ui_ControlsPropertiesWidget
from ui.ui_demproperties import Ui_DEMPropertiesWidget
from ui.ui_vectorproperties import Ui_VectorPropertiesWidget
from rotatedrect import RotatedRect
from qgis2threejsmain import ObjectTreeItem, createQuadTree
from stylewidget import StyleWidget
import qgis2threejstools as tools
from qgis2threejstools import logMessage
from settings import def_vals
PAGE_NONE = 0
PAGE_WORLD = 1
PAGE_CONTROLS = 2
PAGE_DEM = 3
PAGE_VECTOR = 4
def is_number(val):
try:
float(val)
return True
except ValueError:
return False
class PropertyPage(QWidget):
def __init__(self, pageType, dialog, parent=None):
QWidget.__init__(self, parent)
self.pageType = pageType
self.dialog = dialog
self.propertyWidgets = []
self.defaultProperties = {}
def itemChanged(self, item):
pass
def setLayoutVisible(self, layout, visible):
for i in range(layout.count()):
item = layout.itemAt(i)
w = item.widget()
if w is not None:
w.setVisible(visible)
continue
l = item.layout()
if l is not None:
self.setLayoutVisible(l, visible)
def setLayoutsVisible(self, layouts, visible):
for layout in layouts:
self.setLayoutVisible(layout, visible)
def setWidgetsVisible(self, widgets, visible):
for w in widgets:
w.setVisible(visible)
def setLayoutEnabled(self, layout, enabled):
for i in range(layout.count()):
item = layout.itemAt(i)
w = item.widget()
if w is not None:
w.setEnabled(enabled)
continue
l = item.layout()
if l is not None:
self.setLayoutEnabled(l, enabled)
def setLayoutsEnabled(self, layouts, enabled):
for layout in layouts:
self.setLayoutEnabled(layout, enabled)
def setWidgetsEnabled(self, widgets, enabled):
for w in widgets:
w.setEnabled(enabled)
def registerPropertyWidgets(self, widgets):
self.propertyWidgets = widgets
# save default properties
self.defaultProperties = self.properties()
def properties(self):
p = {}
for w in self.propertyWidgets:
v = None
if isinstance(w, QComboBox):
index = w.currentIndex()
if index == -1:
v = None
else:
v = w.itemData(index)
elif isinstance(w, QRadioButton):
if not w.isChecked():
continue
v = w.isChecked()
elif isinstance(w, QCheckBox):
v = w.isChecked()
elif isinstance(w, (QSlider, QSpinBox)):
v = w.value()
elif isinstance(w, QLineEdit):
v = w.text()
elif isinstance(w, StyleWidget):
v = w.values()
else:
logMessage("[propertypages.py] Not recognized widget type: " + unicode(type(w)))
p[w.objectName()] = v
return p
def setProperties(self, properties):
for n, v in properties.items():
w = getattr(self, n, None)
if w is None:
continue
if isinstance(w, QComboBox):
if v is not None:
index = w.findData(v)
if index != -1:
w.setCurrentIndex(index)
elif isinstance(w, (QRadioButton, QCheckBox)): # subclass of QAbstractButton
w.setChecked(v)
elif isinstance(w, (QSlider, QSpinBox)):
w.setValue(v)
elif isinstance(w, QLineEdit):
w.setText(v)
elif isinstance(w, StyleWidget):
if len(v):
w.setValues(v)
else:
logMessage("[propertypages.py] Cannot restore %s property" % n)
class WorldPropertyPage(PropertyPage, Ui_WorldPropertiesWidget):
def __init__(self, dialog, parent=None):
PropertyPage.__init__(self, PAGE_WORLD, dialog, parent)
Ui_WorldPropertiesWidget.setupUi(self, self)
self.registerPropertyWidgets([self.lineEdit_BaseSize, self.lineEdit_zFactor, self.lineEdit_zShift, self.radioButton_Color, self.lineEdit_Color, self.radioButton_WGS84])
self.toolButton_Color.clicked.connect(self.colorButtonClicked)
def setup(self, properties=None):
apiChanged23 = QGis.QGIS_VERSION_INT >= 20300
canvas = self.dialog.iface.mapCanvas()
extent = canvas.extent()
outsize = canvas.mapSettings().outputSize() if apiChanged23 else canvas.mapRenderer()
self.lineEdit_MapCanvasExtent.setText("%.4f, %.4f - %.4f, %.4f" % (extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum()))
self.lineEdit_MapCanvasSize.setText("{0} x {1}".format(outsize.width(), outsize.height()))
# restore properties
if properties:
self.setProperties(properties)
else:
self.lineEdit_BaseSize.setText(str(def_vals.baseSize))
self.lineEdit_zFactor.setText(str(def_vals.zExaggeration))
self.lineEdit_zShift.setText(str(def_vals.zShift))
# Supported projections
# https://github.com/proj4js/proj4js
projs = ["longlat", "merc"]
projs += ["aea", "aeqd", "cass", "cea", "eqc", "eqdc", "gnom", "krovak", "laea", "lcc", "mill", "moll",
"nzmg", "omerc", "poly", "sinu", "somerc", "stere", "sterea", "tmerc", "utm", "vandg"]
mapSettings = canvas.mapSettings() if apiChanged23 else canvas.mapRenderer()
proj = mapSettings.destinationCrs().toProj4()
m = re.search("\+proj=(\w+)", proj)
proj_supported = bool(m and m.group(1) in projs)
if not proj_supported:
self.radioButton_ProjectCRS.setChecked(True)
self.radioButton_WGS84.setEnabled(proj_supported)
def colorButtonClicked(self):
color = QColorDialog.getColor(QColor(self.lineEdit_Color.text().replace("0x", "#")))
if color.isValid():
self.lineEdit_Color.setText(color.name().replace("#", "0x"))
def properties(self):
p = PropertyPage.properties(self)
# check validity
if not is_number(self.lineEdit_BaseSize.text()):
p["lineEdit_BaseSize"] = str(def_vals.baseSize)
if not is_number(self.lineEdit_zFactor.text()):
p["lineEdit_zFactor"] = str(def_vals.zExaggeration)
if not is_number(self.lineEdit_zShift.text()):
p["lineEdit_zShift"] = str(def_vals.zShift)
return p
class ControlsPropertyPage(PropertyPage, Ui_ControlsPropertiesWidget):
def __init__(self, dialog, parent=None):
PropertyPage.__init__(self, PAGE_CONTROLS, dialog, parent)
Ui_ControlsPropertiesWidget.setupUi(self, self)
self.controlsDir = os.path.join(tools.pluginDir(), "js", "threejs", "controls")
self.initControlsList()
self.registerPropertyWidgets([self.comboBox_Controls])
self.comboBox_Controls.currentIndexChanged.connect(self.controlsChanged)
def setup(self, properties=None):
# restore properties
comboBox = self.comboBox_Controls
comboBox.blockSignals(True)
if properties:
self.setProperties(properties)
else:
controls = QSettings().value("/Qgis2threejs/lastControls", "OrbitControls.js", type=unicode)
index = comboBox.findText(controls)
if index != -1:
comboBox.setCurrentIndex(index)
comboBox.blockSignals(False)
self.controlsChanged(comboBox.currentIndex())
def initControlsList(self):
# list controls
self.comboBox_Controls.clear()
for entry in QDir(self.controlsDir).entryList(["*.js"]):
self.comboBox_Controls.addItem(entry, entry)
def controlsChanged(self, index):
controls = self.comboBox_Controls.itemText(index)
descFile = os.path.splitext(os.path.join(self.controlsDir, controls))[0] + ".txt"
if os.path.exists(descFile):
with open(descFile) as f:
desc = f.read()
else:
desc = "No description"
self.textEdit.setText(desc)
class DEMPropertyPage(PropertyPage, Ui_DEMPropertiesWidget):
def __init__(self, dialog, parent=None):
PropertyPage.__init__(self, PAGE_DEM, dialog, parent)
Ui_DEMPropertiesWidget.setupUi(self, self)
# set read only to line edits of spin boxes
self.spinBox_Size.findChild(QLineEdit).setReadOnly(True)
self.spinBox_Roughening.findChild(QLineEdit).setReadOnly(True)
self.isPrimary = False
self.layer = None
self.demWidth = self.demHeight = 0
self.layerImageIds = []
dispTypeButtons = [self.radioButton_MapCanvas, self.radioButton_LayerImage, self.radioButton_ImageFile, self.radioButton_SolidColor]
widgets = [self.comboBox_DEMLayer, self.spinBox_demtransp]
widgets += [self.radioButton_Simple, self.horizontalSlider_Resolution]
widgets += [self.checkBox_Surroundings, self.spinBox_Size, self.spinBox_Roughening]
widgets += [self.radioButton_Advanced, self.spinBox_Height, self.lineEdit_centerX, self.lineEdit_centerY, self.lineEdit_rectWidth, self.lineEdit_rectHeight]
widgets += dispTypeButtons
widgets += [self.checkBox_TransparentBackground, self.lineEdit_ImageFile, self.lineEdit_Color, self.comboBox_TextureSize, self.checkBox_Shading]
widgets += [self.checkBox_Clip, self.comboBox_ClipLayer]
widgets += [self.checkBox_Sides, self.checkBox_Frame]
self.registerPropertyWidgets(widgets)
self.initLayerComboBox()
self.initTextureSizeComboBox()
self.comboBox_DEMLayer.currentIndexChanged.connect(self.demLayerChanged)
self.horizontalSlider_Resolution.valueChanged.connect(self.resolutionSliderChanged)
self.radioButton_Simple.toggled.connect(self.samplingModeChanged)
self.checkBox_Surroundings.toggled.connect(self.surroundingsToggled)
self.spinBox_Roughening.valueChanged.connect(self.rougheningChanged)
self.spinBox_Height.valueChanged.connect(self.updateQuads)
for radioButton in dispTypeButtons:
radioButton.toggled.connect(self.dispTypeChanged)
self.toolButton_SelectLayer.clicked.connect(self.selectLayerClicked)
self.toolButton_ImageFile.clicked.connect(self.browseClicked)
self.toolButton_Color.clicked.connect(self.colorButtonClicked)
self.toolButton_PointTool.clicked.connect(dialog.startPointSelection)
def setup(self, properties=None, layer=None, isPrimary=True):
self.isPrimary = isPrimary
self.layer = layer
self.setLayoutsVisible([self.formLayout_DEMLayer, self.verticalLayout_Advanced, self.formLayout_Surroundings], isPrimary)
self.setWidgetsVisible([self.radioButton_Advanced], isPrimary)
self.setWidgetsVisible([self.toolButton_PointTool], False)
self.setEnabled(isPrimary or self.dialog.currentItem.data(0, Qt.CheckStateRole) == Qt.Checked)
# select dem layer
layerId = None
if layer is not None:
layerId = layer.id()
self.comboBox_DEMLayer.blockSignals(True)
currentIndex = self.selectDEMLayer(layerId)
self.comboBox_DEMLayer.blockSignals(False)
self.groupBox_Resampling.setEnabled(True)
self.demLayerChanged(currentIndex)
# use default properties if properties is not set
if not properties:
properties = self.defaultProperties
properties["comboBox_TextureSize"] = 100
properties["checkBox_Sides"] = self.isPrimary
# restore properties of the layer
self.spinBox_Height.blockSignals(True)
self.setProperties(properties)
self.spinBox_Height.blockSignals(False)
self.calculateResolution()
self.updateLayerImageLabel()
# set enablement and visibility of widgets
if isPrimary:
self.samplingModeChanged(True)
self.surroundingsToggled(self.checkBox_Surroundings.isChecked())
self.dispTypeChanged()
if isPrimary:
# enable map tool to select focus area
self.connect(self.dialog.mapTool, SIGNAL("rectangleCreated()"), self.rectangleSelected)
self.dialog.startPointSelection()
else:
self.checkBox_Sides.setChecked(False) # no sides with additional dem
def initLayerComboBox(self):
# list of 1 band raster layers and plugin dem providers
comboDEM = self.comboBox_DEMLayer
comboDEM.clear()
comboDEM.addItem("Flat plane (no DEM used)", 0)
# plugin dem providers
for plugin in self.dialog.pluginManager.demProviderPlugins():
comboDEM.addItem(plugin.providerName(), "plugin:" + plugin.providerId())
# list of polygon layers
comboPolygon = self.comboBox_ClipLayer
comboPolygon.clear()
for layer in self.dialog.iface.legendInterface().layers():
if layer.type() == QgsMapLayer.RasterLayer:
if layer.providerType() == "gdal" and layer.bandCount() == 1:
comboDEM.addItem(layer.name(), layer.id())
elif layer.type() == QgsMapLayer.VectorLayer:
if layer.geometryType() == QGis.Polygon:
comboPolygon.addItem(layer.name(), layer.id())
def initTextureSizeComboBox(self):
canvas = self.dialog.iface.mapCanvas()
outsize = canvas.mapSettings().outputSize() if QGis.QGIS_VERSION_INT >= 20300 else canvas.mapRenderer()
self.comboBox_TextureSize.clear()
for i in [4, 2, 1]:
percent = i * 100
text = "{0} % ({1} x {2} px)".format(percent, outsize.width() * i, outsize.height() * i)
self.comboBox_TextureSize.addItem(text, percent)
def selectDEMLayer(self, layerId=None):
comboBox = self.comboBox_DEMLayer
if layerId is not None:
# select the last selected layer
index = comboBox.findData(layerId)
if index != -1:
comboBox.setCurrentIndex(index)
return index
elif comboBox.count() > 1:
# select the first 1 band raster layer
comboBox.setCurrentIndex(1)
return 1
# combo box has one item "(Flat plane)"
return 0
def demLayerChanged(self, index):
if not self.isPrimary:
return
comboBox = self.comboBox_DEMLayer
useDEM = comboBox.itemData(index) != 0
self.groupBox_Resampling.setEnabled(useDEM)
if not useDEM:
self.checkBox_Surroundings.setChecked(False)
self.dialog.primaryDEMChanged(comboBox.itemData(index))
def resolutionSliderChanged(self, v):
self.calculateResolution()
size = 100 * self.horizontalSlider_Resolution.value()
QToolTip.showText(self.horizontalSlider_Resolution.mapToGlobal(QPoint(0, 0)), "about {0} x {0}".format(size), self.horizontalSlider_Resolution)
def itemChanged(self, item):
if not self.isPrimary:
self.setEnabled(item.data(0, Qt.CheckStateRole) == Qt.Checked)
def selectLayerClicked(self):
if QGis.QGIS_VERSION_INT < 20400:
QMessageBox.warning(self, "Qgis2threejs", "Sorry, newer QGIS version (>= 2.4) is required.")
return
from layerselectdialog import LayerSelectDialog
dialog = LayerSelectDialog(self)
dialog.initTree(self.layerImageIds)
dialog.setMapSettings(self.dialog.iface.mapCanvas().mapSettings())
if not dialog.exec_():
return
layers = dialog.visibleLayers()
self.layerImageIds = [layer.id() for layer in layers]
self.updateLayerImageLabel()
def updateLayerImageLabel(self):
self.label_LayerImage.setText(tools.shortTextFromSelectedLayerIds(self.layerImageIds))
def browseClicked(self):
directory = os.path.split(self.lineEdit_ImageFile.text())[0]
if directory == "":
directory = QDir.homePath()
filterString = "Images (*.png *.jpg *.gif *.bmp);;All files (*.*)"
filename = QFileDialog.getOpenFileName(self, "Select image file", directory, filterString)
if filename:
self.lineEdit_ImageFile.setText(filename)
def colorButtonClicked(self):
color = QColorDialog.getColor(QColor(self.lineEdit_Color.text().replace("0x", "#")))
if color.isValid():
self.lineEdit_Color.setText(color.name().replace("#", "0x"))
def surroundingsToggled(self, checked):
self.calculateResolution()
self.setLayoutEnabled(self.gridLayout_Surroundings, checked)
is_simple = self.radioButton_Simple.isChecked()
is_simple_wo_surroundings = is_simple and not checked
self.setWidgetsEnabled([self.radioButton_ImageFile, self.groupBox_Clip, self.groupBox_Accessories], is_simple_wo_surroundings)
if checked and self.radioButton_ImageFile.isChecked():
self.radioButton_MapCanvas.setChecked(True)
def rougheningChanged(self, v):
self.calculateResolution()
# possible value is a power of 2
self.spinBox_Roughening.setSingleStep(v)
self.spinBox_Roughening.setMinimum(max(v / 2, 1))
def hide(self):
PropertyPage.hide(self)
if self.isPrimary:
self.disconnect(self.dialog.mapTool, SIGNAL("rectangleCreated()"), self.rectangleSelected)
self.dialog.endPointSelection()
def calculateResolution(self, v=None):
canvas = self.dialog.iface.mapCanvas()
size = 100 * self.horizontalSlider_Resolution.value()
# calculate resolution and size
outsize = canvas.mapSettings().outputSize() if QGis.QGIS_VERSION_INT >= 20300 else canvas.mapRenderer()
width, height = outsize.width(), outsize.height()
s = (size * size / float(width * height)) ** 0.5
if s < 1:
width = int(width * s)
height = int(height * s)
if self.checkBox_Surroundings.isChecked():
roughening = self.spinBox_Roughening.value()
if width % roughening != 0:
width = int(float(width) / roughening + 0.9) * roughening
if height % roughening != 0:
height = int(float(height) / roughening + 0.9) * roughening
self.demWidth = width + 1
self.demHeight = height + 1
self.label_Resolution.setText("{0} x {1} px".format(self.demWidth, self.demHeight))
mupp = canvas.mapUnitsPerPixel()
xres = (mupp * outsize.width()) / width
yres = (mupp * outsize.height()) / height
self.lineEdit_HRes.setText(str(xres))
self.lineEdit_VRes.setText(str(yres))
def properties(self):
p = PropertyPage.properties(self)
item = self.dialog.currentItem
if item is not None:
p["visible"] = item.data(0, Qt.CheckStateRole) == Qt.Checked
p["dem_Width"] = self.demWidth
p["dem_Height"] = self.demHeight
if self.layerImageIds:
p["layerImageIds"] = self.layerImageIds
return p
def setProperties(self, properties):
PropertyPage.setProperties(self, properties)
self.layerImageIds = properties.get("layerImageIds", [])
def updateQuads(self, v=None):
isSimpleMode = self.radioButton_Simple.isChecked()
if isSimpleMode:
self.dialog.clearRubberBands()
return
apiChanged23 = QGis.QGIS_VERSION_INT >= 20300
canvas = self.dialog.iface.mapCanvas()
mapSettings = canvas.mapSettings() if apiChanged23 else canvas.mapRenderer()
baseExtent = RotatedRect.fromMapSettings(mapSettings)
p = {"lineEdit_centerX": self.lineEdit_centerX.text(),
"lineEdit_centerY": self.lineEdit_centerY.text(),
"lineEdit_rectWidth": self.lineEdit_rectWidth.text(),
"lineEdit_rectHeight": self.lineEdit_rectHeight.text(),
"spinBox_Height": self.spinBox_Height.value()}
quadtree = createQuadTree(baseExtent, p)
if quadtree:
self.dialog.createRubberBands(baseExtent, quadtree)
self.dialog.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)
else:
self.dialog.clearRubberBands()
def rectangleSelected(self):
self.radioButton_Advanced.setChecked(True)
rect = self.dialog.mapTool.rectangle() # RotatedRect object
toRect = rect.width() and rect.height()
self.switchFocusMode(toRect)
center = rect.center()
self.lineEdit_centerX.setText(str(center.x()))
self.lineEdit_centerY.setText(str(center.y()))
self.lineEdit_rectWidth.setText(str(rect.width()))
self.lineEdit_rectHeight.setText(str(rect.height()))
# update quad rubber bands
self.updateQuads()
def dispTypeChanged(self, checked=True):
if checked:
if self.radioButton_MapCanvas.isChecked():
t = 0
elif self.radioButton_LayerImage.isChecked():
t = 1
elif self.radioButton_ImageFile.isChecked():
t = 2
else: # self.radioButton_SolidColor.isChecked():
t = 3
self.setWidgetsEnabled([self.label_TextureSize, self.comboBox_TextureSize], t in [0, 1])
self.checkBox_TransparentBackground.setEnabled(t in [0, 1, 2])
if t in [0, 1]:
self.checkBox_TransparentBackground.setText("Transparent background")
elif t == 2:
self.checkBox_TransparentBackground.setText("Enable transparency")
def samplingModeChanged(self, checked):
isSimpleMode = self.radioButton_Simple.isChecked()
isAdvancedMode = not isSimpleMode
surroundings = self.checkBox_Surroundings.isChecked()
is_simple_wo_surroundings = isSimpleMode and not surroundings
self.setLayoutsEnabled([self.verticalLayout_Simple], isSimpleMode)
self.setLayoutsEnabled([self.gridLayout_Surroundings], isSimpleMode and surroundings)
self.setWidgetsEnabled([self.radioButton_ImageFile, self.groupBox_Clip, self.groupBox_Accessories], is_simple_wo_surroundings)
if self.isPrimary:
self.setLayoutsVisible([self.horizontalLayout_Advanced1, self.horizontalLayout_Advanced3], isAdvancedMode)
self.setWidgetsVisible([self.label_Focus], isAdvancedMode)
if isSimpleMode:
self.setLayoutVisible(self.horizontalLayout_Advanced4, False)
else:
try:
isPoint = (float(self.lineEdit_rectWidth.text()) == 0 and float(self.lineEdit_rectHeight.text()) == 0)
except ValueError:
isPoint = True
self.switchFocusMode(not isPoint)
if isAdvancedMode and self.radioButton_ImageFile.isChecked():
self.radioButton_MapCanvas.setChecked(True)
# update quad rubber bands
self.updateQuads()
def switchFocusMode(self, toRect):
toPoint = not toRect
self.setLayoutVisible(self.horizontalLayout_Advanced4, toRect)
selection = "area" if toRect else "point"
action = "Stroke a rectangle" if toRect else "Click"
self.label_Focus.setText("Focus {0} ({1} on map canvas to set values)".format(selection, action))
class VectorPropertyPage(PropertyPage, Ui_VectorPropertiesWidget):
STYLE_MAX_COUNT = 6
def __init__(self, dialog, parent=None):
PropertyPage.__init__(self, PAGE_VECTOR, dialog, parent)
Ui_VectorPropertiesWidget.setupUi(self, self)
self.layer = None
# initialize vector style widgets
self.heightWidget = StyleWidget(StyleWidget.HEIGHT)
self.heightWidget.setObjectName("heightWidget")
self.verticalLayout_zCoordinate.addWidget(self.heightWidget)
self.labelHeightWidget = StyleWidget(StyleWidget.LABEL_HEIGHT)
self.labelHeightWidget.setObjectName("labelHeightWidget")
self.labelHeightWidget.setEnabled(False)
self.verticalLayout_Label.addWidget(self.labelHeightWidget)
self.styleWidgetCount = 0
self.styleWidgets = []
for i in range(self.STYLE_MAX_COUNT):
objName = "styleWidget" + str(i)
widget = StyleWidget()
widget.setVisible(False)
widget.setObjectName(objName)
self.styleWidgets.append(widget)
self.verticalLayout_Styles.addWidget(widget)
# assign the widget to property page attribute
setattr(self, objName, widget)
widgets = [self.comboBox_ObjectType, self.heightWidget] + self.styleWidgets
widgets += [self.radioButton_AllFeatures, self.radioButton_IntersectingFeatures, self.checkBox_Clip]
widgets += [self.checkBox_ExportAttrs, self.comboBox_Label, self.labelHeightWidget]
self.registerPropertyWidgets(widgets)
self.comboBox_ObjectType.currentIndexChanged.connect(self.setupStyleWidgets)
self.heightWidget.comboBox.currentIndexChanged.connect(self.altitudeModeChanged)
self.checkBox_ExportAttrs.toggled.connect(self.exportAttrsToggled)
def setup(self, properties=None, layer=None):
self.layer = layer
self.setEnabled(self.dialog.currentItem.data(0, Qt.CheckStateRole) == Qt.Checked)
for i in range(self.STYLE_MAX_COUNT):
self.styleWidgets[i].hide()
obj_types = self.dialog.objectTypeManager.objectTypeNames(layer.geometryType())
# set up object type combo box
self.comboBox_ObjectType.blockSignals(True)
self.comboBox_ObjectType.clear()
for index, obj_type in enumerate(obj_types):
self.comboBox_ObjectType.addItem(obj_type, index)
if properties:
# restore object type selection
self.comboBox_ObjectType.setCurrentIndex(properties.get("comboBox_ObjectType", 0))
self.comboBox_ObjectType.blockSignals(False)
# get MapTo3D object to calculate default values
mapTo3d = self.dialog.mapTo3d()
# set up height widget and label height widget
self.heightWidget.setup(options={"layer": layer})
if layer.geometryType() != QGis.Line:
defaultLabelHeight = 5
self.labelHeightWidget.setup(options={"layer": layer, "defaultValue": defaultLabelHeight / mapTo3d.multiplierZ})
else:
self.labelHeightWidget.hide()
# point layer has no geometry clip option
self.checkBox_Clip.setVisible(layer.geometryType() != QGis.Point)
# set up style widgets for selected object type
self.setupStyleWidgets()
# set up label combo box
hasPoint = (layer.geometryType() in (QGis.Point, QGis.Polygon))
self.setLayoutVisible(self.formLayout_Label, hasPoint)
self.comboBox_Label.clear()
if hasPoint:
self.comboBox_Label.addItem("(No label)")
fields = self.layer.pendingFields()
for i in range(fields.count()):
self.comboBox_Label.addItem(fields[i].name(), i)
# restore other properties for the layer
self.setProperties(properties or self.defaultProperties)
def setupStyleWidgets(self, index=None):
index = self.comboBox_ObjectType.currentIndex()
# notice 3D model is experimental
is_experimental = self.comboBox_ObjectType.currentText() in ["JSON model", "COLLADA model"]
self.label_ObjectTypeMessage.setVisible(is_experimental)
# get MapTo3D object to calculate default values
mapTo3d = self.dialog.mapTo3d()
# setup widgets
self.dialog.objectTypeManager.setupWidgets(self, mapTo3d, self.layer, self.layer.geometryType(), index)
# update enabled property of feature group box
self.altitudeModeChanged()
def itemChanged(self, item):
self.setEnabled(item.data(0, Qt.CheckStateRole) == Qt.Checked)
def altitudeModeChanged(self, index=None):
geom_type = self.layer.geometryType()
type_index = self.comboBox_ObjectType.currentIndex()
only_clipped = False
if (geom_type == QGis.Line and type_index == 4) or (geom_type == QGis.Polygon and type_index == 1): # Profile or Overlay
if self.heightWidget.func.isCurrentItemRelativeHeight():
only_clipped = True
self.radioButton_IntersectingFeatures.setChecked(True)
self.checkBox_Clip.setChecked(True)
self.groupBox_Features.setEnabled(not only_clipped)
def exportAttrsToggled(self, checked):
self.setLayoutEnabled(self.formLayout_Label, checked)
self.labelHeightWidget.setEnabled(checked)
def properties(self):
p = PropertyPage.properties(self)
item = self.dialog.currentItem
if item is not None:
p["visible"] = item.data(0, Qt.CheckStateRole) == Qt.Checked
return p
def initStyleWidgets(self, color=True, transparency=True):
self.styleWidgetCount = 0
if color:
self.addStyleWidget(StyleWidget.COLOR)
if transparency:
self.addStyleWidget(StyleWidget.TRANSPARENCY)
for i in range(self.styleWidgetCount, self.STYLE_MAX_COUNT):
self.styleWidgets[i].hide()
def addStyleWidget(self, funcType=None, options=None):
self.styleWidgets[self.styleWidgetCount].setup(funcType, options)
self.styleWidgetCount += 1