QGIS – Accessing Menu Functions Like Copy Paste Style Using Python and PyQGIS

pyqgispythonqgisstyle

Following question which was never answered:
https://stackoverflow.com/questions/27140520/how-to-access-qgis-menu-items-using-python

Is there any way to access functions in QGIS menu using python? Particularly in my case copy and paste style but best would be to get some general way / documentation where to find what function / tool is behind menu item and if / how is possible to get to it using python?

In my case because I frequently need to copy paste one or few layers from one project to other I made simple QGIS plugin for it. It can quickly copy layer path to clipboard (also raster/vector type and name from layers panel) and paste layer (using shortcut keys ctrl+shift+c / ctrl+shift+v). It works also between two QGIS windows which is exactly what I needed. Except one thing – it does not copy layer style from project. And because copy paste style is already as part of QGIS I would like to use that as step of copy paste layer without need to try to replicate the functionality in my own code.

Best Answer

I'll answer the concrete question of copying/pasting layer styles with PyQGIS:

  1. Select the source layer in the QGIS layer tree either by hand or by code.

  2. Run the following command to copy the style:

    iface.actionCopyLayerStyle().trigger()
    
  3. Select another layer either by hand or by code (as you mentioned, it could be a layer in another QGIS window).

  4. Run the following command to paste the style:

    iface.actionPasteLayerStyle().trigger()
    

In general, some QGIS functionality is exposed through iface object. Have a look at the different actions that you could call (trigger) at http://www.qgis.org/api/classQgisInterface.html


For your specific use case, since you seem to be managing the clipboard, I suggest you to do this:

  • Save the layer style into a temporary QML file (using layer.saveNamedStyle( pathToQMLFile )),
  • Copy the path to that file into the clipboard,
  • When pasting, load the style from the QML file path in the clipboard (using layer.loadNamedStyle( pathToQMLFile ) and then layer.triggerRepaint()).