Feature request #12200

Move layers within ToC using PyQGIS

Added by Joseph Liam almost 10 years ago. Updated over 8 years ago.

Status:Closed
Priority:Normal
Assignee:-
Category:-
Pull Request or Patch supplied:No Resolution:
Easy fix?:No Copied to github as #:20389

Description

Based on a post on GIS StackExchange (http://gis.stackexchange.com/questions/134284/how-to-move-layers-in-qgis), it seems the only method to move layers to another position in ToC (Table of Contents) via PyQGIS is to:

  1. Clone the layer
  2. Insert clone at the desired position
  3. Remove the original

This process is decribed in the following posts:

It also mentions that each layer in the ToC contains an index which defines the position within the ToC. Therefore, inserting a cloned layer into an index already owned by another layer will cause problems.

Possible solution:

When moving a layer into a desired index (i.e. 3), make all layers with an index >= 3 to have their index increase by 1. This would make the original layer that was at index 3 to have index 4; original layer with index 4 to have index 5 and so on...

History

#1 Updated by Martin Dobias almost 10 years ago

I think I fail to see the problem here...

There is nothing like indexes being owned by layer nodes. Indexes just mirror the order how nodes are stored in an array. It works exactly the same as when you work with a simple python list. Think of list lst=[10,11,12]. How do you move value 11 up or down in such list? To move it up: del lst1; lst.insert(0, 11). To move it down: del lst1; lst.insert(2, 11). It is exactly the same when moving nodes in a layer tree, you just need to clone the objects.

Maybe the confusion comes from the fact the blog post suggest to first insert new node before removing the old node - while it is a bit more practical to do it in reverse? (first delete old node, then insert new one) It is perfectly fine to reverse the operations, the advantage is that the index of the deleted node does not change.

#2 Updated by Alexander Bruy over 8 years ago

  • Status changed from Open to Closed

Closed, as there is no problem here. Please reopen if necessary

Also available in: Atom PDF