1

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 &lt;&lt; &quot;Layer &quot; &lt;&lt; layerName.toStdString() &lt;&lt; &quot; is not checked&quot; &lt;&lt; endl;
        } else
        {
            for ( QgsMapLayer *lc: lst )
            {
                cout &lt;&lt; &quot;Layer &quot; &lt;&lt; lc-&gt;name().toStdString() &lt;&lt; &quot; is checked&quot; &lt;&lt; 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.

skew_t_pie
  • 175
  • 7
  • 2
    Did you declare a QgsLayerTreeMapCanvasBridge https://qgis.org/api/classQgsLayerTreeMapCanvasBridge.html ? It role is to sync QgsMapCanvas with thelayerTreeRoot. It may explains why you do not see change on the canvas although you've changed your checked state for a layer. You may alternatively use the setLayers instead of going through the use of layerTreeRoot. Could be wrong as I do not know your complete application requirement(s) – ThomasG77 May 06 '21 at 18:55
  • @ThomasG77 I did not...and this worked! Well almost. It zooms out and away from the set center, anyway to prevent that without manually doing so? – skew_t_pie May 06 '21 at 19:28
  • Maybe setAutoSetupOnFirstLayer(false) for your QgsLayerTreeMapCanvasBridge instance (check default behaviour with autoSetupOnFirstLayer()). 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
  • @ThomasG77 doesn't seem to offset it; I set it to false initially and then re-center and zoom back in to the set center point. Still working on having the un-checked layers to reappear upon re-checking but progress is progress, thank you. – skew_t_pie May 06 '21 at 21:24

0 Answers0