77from dataclasses import dataclass
88from typing import Callable , Optional
99
10+ import processing
11+ from qgis .core import QgsProject
12+ from qgis .utils import iface
13+
1014from qchat .gui .effects import dizzy , flick_of_the_wrist
1115
1216
@@ -59,6 +63,7 @@ class SlashCommandHandler:
5963 "8ball" : "Ask the magic 8-ball" ,
6064 "dizz" : "Let QGIS shake" ,
6165 "flick" : "Look at QGIS flicking the wrist" ,
66+ "grid" : "Generate a grid layer on the current extent" ,
6267 }
6368
6469 def __init__ (self ):
@@ -74,6 +79,7 @@ def __init__(self):
7479 "8ball" : self .cmd_8ball ,
7580 "dizz" : self .cmd_dizz ,
7681 "flick" : self .cmd_flick ,
82+ "grid" : self .cmd_grid ,
7783 }
7884
7985 def get_command_list (self ) -> list [str ]:
@@ -254,6 +260,57 @@ def cmd_flick(self, args: str) -> SlashCommandResult:
254260 success = True , local_action = lambda : ("show_message_bar" , args )
255261 )
256262
263+ def cmd_grid (self , args : str ) -> SlashCommandResult :
264+ """Grid command, creates a square grid in QGIS, using the extent of the current map canvas.
265+
266+ :param args: size of the grid cells in map units (e.g., "1000" for 1000x1000 units)
267+ :return: SlashCommandResult
268+ """
269+
270+ if not args :
271+ return SlashCommandResult (
272+ success = False ,
273+ error = "No size provided. Use /grid [size]" ,
274+ )
275+
276+ try :
277+ tokens = args .lower ().split (" " )
278+
279+ if len (tokens ) > 1 :
280+ raise ValueError ("Too many arguments" )
281+
282+ size = int (tokens [0 ])
283+
284+ alg_params = {
285+ "TYPE" : 2 , # 0: point, 1: line, 2: rectangle, 3: diamond, 4: hexagon
286+ "EXTENT" : iface .mapCanvas ().extent (),
287+ "HSPACING" : size ,
288+ "VSPACING" : size ,
289+ "HOVERLAY" : 0 ,
290+ "VOVERLAY" : 0 ,
291+ "CRS" : QgsProject .instance ().crs (),
292+ "OUTPUT" : "memory:" ,
293+ }
294+
295+ result = processing .run ("qgis:creategrid" , alg_params )
296+ grid = result ["OUTPUT" ]
297+
298+ QgsProject .instance ().addMapLayer (grid )
299+
300+ return SlashCommandResult (
301+ success = True ,
302+ local_action = lambda : (
303+ "show_message_bar" ,
304+ "Generated a grid with {size} size." .format (size = size ),
305+ ),
306+ )
307+
308+ except (ValueError , IndexError ):
309+ return SlashCommandResult (
310+ success = False ,
311+ error = "Invalid format. Use /grid [size]" ,
312+ )
313+
257314 def cmd_list (self , args : str ) -> SlashCommandResult :
258315 """List all available commands.
259316
0 commit comments