3

Macros are saved in the .qgs project file. However, looking at the QgsProject Class, there is no mention of a method to read or write a macro.

Other than dangerously editing the .qgs project file, is there some other method of accessing a macro?

1 Answer 1

4

Apparently it is possible by using the QgsProject.instance().readEntry() method as shown in the following link:

https://github.com/qgis/QGIS/blob/master/python/utils.py#L487


  • To read the project macro, you can use:

    print QgsProject.instance().readEntry("Macros", "/pythonCode")[0]
    
  • To write a project macro, you can use:

    macro = u'def openProject():\r\n\t#do something\r\n\r\ndef saveProject():\r\n\t#do something else\r\n\r\ndef closeProject():\r\n\tpass\r\n'
    QgsProject.instance().writeEntry("Macros", "/pythonCode", macro)
    

    Written macro

    Where:

    • \r is the carriage return.
    • \n is the new line.
    • \t is the horizontal tab.

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.