As with my previous tutorials, the entire project can be checked out from the QGIS Subversion repository using the following command:
svn co https://svn.qgis.org/repos/qgis/trunk/code_examples/4_adding_rasters_to_canvas
In the working directory for the tutorial code you will find a number of files including c++ sources, icons and a simple data file under data. There is also the .ui file for the main window.
Note: You will need to edit the .pro file in the above svn directory to match your system.
#include <qgsrasterlayer.h>The code that follows sets up the main window and toolbars as covered in previous tutorials. The bit we are really interested in here is:
void MainWindow::addLayer() { QFileInfo myRasterFileInfo("data/Abarema_jupunba_projection.tif"); QgsRasterLayer * mypLayer = new QgsRasterLayer(myRasterFileInfo.filePath(), myRasterFileInfo.completeBaseName()); if (mypLayer->isValid()) { qDebug("Layer is valid"); } else { qDebug("Layer is NOT valid"); return; } mypLayer->setColorRampingType(QgsRasterLayer::BLUE_GREEN_RED); mypLayer->setDrawingStyle(QgsRasterLayer::SINGLE_BAND_PSEUDO_COLOR); std::dequeWell that wraps up this tutorial. Adding rasters to your mapcanvas is easy and doesnt take much coding. One thing you should bare in mind is that QGIS does not support on the fly reprojection of rasters so if you are planning to mix rasters from different spatial reference systesm you will probably get undesirable results. If you are planning to add vectors over the raster, add the raster layer to your canvas first and then the vectors. If the vectors are in a different spatial reference system to the raster, these vectors can be reprojected on the fly - which is something I will cover in a future tutorial.myLayerSet; // Add the Vector Layer to the Layer Registry QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE); // Add the Layer to the Layer Set myLayerSet.push_back(mypLayer->getLayerID()); mypLayer->setVisible(TRUE); // set teh canvas to the extent of our layer mpMapCanvas->setExtent(mypLayer->extent()); // Set the Map Canvas Layer Set mpMapCanvas->setLayerSet(myLayerSet); }
mkdir -p qgis_example3.app/Contents/MacOS/share/qgis/resources/ cp -r /Applications/qgis.app/Contents/MacOS/share/qgis/resources/* \ qgis_example3.app/Contents/MacOS/share/qgis/resources/