在上一篇中,我们图层所有的点位图标都是一样的,但是实际应用中可能每个点位所对应的图标确是不一样的,例如城镇里面的医院、超市、学校等等,都需要用不同的图标来进行标注。
#include <qgis/core.h>
#include <qgis/gui.h>
#include <QApplication>
#include <QIcon>
int main(int argc, char* argv[])
{
// 初始化QGIS应用程序
QgsApplication app(argc, argv, true);
// 加载QGIS提供的GUI工具
QgsGui::initResources();
// 创建地图Canvas(地图画布)
QgsMapCanvas canvas;
canvas.setCanvasColor(Qt::white);
canvas.enableAntiAliasing(true);
canvas.setMinimumSize(800, 600);
// 创建地图Layer(图层)
QgsVectorLayer* layer = new QgsVectorLayer("Point?crs=EPSG:4326", "Points", "memory");
if (!layer)
{
qDebug() << "Failed to create layer!";
return -1;
}
// 添加属性字段,用于区分不同的点位
layer->dataProvider()->addAttributes({QgsField("category", QVariant::String)});
// 创建Feature(要素)并设置点位属性
QgsFeature feature;
QgsGeometry* geometry = new QgsGeometry();
// 设置经纬度坐标,这里假设经度为x,纬度为y
double x1 = 123.456;
double y1 = 78.9;
geometry->addPointXY(x1, y1);
feature.setGeometry(geometry);
feature.setAttribute("category", "category1"); // 设置点位的属性值
// 将Feature添加到图层中
QgsVectorLayerEditBuffer editBuffer(layer);
editBuffer.addFeature(feature);
// 获取不同的点位图标
QString iconPath1 = ":/icons/marker1.png"; // 假设marker1.png是资源文件中的图标1
QString iconPath2 = ":/icons/marker2.png"; // 假设marker2.png是资源文件中的图标2
QIcon icon1(iconPath1);
QIcon icon2(iconPath2);
// 创建符号渲染器
QgsRuleBasedRendererV2* renderer = new QgsRuleBasedRendererV2();
// 创建规则1,根据"category"属性值为"category1"设置图标1
QgsSymbolV2* symbol1 = QgsSymbolV2::defaultSymbol(layer->geometryType());
QgsMarkerSymbolV2* markerSymbol1 = qobject_cast<QgsMarkerSymbolV2*>(symbol1);
markerSymbol1->setIcon(icon1);
QgsRuleBasedRendererV2::Rule* rule1 = new QgsRuleBasedRendererV2::Rule(markerSymbol1);
rule1->setLabel("Category 1");
rule1->setFilterExpression("\"category\" = 'category1'");
renderer->insertChildNode(0, rule1);
// 创建规则2,根据"category"属性值为"category2"设置图标2
QgsSymbolV2* symbol2 = QgsSymbolV2::defaultSymbol(layer->geometryType());
QgsMarkerSymbolV2* markerSymbol2 = qobject_cast<QgsMarkerSymbolV2*>(symbol2);
markerSymbol2->setIcon(icon2);
QgsRuleBasedRendererV2::Rule* rule2 = new QgsRuleBasedRendererV2::Rule(markerSymbol2);
rule2->setLabel("Category 2");
rule2->setFilterExpression("\"category\" = 'category2'");
renderer->insertChildNode(1, rule2);
layer->setRendererV2(renderer);
// 将图层添加到地图Canvas中
QgsMapLayerRegistry::instance()->addMapLayer(layer);
canvas.setExtent(layer->extent());
canvas.setLayers(QgsMapLayerRegistry::instance()->mapLayers().values());
// 显示地图Canvas
canvas.show();
// 运行QGIS应用程序
return app.exec();
}