In my QGIS application, I would like to be able to have a QDialog window pop upon clicking a toolbar icon which lists the layers set to the map canvas, and have QCheckBoxes that allow the user to show/hide layers if needed. I am trying to do so in a C++ application. I have a Python version which follows the answer given by Denis Rouzaud in the following example: Setting layer visibility in QGIS Python API?
Here is the custom slot I wrote which follows the API documentation:
void layerDisplay::setDisplay(QString &layerName, bool &isChecked)
{
for ( QgsMapLayer *lay: qm0->layers() ) //qm0 is QgsMapCanvas
{
if ( layerName != lay->name() )
{
continue;
} else
{
//pj0 is the QgsProject
QgsLayerTreeNode *root = pj0->instance()->layerTreeRoot()->findLayer(lay->id());
root->setItemVisibilityCheckedRecursive(isChecked);
qm0->refresh();
QList<QgsMapLayer* > lst = root->checkedLayers();
if ( lst.isEmpty() )
{
cout << "Layer " << layerName.toStdString() << " is not checked" << endl;
} else
{
for ( QgsMapLayer *lc: lst )
{
cout << "Layer " << lc->name().toStdString() << " is checked" << endl;
}
}
}
}
}
and while the standard output tells me the layers have been checked or unchecked, the map canvas does not update; however the Python code works! If you need to see more code (eg the widget's header and mainwindow slot) I can update this question.
QgsLayerTreeMapCanvasBridgehttps://qgis.org/api/classQgsLayerTreeMapCanvasBridge.html ? It role is to syncQgsMapCanvaswith thelayerTreeRoot. It may explains why you do not see change on the canvas although you've changed yourcheckedstate for a layer. You may alternatively use thesetLayersinstead of going through the use oflayerTreeRoot. Could be wrong as I do not know your complete application requirement(s) – ThomasG77 May 06 '21 at 18:55setAutoSetupOnFirstLayer(false)for yourQgsLayerTreeMapCanvasBridgeinstance (check default behaviour withautoSetupOnFirstLayer()). According to the API doc, "if enabled, will automatically set full canvas extent and destination CRS + map units when first layer(s) are added". – ThomasG77 May 06 '21 at 20:00