forked from GIAPspzoo/GIAP_PolaMap_lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic_layout.py
1170 lines (1005 loc) · 48.8 KB
/
dynamic_layout.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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import webbrowser
from plugins.processing.tools.general import execAlgorithmDialog
from qgis.PyQt.QtCore import Qt, QSize, QEvent, pyqtSignal, QMimeData, QRect
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QDrag, QPainter, QPixmap, QCursor, QIcon, QFont, QFontMetrics
from qgis.PyQt.QtWidgets import QWidget, QApplication, QHBoxLayout, \
QFrame, QLabel, QPushButton, QTabBar, QToolButton, QVBoxLayout, \
QGridLayout, QSpacerItem, QLineEdit, QWidgetItem, QAction, \
QBoxLayout, QMessageBox, QWidgetAction, QSizePolicy, QScrollArea
from qgis._core import QgsApplication
from qgis.utils import iface
from .config import Config
from .CustomMessageBox import CustomMessageBox
from .utils import STANDARD_TOOLS, DEFAULT_TABS, tr
from .select_section import SelectSection
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'dynamic_layout.ui'))
class Widget(QWidget, FORM_CLASS):
editChanged = pyqtSignal(bool)
printsAdded = pyqtSignal()
deletePressSignal = pyqtSignal()
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setupUi(self)
self.parent = parent # mainWindow()
self.tabs = [] # list w tabwidgets
self.edit_session = False
self.conf = Config()
self.save = QMessageBox.Yes
# Custom Tools
self.orto_add = False
self.custom_tabbar = CustomTabBar(tr('New tab'), self.tabWidget)
self.tabWidget.setTabBar(self.custom_tabbar)
self.tabWidget.tabBar().tabBarClicked.connect(self.tab_clicked)
self.tabWidget.tabBar().tabBarDoubleClicked.connect(
self.tab_doubleclicked)
def add_tab(self, label=None):
"""Adds new tab at the end
:return: tab widget
"""
if not label:
label = 'New tab'
label = tr(label)
tab = CustomTab(label, self.tabWidget)
self.tabs.append(tab)
# prevent flickering
self.tabWidget.setUpdatesEnabled(False)
tab_ind = self.tabWidget.insertTab(
self.tabWidget.count()-1, tab, label
)
if self.edit_session:
self._section_control(tab_ind)
self.tabWidget.setCurrentIndex(tab_ind)
# add button to delete, its edit session so should be visible
right = self.tabWidget.tabBar().RightSide
cbutton = QToolButton(self.tabWidget)
cbutton.setObjectName('ribCloseTab')
cbutton.setText('x')
cbutton.setMinimumSize(QSize(16, 16))
cbutton.setMaximumSize(QSize(16, 16))
self.tabWidget.tabBar().setTabButton(tab_ind, right, cbutton)
cbutton.clicked.connect(lambda: self.remove_tab(tab_ind))
self.tabWidget.setUpdatesEnabled(True)
return tab_ind, tab
def remove_tab(self, tind):
"""Removes tab with given tab index"""
self.tabWidget.removeTab(tind)
if tind > 0:
self.tabWidget.setCurrentIndex(tind-1)
def add_section(self, itab, lab, size=30):
"""Adds new section on tab with label and place for icons
:itab: int
:lab: label for section
:size: int size of button
:return: section widget
"""
if itab > -1:
itab = self.tabWidget.currentIndex()
cwidget = self.tabWidget.widget(itab)
if str(lab) in ['', 'False', 'None']:
lab = tr('New section')
section = CustomSection(str(lab), self.tabWidget)
section.installEventFilter(self)
if size > 30:
section.set_size(size)
self._section_control_remove(itab)
cwidget.lay.addWidget(section)
# sep = QFrame()
# sep.setFrameShape(QFrame.VLine)
# sep.setFrameShadow(QFrame.Raised)
# sep.setObjectName('ribLine')
# sep.setMinimumSize(QSize(6, 100))
# cwidget.lay.addWidget(sep)
section.setVisible(True)
self._section_control(itab)
return section
def edit_session_toggle(self, ask=False):
"""Show controls for edti session"""
self.edit_session = not self.edit_session
self.conf = Config()
if ask and self.conf.setts['ribbons_config'] != self.generate_ribbon_config():
self.save = CustomMessageBox(None, tr(f"""<html><head/><body><b>Do you want to save your changes<br></body></html>""")).button_yes_no()
if self.save == QMessageBox.Yes:
self.editChanged.emit(False)
else:
self.editChanged.emit(True)
else:
self.editChanged.emit(self.edit_session)
self._tab_controls()
def _tab_controls(self):
""" show tab controls"""
right = self.tabWidget.tabBar().RightSide
if self.edit_session:
for i in range(self.tabWidget.count()):
self.tabWidget.tabBar().tabButton(i, right).show()
self._section_control(i)
self._new_tab_tab_control() # show add tab option
else:
self._new_tab_tab_control() # hide add tab option
for i in range(self.tabWidget.count()):
self.tabWidget.tabBar().tabButton(i, right).hide()
self._section_control(i)
def _section_control(self, tabind):
"""add buttons to every tab for adding new section"""
plug_dir = os.path.dirname(__file__)
lay = self.tabWidget.widget(tabind).lay
cnt = lay.count()
# remove button
it = lay.itemAt(cnt-1)
if it is not None:
if isinstance(it.widget(), QPushButton):
it.widget().hide()
it.widget().deleteLater()
QApplication.processEvents()
if self.edit_session:
self.instr = QLabel()
self.instr.setText(f"""<html><head/><body><b>{tr('Edit tools within a section:')}</b><br>
<b>{tr('Moving tools')}</b> - {tr('click and hold the left mouse button')}<br>
{tr('on the icon and move it to the desired location')}<br><br>
<b>{tr('Tool removal')}</b> - {tr('double click')}<br>
{tr('tool icon and click delete button')}</body></html>""")
scrll = QScrollArea(self)
scrll.setWidgetResizable(True)
scrll.setWidget(self.instr)
self.instr.setStyleSheet(
"""QFrame, QLabel, QToolTip, QTextEdit{
font:9pt}"""
)
self.instr.setTextFormat(Qt.AutoText)
self.instr.setScaledContents(True)
self.frm = QFrame()
self.frm.setObjectName('ribSectionAdd')
self.frmlay = QHBoxLayout(self.frm)
self.secadd = CustomSectionAdd()
self.secadd.clicked.connect(self.add_user_selected_section)
self.frmlay.addWidget(self.secadd)
self.frmlay.addStretch()
self.frmlay.addStretch()
self.frmlay.addWidget(scrll)
lay = self.tabWidget.widget(tabind).lay
cnt = lay.count()
# there should always be something in layout, (controls)
for i in range(cnt, -1, -1):
if isinstance(lay.itemAt(i), QSpacerItem):
lay.removeItem(lay.itemAt(i))
self.tabWidget.widget(tabind).lay.addWidget(self.frm)
else:
self.tabWidget.widget(tabind).setUpdatesEnabled(False)
self._section_control_remove(tabind)
self.tabWidget.widget(tabind).lay.addStretch()
self.tabWidget.widget(tabind).setUpdatesEnabled(True)
def add_user_selected_section(self):
"""Show dialog to user and adds selected section to current ribbon
if there should be more cutom tools, here is the place to put them
"""
self.dlg = SelectSection()
self.run_select_section()
responce = self.dlg.exec_()
if not responce:
return
ind = self.tabWidget.currentIndex()
# selected tools
selected = [x.text() for x in self.dlg.toolList.selectedItems()]
self.tabWidget.setUpdatesEnabled(True)
print_trig = False
for sel in selected:
secdef = [x for x in STANDARD_TOOLS if tr(x['label']) == sel][0]
sec = self.add_section(ind, sel, secdef['btn_size'])
for btn in secdef['btns']:
child = self.parent.findChild(QAction, btn[0])
if child is None:
sec.add_action(*btn)
self.tabWidget.setUpdatesEnabled(True)
def run_select_section(self):
self.dlg.addSectionTab.clicked.connect(self.next_widget)
self.dlg.searchToolTab.clicked.connect(self.previous_widget)
self.dlg.addAlgButton.clicked.connect(self.add_to_ribbon)
self.dlg.searchBox.textChanged.connect(self.search_tree)
def add_to_ribbon(self):
self.tabWidget.setUpdatesEnabled(True)
sel_ind = self.dlg.algorithmTree.selectedIndexes()
tool = {}
for ind in sel_ind:
alg_ind = 0
alg = self.dlg.algorithmTree.algorithmForIndex(ind)
if alg:
if not alg.group() in tool:
tool[alg.group()] = []
tool[alg.group()].append(alg)
elif self.dlg.algorithmTree.algorithmForIndex(ind.child(0, 0)):
alg = self.dlg.algorithmTree.algorithmForIndex(ind.child(alg_ind, 0))
while alg:
if not alg.group() in tool:
tool[alg.group()] = []
tool[alg.group()].append(alg)
alg_ind += 1
alg = self.dlg.algorithmTree.algorithmForIndex(ind.child(alg_ind, 0))
else:
CustomMessageBox(self.dlg, tr("Select item has sub-section")).button_ok()
return
for group in tool:
tool[group] = list(set(tool[group]))
for name_sec in tool:
section = self.add_section(self.tabWidget.currentIndex(), name_sec, 30)
row = 0
col = 0
for alg in tool[name_sec]:
section.add_action(alg.id(), row, col)
if row == 1:
row = 0
col += 1
else:
row += 1
self.tabWidget.setUpdatesEnabled(True)
self.dlg.close()
def search_tree(self):
self.dlg.algorithmTree.setFilterString(self.dlg.searchBox.value())
def next_widget(self):
self.dlg.stackedWidget.setCurrentIndex(0)
def previous_widget(self):
self.dlg.stackedWidget.setCurrentIndex(1)
def _section_control_remove(self, tabind):
lay = self.tabWidget.widget(tabind).lay
self.tabWidget.setUpdatesEnabled(False)
for ind in range(lay.count()-1, -1, -1):
if isinstance(lay.itemAt(ind), QSpacerItem):
lay.removeItem(lay.itemAt(ind))
continue
it = lay.itemAt(ind)
if it.widget() is not None:
if it.widget().objectName() == 'ribSectionAdd':
it.widget().hide()
lay.removeItem(it)
QApplication.processEvents()
self.tabWidget.setUpdatesEnabled(True)
def _new_tab_tab_control(self):
"""Pseudo tab to control adding fully feature tab"""
self.tabWidget.setUpdatesEnabled(False)
if self.edit_session:
tab = QWidget()
tab.setObjectName('ribAddNewTabControl')
self.tabWidget.addTab(tab, '+')
else:
last_tab = self.tabWidget.tabBar().count() - 1
if self.tabWidget.widget(last_tab).objectName() == \
'ribAddNewTabControl':
self.tabWidget.removeTab(last_tab)
self.tabWidget.setUpdatesEnabled(True)
def tab_doubleclicked(self, ind):
if not self.edit_session:
return
self.tabWidget.tabBar().editTab(ind)
def tab_clicked(self, ind):
if self.edit_session:
if ind == self.tabWidget.tabBar().count() - 1:
self.add_tab()
def eventFilter(self, watched, ev):
# turn off dragging while not in edit session
if isinstance(watched, CustomSection) and not self.edit_session:
if ev.type() == QEvent.MouseMove:
return True
return super().eventFilter(watched, ev)
def keyPressEvent(self, e):
if self.edit_session:
if e.key() == Qt.Key_Delete:
self.deletePressSignal.emit()
def generate_ribbon_config(self):
""" return ribbon setup to save in user config
(for detail structure look in config file)
return: list
"""
riblist = []
active_ind = self.tabWidget.currentIndex()
for ind in range(self.tabWidget.count()):
self.tabWidget.setCurrentIndex(ind)
wid = self.tabWidget.widget(ind)
if not isinstance(wid, CustomTab):
continue
tdict = wid.return_tab_config()
# if tab name not edited by user, save eng version
tab_name = self.tabWidget.tabText(ind)
trans_tab_names = [tr(key) for key in DEFAULT_TABS]
if tab_name in trans_tab_names:
tab_name = DEFAULT_TABS[trans_tab_names.index(tab_name)]
tdict['tab_name'] = tab_name
riblist.append(tdict)
self.tabWidget.setCurrentIndex(active_ind)
return riblist
class CustomTabBar(QTabBar):
def __init__(self, label='New tab', parent=None):
super().__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self._editor = QLineEdit(self)
self._editor.setWindowFlags(Qt.Popup)
self._editor.editingFinished.connect(self.handleEditingFinished)
self._editor.installEventFilter(self)
def eventFilter(self, widget, event):
if ((event.type() == QEvent.MouseButtonPress and
not self._editor.geometry().contains(event.globalPos())) or
(event.type() == QEvent.KeyPress and
event.key() == Qt.Key_Escape)):
self.handleEditingFinished()
self._editor.hide()
return super().eventFilter(widget, event)
def editTab(self, index):
rect = self.parent().tabBar().tabRect(index)
self._editor.setFixedSize(rect.size())
self._editor.move(self.parent().mapToGlobal(rect.topLeft()))
self._editor.setText(self.parent().tabText(index))
if not self._editor.isVisible():
self._editor.show()
def handleEditingFinished(self):
index = self.parent().currentIndex()
if index >= 0:
self._editor.hide()
self.parent().setTabText(index, self._editor.text())
class CustomTab(QWidget):
def __init__(self, lab, parent=None):
super(CustomTab, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.lab = lab
self.lay = QHBoxLayout()
self.lay.setSpacing(0)
self.lay.setMargin(6)
self.setLayout(self.lay)
self.setObjectName('ribTab')
self.lay.addStretch()
self.lay.setDirection(QBoxLayout.LeftToRight)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
e.accept()
def dragMoveEvent(self, e):
e.accept()
def dropEvent(self, e):
# accept only Custom Sections
if not isinstance(e.source(), CustomSection):
if isinstance(e.source(), CustomToolButton):
e.source().drag_state = False
e.setAccepted(False)
return
try:
lay = e.source().parent().lay
except AttributeError:
return
source = None
for i in range(lay.count()):
if not isinstance(lay.itemAt(i).widget(), CustomSection):
continue
it = lay.itemAt(i)
if it.widget() is e.source():
source = i
break
if source is None:
return
lay.takeAt(lay.count()-1)
addsec = lay.takeAt(lay.count()-1)
item = lay.takeAt(i)
lay.addItem(item)
lay.addItem(addsec)
lay.addStretch()
e.setAccepted(True)
def return_tab_config(self):
"""Returns config for current tab with all sections,
(description in config file)
:return: dict
"""
sec_conf = []
for ind in range(self.lay.count()):
it = self.lay.itemAt(ind)
if it is None:
continue
wid = it.widget()
if not isinstance(wid, CustomSection):
continue
sec_conf.append(wid.return_section_config())
return {
'tab_name': self.lab,
'sections': sec_conf,
}
class CustomSection(QWidget):
def __init__(self, name='New Section', parent=None):
super(CustomSection, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.edit = True
self.setAcceptDrops(True)
self.setMaximumSize(QSize(99999, 110))
self.setMinimumSize(QSize(70, 110))
if parent is not None:
parent.parent().editChanged.connect(self.edit_toggle)
parent.parent().deletePressSignal.connect(self.key_pressed)
self.setObjectName('ribSection')
# target of drop
self.target = None
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setContentsMargins(7, 0, 7, 0)
self.button_size = 30
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.horizontalLayout_2.setSpacing(0)
self.clabel = CustomLabel(tr(name), self)
self.clabel.setObjectName("ribSectionLabel")
self.clabel.setMaximumSize(QSize(100000, 20))
self.clabel.setMinimumSize(QSize(50, 20))
self.clabel.setAlignment(Qt.AlignCenter)
charakter = len(self.clabel.text())
self.clabel.setMinimumSize(QSize(charakter * 8, 20))
self.pushButton_close_sec = QToolButton(self)
self.pushButton_close_sec.setObjectName("ribSectionClose")
self.pushButton_close_sec.setText('x')
self.pushButton_close_sec.setStyleSheet(
'border-radius: 3px; font: 7pt;'
)
self.pushButton_close_sec.show()
self.pushButton_close_sec.setMaximumSize(QSize(18, 18))
self.horizontalLayout_2.addWidget(self.clabel)
self.horizontalLayout_2.addWidget(self.pushButton_close_sec)
self.sep = QFrame()
self.sep.setFrameShape(QFrame.VLine)
self.sep.setFrameShadow(QFrame.Raised)
self.sep.setObjectName('ribLine')
self.sep.setMinimumSize(QSize(6, 100))
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.gridLayout = QGridLayout()
self.gridLayout.setSpacing(10)
self.gridLayout.setContentsMargins(0,6,0,8)
self.gridLayout.setObjectName(u"gridLayout")
self.verticalLayout.addLayout(self.gridLayout)
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.horizontalLayout.addLayout(self.verticalLayout)
self.horizontalLayout.addWidget(self.sep)
self.horizontalLayout.setContentsMargins(4, 0, 4, 2)
self.setLayout(self.horizontalLayout)
self.pushButton_close_sec.clicked.connect(self.unload)
def unload(self):
self.hide()
self.deleteLater()
QApplication.processEvents()
def return_section_config(self):
"""return config for current section
:return: {}
"""
blist = []
for row in range(self.gridLayout.rowCount()):
for col in range(self.gridLayout.columnCount()):
it = self.gridLayout.itemAtPosition(row, col)
if it is None:
continue
itw = it.widget()
ind = self.gridLayout.indexOf(itw)
wid = self.gridLayout.itemAt(ind).widget()
if wid.objectName()[:4].lower() == 'rib' or not wid.actions():
act = wid.objectName()
else:
act = wid.actions()[0].objectName()
blist.append([act, row, col])
lab = self.clabel.text()
untra_lab = [ll['id'] for ll in STANDARD_TOOLS
if tr(ll['label']) == lab]
if untra_lab:
lab = untra_lab[0]
return {
'label': lab, 'btn_size': self.button_size, 'btns': blist,
}
def edit_toggle(self, state):
if state:
self.show_edit_options()
else:
self.hide_edit_options()
def key_pressed(self):
"""user pressed delete, and we are in edit session"""
if not self.edit:
return
# remove selected buttons
for col in range(self.gridLayout.columnCount()):
for row in [0, 1]:
it = self.gridLayout.itemAtPosition(row, col)
if it is None:
continue
if not it.widget().selected:
continue
ind = self.gridLayout.indexOf(it.widget())
wid = self.gridLayout.takeAt(ind)
wid.widget().turn_off_edit()
wid.widget().deleteLater()
self.clean_grid_layout()
def clean_grid_layout(self):
""" move all icons to left, after some where deleted"""
items = [[], []] # both rows
for col in range(self.gridLayout.columnCount()):
for row in [0, 1]:
itl = self.gridLayout.itemAtPosition(row, col)
if itl is None:
continue
it = itl.widget()
ind = self.gridLayout.indexOf(it)
it = self.gridLayout.takeAt(ind)
if it is not None:
items[row].append(it)
for irow, row in enumerate(items):
for icol, it in enumerate(row):
if isinstance(it, QWidgetItem):
self.gridLayout.addItem(it, irow, icol, 1, 1)
else:
self.gridLayout.addWidget(it, irow, icol, 1, 1)
self.gridLayout.update()
# self.gridLayoutWidget.adjustSize()
def add_action(self, action, row, col):
self.tbut = CustomToolButton(self)
if isinstance(action, QAction):
name_tool = action.objectName()
name_tool = name_tool.replace(':', '_')
self.tbut.setObjectName(name_tool)
self.tbut.org_state = action.isEnabled()
self.set_new_rib_icons(self.tbut, name_tool, action)
self.tbut.setObjectName('gp_' + action.objectName())
self.tbut.setDefaultAction(action)
elif QgsApplication.processingRegistry().algorithmById(action):
alg = QgsApplication.processingRegistry().algorithmById(action)
self.tbut.setObjectName(alg.id())
newAct = QAction(alg.icon(), alg.displayName(), self)
def open_window():
execAlgorithmDialog(newAct.objectName())
newAct.setObjectName(alg.id())
newAct.triggered.connect(open_window)
self.tbut.setDefaultAction(newAct)
self.tbut.org_state = True
self.tbut.setText(alg.id())
action = action.replace(':', '_')
lista = [x.split('.')[0] for x in os.listdir(os.path.join(os.path.dirname(__file__), 'icons'))]
if action in lista:
self.tbut.setIcon(QIcon(os.path.join(os.path.dirname(__file__), 'icons', action)))
elif isinstance(action, str):
self.tbut.setObjectName(action)
self.set_custom_action()
self.tbut.setMaximumSize(QSize(self.button_size, self.button_size))
self.tbut.setMinimumSize(QSize(self.button_size, self.button_size))
if self.button_size == 30:
self.tbut.setIconSize(
QSize(self.button_size-4, self.button_size-4)
)
else:
self.tbut.setIconSize(
QSize(self.button_size-5, self.button_size-5)
)
self.tbut.setEnabled(True)
self.tbut.installEventFilter(self)
self.gridLayout.addWidget(self.tbut, row, col, 1, 1)
return self.tbut
def set_new_rib_icons(self, button, name_tool, action):
dirnm = os.path.dirname(__file__)
list_tool = [
'mProcessingUserMenu_native_buffer','mProcessingUserMenu_native_centroids',
'mProcessingUserMenu_native_clip','mProcessingUserMenu_native_collect',
'mProcessingUserMenu_native_convexhull','mProcessingUserMenu_native_countpointsinpolygon',
'mProcessingUserMenu_native_creategrid','mProcessingUserMenu_native_difference',
'mProcessingUserMenu_native_extractvertices','mProcessingUserMenu_native_intersection',
'mProcessingUserMenu_native_lineintersections','mProcessingUserMenu_native_meancoordinates',
'mProcessingUserMenu_native_multiparttosingleparts','mProcessingUserMenu_native_nearestneighbouranalysis',
'mProcessingUserMenu_native_polygonfromlayerextent','mProcessingUserMenu_native_polygonstolines',
'mProcessingUserMenu_native_randompointsinextent','mProcessingUserMenu_native_simplifygeometries',
'mProcessingUserMenu_native_sumlinelengths','mProcessingUserMenu_native_symmetricaldifference',
'mProcessingUserMenu_native_union','mProcessingUserMenu_qgis_basicstatisticsforfields',
'mProcessingUserMenu_qgis_checkvalidity','mProcessingUserMenu_qgis_delaunaytriangulation',
'mProcessingUserMenu_qgis_distancematrix','mProcessingUserMenu_qgis_eliminateselectedpolygons',
'mProcessingUserMenu_qgis_exportaddgeometrycolumns', 'mProcessingUserMenu_qgis_linestopolygons',
'mProcessingUserMenu_qgis_listuniquevalues', 'mProcessingUserMenu_qgis_randompointsinsidepolygons',
'mProcessingUserMenu_qgis_regularpoints', 'mProcessingUserMenu_qgis_voronoipolygons',
'mProcessingUserMenu_native_dissolve', 'mProcessingUserMenu_qgis_randompointsinlayerbounds',
'mProcessingUserMenu_native_densifygeometries','mProcessingUserMenu_gdal_aspect',
'mProcessingUserMenu_gdal_fillnodata', 'mProcessingUserMenu_gdal_gridaverage',
'mProcessingUserMenu_gdal_griddatametrics', 'mProcessingUserMenu_gdal_gridinversedistance',
'mProcessingUserMenu_gdal_gridnearestneighbor', 'mProcessingUserMenu_gdal_hillshade',
'mProcessingUserMenu_gdal_roughness', 'mProcessingUserMenu_gdal_slope',
'mProcessingUserMenu_gdal_tpitopographicpositionindex', 'mProcessingUserMenu_gdal_triterrainruggednessindex',
'mProcessingUserMenu_native_createspatialindex', 'mProcessingUserMenu_native_joinattributesbylocation',
'mProcessingUserMenu_native_reprojectlayer',
'mActionZoomTo', 'mActionZoomOut', 'mActionZoomToSelected', 'mActionZoomToLayer', 'mActionZoomToBookmark',
'mActionZoomToArea', 'mActionZoomNext', 'mActionZoomLast', 'mActionZoomIn', 'mActionZoomFullExtent',
'mActionZoomActual', 'mActionWhatsThis', 'mActionViewScaleInCanvas', 'mActionViewExtentInCanvas',
'mActionVertexToolActiveLayer', 'mActionVertexTool', 'mActionUnlockAll', 'mActionUnlink',
'mActionUngroupItems', 'mActionUndo', 'mActionTrimExtendFeature', 'mActionTracing', 'mActionTouch',
'mActionToggleSelectedLayers', 'mActionToggleEditing', 'mActionToggleAllLayers', 'mActionTiltUp',
'mActionTiltDown', 'mActionTextAnnotation', 'mActionTerminal', 'mActionSvgAnnotation', 'mActionSum',
'mActionStyleManager', 'mActionStreamingDigitize', 'mActionStop', 'mActionStart', 'mActionSimplify',
'mActionShowUnplacedLabel', 'mActionShowSelectedLayers', 'mActionShowPluginManager',
'mActionShowPinnedLabels', 'mActionShowMeshCalculator', 'mActionShowHideLabels', 'mActionShowBookmarks',
'mActionShowAllLayersGray', 'mActionSharingImport', 'mActionSharingExport', 'mActionSharing',
'mActionSetToCanvasScale', 'mActionSplitParts', 'mActionSetToCanvasEtent', 'mActionSetProjection',
'mActionSelectRectangle', 'mActionSelectRadius', 'mActionSelectPolygon', 'mActionSelectPan',
'mActionShowAllLayers', 'mACtionSelectFreehand', 'mActionSelectedToTop', 'mActionSelectAllTree',
'mActionSelectAll', 'mActionSelect', 'mActionScriptOpen', 'mActionScaleHighlightFeature',
'mActionScaleFeature', 'mActionScaleBar', 'mActionSaveMapAsImage', 'mActionSaveEdits', 'mActionSaveAsSVG',
'mActionSaveAsPython', 'mActionSaveAsPDF', 'mActionSplitFeatures', 'mActionSaveAllEdits',
'mActionRotatePointSymbols', 'mActionRotateFeature', 'mActionRollbackEdits', 'mActionRollbackAllEdits',
'mActionReverseLine', 'mActionResizeWidest', 'mActionResizeTallest', 'mActionResizeSquare',
'mActionResizeShortest', 'mActionResizeNarrowest', 'mActionReshape', 'mActionRemoveSelectedFeature',
'mActionRemoveLayer', 'mActionRemoveAllFromOverview', 'mActionRemove', 'mActionReload',
'mActionRegularPolygonCenterPoint', 'mActionRegularPolygonCenterCorner', 'mActionRegularPolygon2Points',
'mActionRefresh', 'mActionRedo', 'mActionRectangleExtent', 'mActionRectangleCenter',
'mActionRectangle3PointsProjected', 'mActionRectangle3PointsDistance', 'mActionRecord',
'mActionRaiseItems', 'mActionPropertyItem', 'mActionPropertiesWidget', 'mActionProjectProperties',
'mActionProcessSelected', 'mActionPrevious', 'mActionPlay', 'mActionPinLabels', 'mActionRotateLabel',
'mActionPanToSelected', 'mActionPanTo', 'mActionPanHighlightFeature', 'mActionOptions',
'mActionOpenTableVisible', 'mActionOpenTableSelected', 'mActionOpenTableEdited', 'mActionOpenTable',
'mActionOffsetPointSymbols', 'mActionOffsetCurve', 'mActionNext', 'mActionNewVirtualLayer',
'mActionNewVectorLayer', 'mActionNewTableRow', 'mActionNewSpatiaLiteLayer', 'mActionNewReport',
'mActionNewPage', 'mActionNewMeshLayer', 'mActionNewMap', 'mActionNewLayout', 'mActionNewGeoPackageLayer',
'mActionNewFolder', 'mActionNewComposer', 'mActionNewBookmark', 'mActionNewAttribute',
'mActionNew3DMap', 'mActionMultiEdit', 'mActionMoveVertex', 'mActionMoveLabel', 'mActionMoveItemsToTop',
'mActionMoveItemsToBottom', 'mActionMoveItemContent', 'mActionMoveFeaturePoint',
'mActionMoveFeatureLine', 'mActionMoveFeatureCopyLine', 'mActionMoveFeatureCopyPoint',
'mActionMoveFeatureCopy', 'mActionMoveFeature', 'mActionMeshDigitizing', 'mActionMeshDigitizing',
'mActionMergeFeatures', 'mActionMergeFeaturesAttributes', 'mActionMeasureBearing',
'mActionMeasureArea', 'mActionMeasureAngle', 'mActionMapTips', 'mActionMapSettings',
'mActionMapIdentification', 'mActionLowerItems', 'mActionFeature', 'mActionLockItems',
'mActionLockExtent', 'mActionLocalHistogramStretch', 'mActionLocalCumulativeCutStretch',
'mActionLink', 'mActionLayoutManager', 'mActionLast', 'mActionLabeling', 'mActionLabelAnchorStart',
'mActionLabelAnchorEnd', 'mActionLabelAnchorCustom', 'mActionLabelAnchorCenter', 'mActionLabel',
'mActionKeyboardShortcuts', 'mActionInvertSelection', 'mActionInterfaceCustomization',
'mActionInOverview', 'mActionIncreaseGamma', 'mActionIncreaseFont', 'mActionIncreaseContrast',
'mActionIncreaseBrightness', 'mActionIdentifyByRectangle', 'mActionIdentifyByRadius',
'mActionIdentifyByPolygon',
'mActionIdentifyByFreehand', 'mActionIdentify', 'mActionIconView', 'mActionHtmlAnnotation',
'mActionHistory', 'mActionHighlightFeature', 'mActionHideSelectedLayers',
'mActionHideDeselectedLayers', 'mActionHideAllLayers', 'mActionHelpContents',
'mActionHelpAbout', 'mActionHandleStoreFilterExpressionUnchecked',
'mActionHandleStoreFilterExpressionChecked',
'mActionGroupItems', 'mActionFullHistogramStretch', 'mActionFullCumulativeCutStretch',
'mActionFromSelectedFeature', 'mActionFromLargestFeature', 'mActionFormView', 'mActionFormAnnotation',
'mActionFolder', 'mActionFirst', 'mActionFindReplace', 'mActionFilterTableFields', 'mActionFilter2',
'mActionFilter', 'mActionFillRing', 'mActionFileSaveAs', 'mActionFileSave', 'mActionFilePrint',
'mActionFileNew', 'mActionFileExit', 'mActionExport', 'mActionExpandTree', 'mActionExpandNewTree',
'mActionEllipseExtent', 'mActionEllipseCenterPoint', 'mActionEllipseCenter2Points',
'mActionEditTable', 'mActionEditPaste', 'mActionEditNodesItem', 'mActionEditModelComponent',
'mActionEditHtml', 'mActionEditHelpContent', 'mActionEditCut', 'mActionEditCopy', 'mActionDuplicateLayout',
'mActionDuplicateLayer', 'mActionDuplicateFeatureDigitized', 'mActionDuplicateFeature',
'mActionDuplicateComposer', 'mActionDoubleArrowRight', 'mActionDoubleArrowLeft', 'mActionDistributeVSpace',
'mActionDistributeVCenter', 'mActionDistributeTop', 'mActionDistributeRight', 'mActionDistributeLeft',
'mActionDistributeHSpace', 'mActionDistributeHCenter', 'mActionDistributeBottom',
'mActionDigitizeWithCurve',
'mActionDeselectAllTree', 'mActionDeselectAll', 'mActionDeselectActiveLayer', 'mActionDeleteTable',
'mActionDeleteSelectedFeatures', 'mActionDeleteSelected', 'mActionDeleteRing', 'mActionDeletePart',
'mActionDeleteModelComponent', 'mActionDeleteAttribute', 'mActionDecreaseGamma', 'mActionDecreaseFont',
'mActionDecreaseContrast', 'mActionDecreaseBrightness', 'mActionDataSourceManager',
'mActionCustomProjection',
'mActionCreateTable', 'mActionCreateMemory', 'mActionConditionalFormatting', 'mActionComposerManager',
'mActionCollapseTree', 'mActionCircularStringRadius', 'mActionCircularStringCurvePoint',
'mActionCircleExtent', 'mActionCircleCenterPoint', 'mActionCircle3Tangents', 'mActionCircle3Points',
'mActionCircle2TangentsPoint', 'mActionCircle2Points', 'mActionChangeLabelProperties',
'mActionCapturePoint', 'mActionCaptureLine', 'mActionCancelEdits', 'mActionCancelAllEdits',
'mActionCalculateField', 'mActionAvoidIntersetionsLayers', 'mActionAvoidIntersectionsCurrentLayer',
'mActionAtlasSettings', 'mActionAtlasPrev', 'mActionAtlasNext', 'mActionAtlasLast', 'mActionAtlasFirst',
'mActionArrowUp', 'mActionArrowRight', 'mActionArrowLeft', 'mActionArrowDown', 'mActionAnnotation',
'mActionAllowIntersections', 'mActionAllEdits', 'mActionAlignVCenter', 'mActionAlignTop',
'mActionAlignRight', 'mActionAlignLeft', 'mActionAlignHCenter', 'mActionAlignBottom',
'mActionAddTable', 'mActionAddPolyline', 'mActionAddPolygon', 'mActionAddPointCloudLayer',
'mActionAddNodesItem', 'mActionAddMssqlLayer', 'mActionAddMeshLayer', 'mActionAddMarker',
'mActionAddMap', 'mActionAddManualTable', 'mActionAddLegend', 'mActionAddLayer', 'mActionAddImage',
'mActionAddHtml', 'mActionAddHanaLayer', 'mActionAddGroup', 'mActionAddPackageLayer',
'mActionAddGeomodeLayer',
'mActionAddExpression', 'mActionAddDelimitedTextLayer', 'mActionAddDb2Layer', 'mActionAddBasicTriangle',
'mActionAddBasicShape', 'mActionAddBasicRectangle', 'mActionAddBasicCircle', 'mActionAddArrow',
'mActionAddAmsLayer', 'mActionAddAllToOverview', 'mActionAddAfsLayer', 'mActionAdd3DMap',
'mActionAdd', 'mActionActive', 'mAction3DNavigation', 'mAction', 'mActionMeasure', 'mActionPan',
'mActionFileOpen', 'mActionAddWmsLayer', 'mActionAddWfsLayer', 'mActionAddWcsLayer',
'mActionAddVirtualLayer',
'mActionAddSpatiaLiteLayer', 'mActionAddRing', 'mActionAddRasterLayer', 'mActionAddPostgisLayer',
'mActionAddPart', 'mActionAddOgrLayer', 'mAlgorithmBasicStatistics','mActionStatisticalSummary',
'mProcessingUserMenu_native_selectbylocation', 'mProcessingUserMenu_qgis_randomselection',
'native_fuzzifyrasterlinearmembership', 'native_fuzzifyrastergaussianmembership',
'native_fuzzifyrasterlargemembership',
'native_fuzzifyrasternearmembership', 'native_fuzzifyrasterpowermembership',
'native_fuzzifyrastersmallmembership', 'native_cellstatistics', 'qgis_concavehull',
'native_createconstantrasterlayer', 'native_fillnodata', 'native_linedensity',
'native_serviceareafromlayer',
'native_serviceareafrompoint',
'native_shortestpathlayertopoint',
'native_shortestpathpointtolayer',
'native_shortestpathpointtopoint',
'native_createrandomnormalrasterlayer',
'native_createrandomexponentialrasterlayer',
'native_createrandompoissonrasterlayer',
'native_createrandomuniformrasterlayer',
'native_createrandomgammarasterlayer',
'native_roundrastervalues',
'qgis_heatmapkerneldensityestimation',
'mActionToggleAdvancedDigitizeToolBar',
'dbManager',
'mActionEllipseFoci', 'mActionOpenProject', 'mActionNewProject', 'mActionSaveProject',
'mActionSaveProjectAs', 'mActionCapturePolygon','mActionSelectFeatures','mActionAddPgLayer',
'mActionAddDelimitedText','mActionNewMemoryLayer'
]
if name_tool in list_tool:
action.setIcon(QIcon(os.path.join(dirnm, 'icons', button.objectName())))
if name_tool =='mActionNewMemoryLayer':
action.setIcon(QIcon(os.path.join(dirnm, 'icons', 'mActionNewMemoryLayer')))
if name_tool =='mActionSaveProjectAs':
action.setIcon(QIcon(os.path.join(dirnm, 'icons', 'mActionSaveProjectAs')))
def set_custom_action(self):
oname = self.tbut.objectName()
dirnm = os.path.dirname(__file__)
if oname == 'ribWMS':
self.orto_add = OrtoAddingTool(self, self.tbut)
connect_orto = self.orto_add.connect_ortofotomapa_group
self.tbut.setIcon(
QIcon(os.path.join(dirnm, 'icons', 'orto_icon2.png'))
)
for service in self.orto_add.services:
service.orto_group_added.connect(connect_orto)
if oname == 'ribCompositions':
# this on will be find by compositions after loading
# documentation purposes
self.tbut.setIcon(
QIcon(os.path.join(dirnm, 'icons', 'compositions_rib.png'))
)
self.tbut.setToolTip(tr("Composition settings"))
def unload_custom_actions(self):
if self.orto_add:
self.orto_add.disconnect_ortofotomapa_group()
def change_label(self, lab):
"""Changes label
:lab: str
"""
if isinstance(lab, str) and lab not in ['', 'None', 'False']:
self.label.setText(lab)
def set_size(self, sz):
"""change size of button
:sz: int
"""
self.button_size = sz
def _get_items(self):
"""return list with item stored in gridlayout
:return: [[tool, tool], [tool, tool]]
"""
items = [[], []] # both rows
for col in range(self.gridLayout.columnCount()):
for row in [0, 1]:
it = self.gridLayout.itemAtPosition(row, col)
if it is not None:
items[row].append(it.widget())
return items
def get_toolbutton_layout_index_from_pos(self, pos):
for i in range(self.gridLayout.count()):
rect = self.gridLayout.itemAt(i).widget()
# recalculate rect to compatible coord system
rect_ok = QRect(0, 0, rect.width(), rect.height())
if rect_ok.contains(rect.mapFromGlobal(pos)) and \
i != self.target:
return i
def eventFilter(self, watched, event):
if event.type() == QEvent.MouseButtonPress:
self.mousePressEvent(event)
elif event.type() == QEvent.MouseMove and \
isinstance(watched, CustomSection):
self.mouseMoveEvent(event)
elif event.type() == QEvent.MouseButtonRelease:
self.mouseReleaseEvent(event)
# prevent default action from qtoolbutton
if isinstance(watched, CustomToolButton) and self.edit:
if event.type() == QEvent.MouseButtonPress:
watched.setDown(False)
if event.type() == QEvent.HoverEnter:
# if tooltip should show wtihout delay code place here
pass
return super().eventFilter(watched, event)
def mouseReleaseEvent(self, event):
event.accept()
def mouseMoveEvent(self, e):
print('mouse event')
if not self.edit:
return
drag = QDrag(self)
drag.setDragCursor(QPixmap("images/drag.png"), Qt.MoveAction)
mimedata = QMimeData()
pixmap = QPixmap(self.size()) # Get the size of the object
painter = QPainter(pixmap) # Set the painter’s pixmap
painter.drawPixmap(self.rect(), self.grab())
painter.end()
drag.setMimeData(mimedata)
drag.setHotSpot(e.pos())
drag.setPixmap(pixmap)
drag.exec_(Qt.MoveAction)
e.accept()
def dragEnterEvent(self, event):
event.accept()
def dropEvent(self, event): # noqa
gpos = QCursor().pos()
if isinstance(event.source(), CustomToolButton):
# check if source and target are in the same gridlayout
if event.source().parent() is not self:
event.source().drag_state = False
return
# swap toolbuttons
# get origin button
source = self.get_toolbutton_layout_index_from_pos(gpos)
glay = event.source().parent().gridLayout
self.target = None
for i in range(glay.count()):
it = glay.itemAt(i)
if it.widget() is event.source():
self.target = i
break
if source == self.target:
try:
it.widget().drag_state = False
except Exception:
pass
return
if None not in [source, self.target]:
# swap qtoolbuttons
i, j = max(self.target, source), min(self.target, source)
p1 = self.gridLayout.getItemPosition(i)
p2 = self.gridLayout.getItemPosition(j)
it1 = self.gridLayout.takeAt(i)
it2 = self.gridLayout.takeAt(j)
it1.widget().setDown(False)
it2.widget().setDown(False)
it1.widget().drag_state = False
it2.widget().drag_state = False
self.gridLayout.addItem(it1, *p2)
self.gridLayout.addItem(it2, *p1)
if isinstance(event.source(), CustomSection):
lay = self.parent().lay
target = None
source = None
for i in range(lay.count()):
if not isinstance(lay.itemAt(i).widget(), CustomSection):
continue
it = lay.itemAt(i)
if it.widget() is event.source():
source = i
if it.widget().geometry().contains(
it.widget().parent().mapFromGlobal(gpos)):
target = i
if source == target or None in [source, target]:
return
item = lay.takeAt(source)