I'm developing my QGIS3 plugin and I've realized that if I have the Python console active (so I can see it) the plugin behaves as expected, while if I don't see it doesn't. So this is the code:
for field in fields_db:
field = field[0]
layer = self.db.addPostGISLayer('fields', 'polygon', 'public',
extra_name=field + '_',
filter_text="field_name='{f}'".format(f=field))
set_label(layer, 'field_name')
QgsProject.instance().addMapLayer(layer)
print('Added')
set_zoom(self.parent.iface, 1.1)
self.defined_field = ''
When I run the code with the python console present the layers adds one by one, and zoom to the fields.
However when I don't have the Python console (or print('added')
is comment away with a #
). The code wait until all layers are ready to show and adds them at the same time in the end and it doesn't manage to zoom to the fields either(?). Any suggestions what I may edit?
This is the set_zoom
code :
def set_zoom(iface, extra_extent):
"""
Sets the zoom level to include all layers (excluding tiles layer) with some extra extent
Parameters
----------
iface: QGIS interface
The QGIS iface module.
extra_extent: float
How much extra space around the layers eg. 1.1 is 10% extra
Returns
-------
"""
zoom_extent = QgsRectangle()
for layer in QgsProject.instance().mapLayers().values():
if 'xyz&url' not in layer.source():
zoom_extent.combineExtentWith(layer.extent())
if zoom_extent.center().x() != 0.0:
wgsCRS = QgsCoordinateReferenceSystem(4326)
QgsProject.instance().setCrs(wgsCRS)
zoom_extent.scale(extra_extent)
iface.mapCanvas().setExtent(zoom_extent)
iface.mapCanvas().refresh()
wgsCRS = QgsCoordinateReferenceSystem(3857)
QgsProject.instance().setCrs(wgsCRS)