-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariable_panel_dockwidget.py
More file actions
215 lines (180 loc) · 8.92 KB
/
variable_panel_dockwidget.py
File metadata and controls
215 lines (180 loc) · 8.92 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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
VariablePanel
A QGIS plugin
The VariablePanel plugin displays project variables in a dedicated QGIS panel, allowing for easy access
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2024-11-16
git sha : $Format:%H$
copyright : (C) 2024 by Alexandre Parente Lima
email : alexandre.parente@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. *
* *
***************************************************************************/
"""
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtWidgets import QVBoxLayout, QWidget, QLabel, QTreeView
from qgis.gui import QgsDockWidget, QgsVariableEditorWidget
from qgis.core import QgsExpressionContextUtils, QgsExpressionContext, QgsProject
from qgis.utils import iface
from qgis.PyQt.QtCore import QCoreApplication, Qt
def tr(string):
"""Translation function."""
return QCoreApplication.translate('VariablePanel', string)
class VariablePanelDockWidget(QgsDockWidget):
"""The main dock widget for the Variable Panel plugin."""
def __init__(self, parent=None):
"""Constructor."""
super(VariablePanelDockWidget, self).__init__(parent)
# Basic Widget Setup
self.setWindowTitle(self.tr("Variables"))
self.setObjectName("VariablePanelDockWidget")
# State Variables
# Get a reference to the current QGIS project.
self.project = QgsProject.instance()
# Store the ID of the currently active layer to handle saving.
self.active_layer_id = None
# Store the name ('project' or 'layer') of the last scope the user clicked on.
self.last_selected_scope_name = 'project'
# Track the current editable scope index to avoid calling non-existent API getters.
self.current_editable_index = 0
# UI Layout
main_layout = QVBoxLayout()
container = QWidget()
container.setLayout(main_layout)
self.setWidget(container)
# A single, unified editor widget displays all variables.
self.variable_editor = QgsVariableEditorWidget(self)
main_layout.addWidget(self.variable_editor)
# Standard dialog buttons (OK, Cancel, Apply).
self.button_box = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok |
QtWidgets.QDialogButtonBox.Cancel |
QtWidgets.QDialogButtonBox.Apply
)
main_layout.addWidget(self.button_box)
# Signal Connections
self.button_box.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.applyChangesAndClose)
self.button_box.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.close)
self.button_box.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(self.applyChanges)
# Connect to the signal that fires when the active layer changes in the QGIS Layers Panel.
iface.layerTreeView().currentLayerChanged.connect(self.handleActiveLayerChange)
# Initialize the UI with the current context.
self.handleActiveLayerChange(iface.activeLayer())
def onVariableItemSelected(self, current_index, previous_index):
"""
Called whenever a tree item is selected. It determines which scope was clicked
and sets it as the target for new variables.
"""
if not current_index.isValid():
return
# Find the top-level item for the clicked index by traversing up the tree.
top_level_index = current_index
while top_level_index.parent().isValid():
top_level_index = top_level_index.parent()
# Get the row number of the top-level item.
top_level_row = top_level_index.row()
# Map the row number to the correct scope name based on the current context.
scope_name = None
if self.active_layer_id:
# Context order is [project, layer].
if top_level_row == 0:
scope_name = 'project'
elif top_level_row == 1:
scope_name = 'layer'
else:
# Context order is just [project].
if top_level_row == 0:
scope_name = 'project'
# Store the last valid scope selected by the user.
if scope_name:
self.last_selected_scope_name = scope_name
# Update the target for the '+' (add variable) button.
self.updateEditableScope()
def updateEditableScope(self):
"""
Sets which scope (project or layer) will receive new variables.
This method translates the stored scope name ('project'/'layer') into the correct index.
"""
target_scope = self.last_selected_scope_name
index_to_set = 0
if self.active_layer_id:
# Context order is [project, layer].
if target_scope == 'project':
index_to_set = 0
elif target_scope == 'layer':
index_to_set = 1
else:
# Context order is just [project].
if target_scope == 'project':
index_to_set = 0
# Tell the widget which scope is the target for additions and update our state variable.
self.variable_editor.setEditableScopeIndex(index_to_set)
self.current_editable_index = index_to_set
def handleActiveLayerChange(self, layer):
"""
Rebuilds the editor's context based on the newly selected active layer.
This is the main function for updating the panel's view.
"""
context = QgsExpressionContext()
self.active_layer_id = None
if layer:
self.active_layer_id = layer.id()
context.appendScope(QgsExpressionContextUtils.projectScope(self.project))
context.appendScope(QgsExpressionContextUtils.layerScope(layer))
self.last_selected_scope_name = 'project'
else:
# If no layer is selected, only show the project scope.
context.appendScope(QgsExpressionContextUtils.projectScope(self.project))
self.last_selected_scope_name = 'project'
self.variable_editor.setContext(context)
# Set the default editable scope based on the new context.
self.updateEditableScope()
# Find the internal tree view to connect its selection signal.
tree_view = self.variable_editor.findChild(QTreeView)
if tree_view:
# prevents connecting the same signal multiple times.
try:
tree_view.selectionModel().currentChanged.disconnect(self.onVariableItemSelected)
except (TypeError, RuntimeError):
pass
# Reconnect the signal.
tree_view.selectionModel().currentChanged.connect(self.onVariableItemSelected)
def applyChanges(self):
"""
Saves the changes for all scopes present in the context.
"""
context = self.variable_editor.context()
if not context:
return
# Store the user's last selected scope index
original_editable_index = self.current_editable_index
# Iterate through all scopes to save.
for i, scope in enumerate(context.scopes()):
self.variable_editor.setEditableScopeIndex(i)
variables_dict = self.variable_editor.variablesInActiveScope()
# Identify the scope by its index.
is_project_scope = (self.active_layer_id and i == 0) or (not self.active_layer_id and i == 0)
is_layer_scope = self.active_layer_id and i == 1
if is_project_scope:
QgsExpressionContextUtils.setProjectVariables(self.project, variables_dict)
elif is_layer_scope:
layer = self.project.mapLayer(self.active_layer_id)
if layer:
QgsExpressionContextUtils.setLayerVariables(layer, variables_dict)
# Restore the editable scope to the user's last selection.
self.variable_editor.setEditableScopeIndex(original_editable_index)
# Reload the context to ensure the view is synchronized with the saved data.
self.variable_editor.reloadContext()
def applyChangesAndClose(self):
"""Apply changes and close the DockWidget."""
self.applyChanges()
self.close()