目录

  • 效果图
  • 思路
  • mygistreeviewmenu.h
  • mygistreeviewmenu.cpp
  • Symbolstyle.h
  • Symbolstyle.cpp
  • mainwindow.cpp
  • mainwindow.h
  • main.cpp
  • labelcontrol.h
  • labelcontrol.cpp

效果图

qgis图层树右键图层更改图层颜色,以及图层标注。

思路

新建一个类mygistreeviewmenu用于管理图层树,新建一个窗体类symbolstyle用于选择颜色。新建一个窗体类labelcontrol用于设置标注。

mygistreeviewmenu.h

#ifndef MYGISTREEVIEWMENU_H
#define MYGISTREEVIEWMENU_H
#include <QObject>
#include "qgslayertreeview.h"
#include "qgsmaplayer.h"
#include "symbolstyle.h"
class QAction;
class QgsMapCanvas;
class MyGistreeviewMenu : public QObject, public QgsLayerTreeViewMenuProvider
{Q_OBJECT
public:MyGistreeviewMenu(QgsLayerTreeView* view,QgsMapCanvas* canvas);~MyGistreeviewMenu() override;QMenu * createContextMenu() override; // 创建菜单
private:QgsLayerTreeView* m_layerTreeView;QgsMapCanvas* m_mapCanvas;Symbolstyle *colordlg{nullptr};private slots:void slot_autoSelectAddedLayer(const QList<QgsMapLayer *> layers);void slot_pointstyle(QString);  //点样式窗口显控void slot_pointstyleclick();
};#endif // MYGISTREEVIEWMENU_H

mygistreeviewmenu.cpp

#include "mygistreeviewmenu.h"
#include "mainwindow.h"
#include <QMenu>
#include <QModelIndex>
#include <QIcon>
#include <qgswkbtypes.h>//QGIS include
#include "qgslayertreeviewdefaultactions.h"
#include "qgslayertreenode.h"
#include "qgslayertreemodel.h"
#include "qgslayertree.h"
#include "qgsrasterlayer.h"
#include "qgsvectorlayer.h"
#include"labelcontrol.h"
#include <qgssinglesymbolrenderer.h>
#include "qgsmarkersymbollayer.h"MyGistreeviewMenu::MyGistreeviewMenu(QgsLayerTreeView* view,QgsMapCanvas* canvas)
{m_layerTreeView = view;m_mapCanvas = canvas;colordlg = new Symbolstyle();connect(colordlg,SIGNAL(color(QString)),this,SLOT(slot_pointstyle(QString)));
}MyGistreeviewMenu::~MyGistreeviewMenu()
{}
//创建菜单
QMenu *MyGistreeviewMenu::createContextMenu()
{QMenu* menu = new QMenu;QgsLayerTreeViewDefaultActions* actions = m_layerTreeView->defaultActions();QModelIndex idx = m_layerTreeView->currentIndex();// global menuif(!idx.isValid()){menu->addAction(actions->actionAddGroup(menu));menu->addAction(tr("&Expand All"),m_layerTreeView,SLOT(expandAll()));menu->addAction(tr("&Collapse All"),m_layerTreeView,SLOT(collapseAll()));}else{QgsLayerTreeNode* node = m_layerTreeView->layerTreeModel()->index2node(idx);//layer or group selectedif(QgsLayerTree::isGroup(node)){menu->addAction(actions->actionZoomToGroup(m_mapCanvas,menu));menu->addAction(actions->actionRemoveGroupOrLayer(menu));menu->addAction(actions->actionRenameGroupOrLayer());if(m_layerTreeView->selectedNodes(true).count() >= 2)menu->addAction(actions->actionGroupSelected(menu));menu->addAction(actions->actionAddGroup(menu));}else if(QgsLayerTree::isLayer(node)){QgsMapLayer* layer = QgsLayerTree::toLayer(node)->layer();menu->addAction(actions->actionZoomToLayer(m_mapCanvas,menu));menu->addAction(actions->actionRemoveGroupOrLayer(menu));menu->addAction(tr("&Label"),MainWindow::Instance(),SLOT(slot_labelShowAction()));
//            QAction *labelaction = menu->addAction("Label");
//            connect(labelaction,SIGNAL(triggered()),MainWindow::Instance(),SLOT(slot_labelShowAction()));if(layer->type() == QgsMapLayerType::VectorLayer){//点矢量图层增加点样式设置菜单QgsVectorLayer* veclayer = qobject_cast<QgsVectorLayer*>(layer);if(veclayer->geometryType() == QgsWkbTypes::PointGeometry ){menu->addAction(tr("PointStyle"),this,SLOT(slot_pointstyleclick()));}else if(veclayer->geometryType() == QgsWkbTypes::PolygonGeometry){menu->addAction(tr("PolygonStyle"),this,SLOT(slot_pointstyleclick()));}else if(veclayer->geometryType() == QgsWkbTypes::LineGeometry){menu->addAction(tr("LineStyle"),this,SLOT(slot_pointstyleclick()));}}}}return menu;
}//图层控制器树结构变化
void MyGistreeviewMenu::slot_autoSelectAddedLayer(const QList<QgsMapLayer *> layers)
{if ( !layers.isEmpty() ){QgsLayerTreeLayer *nodeLayer = QgsProject::instance()->layerTreeRoot()->findLayer( layers[0]->id() );if ( !nodeLayer )return;QModelIndex index = m_layerTreeView->layerTreeModel()->node2index( nodeLayer );m_layerTreeView->setCurrentIndex( index );}
}void MyGistreeviewMenu::slot_pointstyleclick()
{colordlg->raise();colordlg->activateWindow();colordlg->show();
}//点样式-右键菜单
void MyGistreeviewMenu::slot_pointstyle(QString name)
{//TO DOm_mapCanvas->freeze();//获取当前图层QModelIndex idx = m_layerTreeView->currentIndex();QgsLayerTreeNode* node = m_layerTreeView->layerTreeModel()->index2node(idx);QgsMapLayer* layer = QgsLayerTree::toLayer(node)->layer();QgsVectorLayer* veclayer = qobject_cast<QgsVectorLayer*>(layer);//创建QgsSymbolLayerListQgsSymbolLayerList Sym_Layer_List;//判断是点渲染还是面渲染if(veclayer->geometryType() == QgsWkbTypes::PointGeometry ){// 构建QgsMarkerSymbolQgsMarkerSymbol *markersymbol =new QgsMarkerSymbol(Sym_Layer_List);//设置颜色if(name==QString::fromLocal8Bit("红色"))markersymbol->setColor(Qt::red);if(name==QString::fromLocal8Bit("绿色"))markersymbol->setColor(Qt::green);if(name==QString::fromLocal8Bit("蓝色"))markersymbol->setColor(Qt::blue);if(name==QString::fromLocal8Bit("黑色"))markersymbol->setColor(Qt::black);if(name==QString::fromLocal8Bit("黄色"))markersymbol->setColor(Qt::yellow);if(name==QString::fromLocal8Bit("灰色"))markersymbol->setColor(Qt::gray);// 构建QgsSingleSymbolRenderer, 即最终图层的渲染器QgsSingleSymbolRenderer *render1=new QgsSingleSymbolRenderer(markersymbol);veclayer->setRenderer(render1);}if(veclayer->geometryType() == QgsWkbTypes::PolygonGeometry){// 构建QgsFillSymbolQgsFillSymbol *fillsymbol = new QgsFillSymbol(Sym_Layer_List);//设置颜色if(name==QString::fromLocal8Bit("红色"))fillsymbol->setColor(Qt::red);if(name==QString::fromLocal8Bit("绿色"))fillsymbol->setColor(Qt::green);if(name==QString::fromLocal8Bit("蓝色"))fillsymbol->setColor(Qt::blue);if(name==QString::fromLocal8Bit("黑色"))fillsymbol->setColor(Qt::black);if(name==QString::fromLocal8Bit("黄色"))fillsymbol->setColor(Qt::yellow);if(name==QString::fromLocal8Bit("灰色"))fillsymbol->setColor(Qt::gray);// 构建QgsSingleSymbolRenderer, 即最终图层的渲染器QgsSingleSymbolRenderer *render1=new QgsSingleSymbolRenderer(fillsymbol);veclayer->setRenderer(render1);}if(veclayer->geometryType() == QgsWkbTypes::LineGeometry){// 构建QgslineSymbolQgsLineSymbol *linesymbol = new QgsLineSymbol(Sym_Layer_List);//设置颜色if(name==QString::fromLocal8Bit("红色"))linesymbol->setColor(Qt::red);if(name==QString::fromLocal8Bit("绿色"))linesymbol->setColor(Qt::green);if(name==QString::fromLocal8Bit("蓝色"))linesymbol->setColor(Qt::blue);if(name==QString::fromLocal8Bit("黑色"))linesymbol->setColor(Qt::black);if(name==QString::fromLocal8Bit("黄色"))linesymbol->setColor(Qt::yellow);if(name==QString::fromLocal8Bit("灰色"))linesymbol->setColor(Qt::gray);// 构建QgsSingleSymbolRenderer, 即最终图层的渲染器QgsSingleSymbolRenderer *render1=new QgsSingleSymbolRenderer(linesymbol);veclayer->setRenderer(render1);}m_mapCanvas->freeze( false );m_mapCanvas->refresh();
}//附移除图层,缩放至图层源代码
void MyGistreeviewMenu::slot_removelayer()
{QModelIndex idx = m_layerTreeView->currentIndex();QgsLayerTreeNode* node = m_layerTreeView->layerTreeModel()->index2node(idx);// could be more efficient if working directly with ranges instead of individual nodesqobject_cast<QgsLayerTreeGroup *>( node->parent() )->removeChildNode( node );
}void MyGistreeviewMenu::zoomToLayers()
{QgsRectangle extent;extent.setMinimal();QModelIndex idx = m_layerTreeView->currentIndex();QgsLayerTreeNode* node = m_layerTreeView->layerTreeModel()->index2node(idx);QgsMapLayer* layer = QgsLayerTree::toLayer(node)->layer();QgsRectangle layerExtent = layer->extent();QgsVectorLayer* vLayer = qobject_cast<QgsVectorLayer*>(layer);vLayer->updateExtents();layerExtent = vLayer->extent();//transform extentlayerExtent = m_mapCanvas->mapSettings().layerExtentToOutputExtent( layer, layerExtent );extent.combineExtentWith( layerExtent );m_mapCanvas->setExtent( extent, true );m_mapCanvas->refresh();
}

Symbolstyle.h

#ifndef SYMBOLSTYLE_H
#define SYMBOLSTYLE_H#include <QWidget>namespace Ui {class Symbolstyle;
}class Symbolstyle : public QWidget
{Q_OBJECTpublic:explicit Symbolstyle(QWidget *parent = nullptr);~Symbolstyle();QString colorname();
private slots:void on_pushButton_clicked();void on_pushButton_2_clicked();signals:void color(QString);private:Ui::Symbolstyle *ui;};#endif // SYMBOLSTYLE_H

Symbolstyle.cpp

#include "symbolstyle.h"
#include "ui_symbolstyle.h"Symbolstyle::Symbolstyle(QWidget *parent) :QWidget(parent),ui(new Ui::Symbolstyle)
{ui->setupUi(this);QStringList ll;ll<<QString::fromLocal8Bit("红色") << QString::fromLocal8Bit("绿色") << QString::fromLocal8Bit("蓝色")<<QString::fromLocal8Bit("黑色")<<QString::fromLocal8Bit("黄色")<<QString::fromLocal8Bit("灰色");ui->comboBox->addItems(ll);
}Symbolstyle::~Symbolstyle()
{delete ui;
}void Symbolstyle::on_pushButton_clicked()
{QString colorname = ui->comboBox->currentText();emit color(colorname);
}void Symbolstyle::on_pushButton_2_clicked()
{this->close();
}QString Symbolstyle::colorname()
{return ui->comboBox->currentText();
}

mainwindow.cpp

struct StLabelShowInfo
{bool bshow;        //是否显示标签QString name;    //显示的标签字段
};
QMap<QgsVectorLayer*,StLabelShowInfo> m_mapLabelshowInfo;  //记录每个图层上一次的标签显示信息//标签显示变更
void MainWindow::slot_labelctrlChange(int id,bool bchange,QString name)
{if(m_dlgLabelctrl){m_dlgLabelctrl->hide();delete m_dlgLabelctrl;m_dlgLabelctrl = 0;}if(id == 1){QgsMapLayer* ll = m_layerTreeView->currentLayer();if(ll && ll->type() == QgsMapLayerType::VectorLayer ){QgsVectorLayer* vecLayer =qobject_cast<QgsVectorLayer*>(ll);//标签显示信息查询QMap<QgsVectorLayer*,StLabelShowInfo>::iterator it =  m_mapLabelshowInfo.find(vecLayer);  //标签显示信息StLabelShowInfo st;if(it != m_mapLabelshowInfo.end()){st = it.value();m_mapLabelshowInfo.erase(it);}st.bshow = bchange;st.name = name;m_mapLabelshowInfo.insert(vecLayer,st);if(bchange){//显示标签QgsPalLayerSettings layerSettings;layerSettings.drawLabels = true;layerSettings.fieldName = name;layerSettings.isExpression = false;layerSettings.placement = QgsPalLayerSettings::OverPoint;layerSettings.yOffset = 2.50;QgsTextBufferSettings buffersettings;buffersettings.setEnabled(false);buffersettings.setSize(1);buffersettings.setColor(QColor());QgsTextFormat format;QFont font("SimSun",5,5,false);font.setUnderline(false);format.setFont(font);format.setBuffer(buffersettings);layerSettings.setFormat(format);QgsVectorLayerSimpleLabeling * labeling = new QgsVectorLayerSimpleLabeling (layerSettings);vecLayer->setLabeling(labeling);vecLayer->setLabelsEnabled(true);}else{vecLayer->setLabelsEnabled(false);}m_mapcanvas->refresh();} //vecterlayer}// change//设置图层显示标签
void MainWindow::slot_labelShowAction()
{//TO DOQgsMapLayer* layer =m_layerTreeView->currentLayer();if(layer && layer->type() == QgsMapLayerType::VectorLayer){QgsVectorLayer* veclayer = qobject_cast<QgsVectorLayer*>(layer);//查找标签显示信息QMap<QgsVectorLayer*,StLabelShowInfo>::iterator it =  m_mapLabelshowInfo.find(veclayer);  //标签显示信息StLabelShowInfo st;if(it != m_mapLabelshowInfo.end())st = it.value();else{st.bshow = false;st.name = "";}QStringList items = veclayer->fields().names();if(m_dlgLabelctrl == nullptr){m_dlgLabelctrl = new LabelControl();connect(m_dlgLabelctrl,SIGNAL(sig_labelctrlBtnClicked(int,bool,QString)),this,SLOT(slot_labelctrlChange(int,bool,QString)));}m_dlgLabelctrl->SetItems(items);m_dlgLabelctrl->SetInitInfo(st.bshow,st.name);m_dlgLabelctrl->show();m_dlgLabelctrl->raise();m_dlgLabelctrl->activateWindow();}}MainWindow* MainWindow::m_appinstance = nullptr;
//返回实例指针
MainWindow *MainWindow::Instance()
{if(!m_appinstance){m_appinstance = new MainWindow();}return m_appinstance;
}

构造函数中添加

   MyGistreeviewMenu *menu = new MyGistreeviewMenu(m_layerTreeView,m_mapcanvas);m_layerTreeView->setMenuProvider(menu);connect(QgsProject::instance()->layerTreeRegistryBridge(),SIGNAL(addedLayersToLayerTree(const QList<QgsMapLayer*>)),this,SLOT(slot_autoSelectAddedLayer( const QList<QgsMapLayer*>)));

mainwindow.h

private slots://newvoid slot_labelctrlChange(int id,bool bchange,QString name);void slot_labelShowAction()  ;  //设置图层显示标签void on_actionselectbyvalue_triggered();
private:LabelControl *m_dlgLabelctrl{nullptr};
public:static MainWindow* Instance();   //返回主窗口实例指针
private:static MainWindow* m_appinstance;

main.cpp

#include "mainwindow.h"
#include "qgsapplication.h"
#include <QDir>
#include "odbchelper.h"
#include "QDebug"
int main(int argc, char *argv[])
{QgsApplication a(argc, argv,true);QgsApplication::setPluginPath(QDir::currentPath() + "/plugins");QgsApplication::initQgis();  //初始化QGIS应用MainWindow *w = MainWindow::Instance();w->show();odbchelper o;   return a.exec();}

添加一个窗体类labelcontrol用于显示标签。

labelcontrol.h

#ifndef LABELCONTROL_H
#define LABELCONTROL_H#include <QWidget>namespace Ui {class LabelControl;
}class LabelControl : public QWidget
{Q_OBJECTpublic:explicit LabelControl(QWidget *parent = nullptr);~LabelControl();void SetItems(QStringList items);  //设置combox列表内容void SetInitInfo(bool bshow,QString name);  //设置初始显示内容QString GetSelectedItem();         //获取选中的项bool isShowLabel();                     //是否显示labelprivate slots:void on_btnOk_clicked();void on_btnCancle_clicked();signals:void sig_labelctrlBtnClicked(int,bool,QString);private:Ui::LabelControl *ui;bool m_bshowLabels;               //是否显示字段QString m_strShowName;        //显示的字段名称
};#endif // LABELCONTROL_H

labelcontrol.cpp

#include "labelcontrol.h"
#include "ui_labelcontrol.h"LabelControl::LabelControl(QWidget *parent) :QWidget(parent),ui(new Ui::LabelControl)
{ui->setupUi(this);QStringList ll;ll<<QString::fromLocal8Bit("显示") << QString::fromLocal8Bit("不显示");ui->comboBox_show->addItems(ll);ui->comboBox_show->setCurrentIndex(1);m_bshowLabels = false;m_strShowName = "";setWindowTitle(QString::fromLocal8Bit("标签设置"));QPalette pe = this->palette();pe.setColor(QPalette::Background,Qt::white);setPalette(pe);
}LabelControl::~LabelControl()
{delete ui;
}
//设置combox列表内容
void LabelControl::SetItems(QStringList items)
{ui->comboBox_items->clear();ui->comboBox_items->addItems(items);
}
//设置初始显示内容
void LabelControl::SetInitInfo(bool bshow, QString name)
{if(bshow)ui->comboBox_show->setCurrentIndex(0);elseui->comboBox_show->setCurrentIndex(1);if(!name.isEmpty())ui->comboBox_items->setCurrentText(name);
}
//获取选中的项
QString LabelControl::GetSelectedItem()
{return ui->comboBox_items->currentText();
}
//是否显示label
bool LabelControl::isShowLabel()
{return true;
}
//OK
void LabelControl::on_btnOk_clicked()
{int ind = ui->comboBox_show->currentIndex();bool sh = false;if(ind == 0) sh = true;QString name = ui->comboBox_items->currentText();if(sh != m_bshowLabels || name != m_strShowName){m_bshowLabels = sh;m_strShowName = name;emit sig_labelctrlBtnClicked(1,m_bshowLabels,m_strShowName);}elseemit sig_labelctrlBtnClicked(0,m_bshowLabels,m_strShowName);  //Do nothing}}//Cancle
void LabelControl::on_btnCancle_clicked()
{emit sig_labelctrlBtnClicked(0,m_bshowLabels,m_strShowName);
}

12.qgis二次开发qt中实现图层树右键图层更改图层颜色,以及图层标注。相关推荐

  1. QGIS二次开发:加载XYZ Tiles形式的瓦片地图

    1.前言 QGIS官方提供的QGIS.exe可以加载远程地图提供商提供的基于URL格式的XYZ Tiles形式的瓦片地图.如:https://tile.openstreetmap.org/{z}/{x ...

  2. QGis二次开发基础 -- 根据属性查询要素

    属性查询是GIS应用不可缺少的重要功能,尤其是在各种业务系统中,根据用户输入相应的查询条件,从属性要素中快速定位到用户感兴趣的要素,为业务应用提供了便利.本文就来聊一聊QGis二次开发中如何实现属性查 ...

  3. qgis二次开发环境搭建(超级详细)

    最近有一个项目要求基于qgis+QT进行二次开发开发,要使用到qgis平台.陆陆 续续花了差不多两个多星期,在把开发环境搭建起来. 首先就面临2种选择,一种 到qgis官网下载源码,进行编译,此 情况 ...

  4. QGis二次开发基础 -- 构建图层管理器

    为了回应有些同学对上一篇博文的建议,这篇文章主要关注于QGis二次开发中的"图层管理器"的实现. 使用QGis构建独立应用系统,我相信大部分同学应该还是关注于GIS基本功能框架构建 ...

  5. 我的CAD二次开发程序中的操作excel的部分

    这是我的CAD二次开发程序中的操作excel的部分,特此分享 using System; using System.Collections.Generic; using System.Text; us ...

  6. QGIS二次开发地图添加标记添加注记Svg小图标SvgItem

    QGIS二次开发地图添加标记添加注记Svg小图标 即QgsAnnotationLayer.QgsMarkerSymbol和QgsAnnotationMarkerItem的用法,我把QGIS3.20软件 ...

  7. QGIS二次开发:鼠标在地图上移动时,状态栏显示鼠标所在位置经纬度

    主要思路: 当鼠标在地图画布控件上移动时,会发送xyCoordinates信号,该信号参数是墨卡托坐标系表示的地图上的点坐标,然后将墨卡托坐标转为经纬度表示的WSG84坐标,绑定该信号到槽函数,然后发 ...

  8. Python SolidWorks 二次开发—SolidWorks中的事件实现

    Python SolidWorks 二次开发-SolidWorks中的事件实现 文章目录 Python SolidWorks 二次开发---SolidWorks中的事件实现 前言 一.如何实现com事 ...

  9. CAD二次开发C#.Net编程-CAD创建右键菜单

    CAD二次开发&C#.Net编程-CAD创建右键菜单 private static ContextMenuExtension m_ContextMenu;//装载右键菜单public stat ...

  10. qt中qlineedit和qtextedit右键菜单翻译成中文

    qt中qlineedit和qtextedit右键菜单翻译成中文 qlineedit和qtextedit属于qwidget控件,在源码中找到../widgets/widgets.pro,在.pro文件最 ...

最新文章

  1. python 搭建系统监控
  2. Pycharm搜索文件名、符号名
  3. 双指针找链表中点多种写法
  4. MATLAB中的分类器
  5. python 通过shutil.move移动图片出错xe5\xb8\xb8\xe7
  6. 【Java字节码操作】JavaAssist的使用方式,代码示例
  7. adb无法连接安卓手机
  8. ReportViewer教程(15)-矩阵报表-5
  9. 海量数据挖掘MMDS week5: 计算广告Computational Advertising
  10. 简洁优雅的.net代码赏析
  11. 人只会看到他想看的,不想看的视而不见
  12. mysql 在线语法检查工具_「mysql 管理工具」五大开源MySQL管理工具! - seo实验室
  13. php 四叉树quadtree,线性四叉树十进制编码原理 四叉树(Quadtrees)一共有多少种?...
  14. 三星S7edge番茄花园ROM
  15. 2.IDEA修改主题
  16. 数值分析课程主要学习内容总结
  17. 苹果MFI bluetooth认证开发过程:iDevice和accessory
  18. 我de虚拟经济学系列---第二章 经济繁荣不建桥
  19. ip地址数据库 高效解析查询
  20. TCP ACKed unseen segment TCP Previous not captured

热门文章

  1. 离散 单射 满射 双射
  2. 核只有单位元等价于映射是单射
  3. 微信小游戏世界排行榜的绘制
  4. win7远程服务器管理工具
  5. [江枫]用Amoeba构架MySQL分布式数据库环境
  6. roblox虚拟世界怎么做服务器,roblox虚拟世界
  7. 电脑换硬盘要重装系统吗
  8. keil5编写C51程序
  9. python二项分布产生随机数_python随机生成 - osc_c10h48oh的个人空间 - OSCHINA - 中文开源技术交流社区...
  10. 线程基础 第一篇:线程的定义、状态、属性、简单实现线程