'How to copy a layer attribute form from an xml style in a postgres database to a Qgis layer using python?

Frame : I'm working on a Qgis plugin, written in python that connects to a postgres database for some of its features. This plugin allows the user to select a layer style from said database. When the user do so, every property of the saved style is applied, including the layer configuration, symbology,tooltip and the layer form. I'm looking for a way to only get the form style from my database and apply it to another layer which has the same attributes. In my database the layer style is saved as an xml.

I've been looking for a way to do this using the QgsAttributeForm class, I've tried to use the QgsAttributeFormInterface but I don't think these classes were intended to be used this way. To get the whole style to be applied i'm using this code:

#List styles in our database
listedStyles = layer.listStylesInDatabase()
#First element of said list is the number of styles in DB
numberOfStyles = listedStyles[0]
#Finds the index of wanted style
styleIndex = listedStyles[2].index(style_name)
#Finds style ID by index
defaultStyleId = listedStyles[1][styleIndex]
#If we have styles in our db that are indeed recorded.
if numberOfStyles > 0:
    styledoc = QDomDocument()
    #Select right style
    styleTuple = layer.getStyleFromDatabase(defaultStyleId)
    styleqml = styleTuple[0]
    styledoc.setContent(styleqml)
    #Import style
    layer.importNamedStyle(styledoc)
    #Apply it
    layer.triggerRepaint()

I have multiple databases in postgres, ,some of them don't have styles recorded in them. That's why i do a test to see if there is a style recorded in it. The code above apply the whole style to the layer, but i need to find a way to only get the form from it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source