I'm trying to add a QGis map in Qt/C++ widget using QgsMapCanvas, but I have some problems...

I'm working with the following environment: - Ubuntu 12.04 - QGis 2.8.1 - Qt Creator 2.4.1 (based on Qt 4.8.0 - 32 bit)

I found online a sample code that should do what I'm looking for, but something doesn't work..

The code is the following:

int main(int argc, char **argv)
    QgsApplication app(argc, argv, true);

    QString myPluginsDir        = "/home/pesce/qgis";
    QString myLayerPath         = "/home/pesce/qgis_sample_data/shapefiles/alaska.shp";
    QString myLayerBaseName     = "al";
    QString myProviderName      = "ogr";

    // Instantiate Provider Registry
    QgsProviderRegistry * preg = QgsProviderRegistry::instance(myPluginsDir);

    QgsVectorLayer *mypLayer =  new QgsVectorLayer(myLayerPath,myLayerBaseName,myProviderName);

    QgsSingleSymbolRendererV2 *mypRenderer = new QgsSingleSymbolRendererV2(QgsSymbolV2::defaultSymbol(mypLayer->geometryType()));

    QList <QgsMapCanvasLayer> myLayerSet;


        qDebug("Layer is valid");
    } else {
        qDebug("Layer is NOT valid");

    // Add the Vector Layer to the Layer Registry
    QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE);
    // Add the Layer to the Layer Set
    myLayerSet.append(QgsMapCanvasLayer(mypLayer, TRUE));

    // Create the Map Canvas
    QgsMapCanvas * mypMapCanvas = new QgsMapCanvas(0, 0);
    mypMapCanvas->setCanvasColor(QColor(255, 255, 255));
    // Set the Map Canvas Layer Set

    return app.exec();

The code is correctly compiled and the program correctly starts, but the map is empty..nothing is show... the selected layer (/home/pesce/qgis_sample_data/shapefiles/alaska.shp) seems to be not valid (mypLayer->isValid() returns "false")... but it's a .shp file....it should be valid!

Which kind of files are supported?

2 Answers 2


Make sure you have setup the environment for QGIS properly before you start using the providers.

In particular you will have to call

QgsApplication::setPrefixPath( prefixPath )

before using providers.

See also this answer


i think it is your method when you delcare your myplayer.

try this way :

QString myFileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                       QCoreApplication::applicationDirPath () + "/data",
                       tr("GeoTiff (*.shp)"));
  QFileInfo myRasterFileInfo(myFileName);

  qDebug() << "myFileName =" << myFileName;

QgsVectorLayer * mypLayer =  new QgsVectorLayer(myRasterFileInfo.filePath(), myRasterFileInfo.completeBaseName(), myProviderName);

QgsSingleSymbolRendererV2 *mypRenderer = new QgsSingleSymbolRendererV2(QgsSymbolV2::defaultSymbol(mypLayer->geometryType()));

it works in 2.8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.