1

I am trying to change the default symbol for the point/line/ polygon vector layer using QGIS3 C++ APIs.

I was able to render a vector layer with default symbols on QgsMapCanvas. When I try to change the default symbol of the point vector layer, somehow it is not changing. When I am trying to change color, it does not change color as expected, but the symbol color changes in a different color. Here is the piece of code.

layer->startEditing();     
qDebug()<< "is editable " << layer->isEditable();  // returns true
QgsFeatureRenderer * layerRenderer= layer->renderer();
QgsSingleSymbolRenderer *mSingleRenderer = QgsSingleSymbolRenderer::convertFromRenderer(layerRenderer);
QgsMarkerSymbol* symbol = new  QgsMarkerSymbol();
QgsStringMap mp;
mp[QString("name")]= QString("square");
mp[QString("color")]=QString("yellow");
symbol->createSimple(mp);
symbol->setColor(QColor(255,255,255));
mSingleRenderer->setSymbol(symbol);
layer->triggerRepaint();
mLayerTreeView->refreshLayerSymbology(layer->id());
layer->commitChanges();

variable-name layer defines QgsVectorLayer.

1 Answer 1

3

A Python correction to get your issues (moreover, was too long to get a minimum C++ project to debug ;) )

layer = iface.activeLayer()

layerRenderer= layer.renderer()
mSingleRenderer = QgsSingleSymbolRenderer.convertFromRenderer(layerRenderer)
# No need to instantiate here
#symbol = QgsMarkerSymbol()

style = {
    "name": "square",
    "color": "yellow"
}
# Issue 1: you create a symbol but do not assign it
# (not void function, it returns a new element)
new_sym = QgsMarkerSymbol.createSimple(style)
# Commented as it was already working with above code
# symbol.setColor(QColor(255,255,255));
mSingleRenderer.setSymbol(new_sym)
# Issue 2: Forgot to reassign the newly created renderer to your layer
layer.setRenderer(mSingleRenderer)
layer.triggerRepaint()

# Did not test, commented so can be tested "standalone" in PyQGIS
# mLayerTreeView.refreshLayerSymbology(layer.id())
0

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.