3

In QGIS 2.2 , I was able to sort in alphabetical order the layers simply using this:

self.maplegendtree = iface.mainWindow().findChild(QTreeWidget, "theMapLegend")
self.maplegendtree.sortItems(0, Qt.AscendingOrder)

I search a lot and I understand there where some changes with the legend in QGIS 2.4 ...

I tried this :

self.maplegendtree = self.iface.mainWindow().findChild( QTreeView, 'theLayerTreeView')
self.maplegendtree.setSortingEnabled(True);
self.maplegendtree.sortByColumn(0, Qt.AscendingOrder);

No error ... but no changes in the legend or mapcanvas?

1 Answer 1

1

Following that super blog post http://www.lutraconsulting.co.uk/blog/2014/07/06/qgis-layer-tree-api-part-1/ I will be able to sort manually my layers/groups using layerTreeRoot and moving nodes at the right position. Not as straight forward, but it should work.

Here a snippet for moving one node (a group in this case)

self.treeRoot = QgsProject.instance().layerTreeRoot() 
lnGroup = self.treeRoot.findGroup("GroupName")
lnGroupClone = lnGroup.clone()
self.treeRoot.insertChildNode(1, lnGroupClone) #insert at index 1
self.treeRoot.removeChildNode(lnGroup)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.