效果图
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 menu
if(!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 selected
if(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 DO
m_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);
//创建QgsSymbolLayerList
QgsSymbolLayerList Sym_Layer_List;
//判断是点渲染还是面渲染
if(veclayer->geometryType() == QgsWkbTypes::PointGeometry )
{
// 构建QgsMarkerSymbol
QgsMarkerSymbol *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)
{
// 构建QgsFillSymbol
QgsFillSymbol *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)
{
// 构建QgslineSymbol
QgsLineSymbol *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 nodes
qobject_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 extent
layerExtent = 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_OBJECT
public:
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 DO
QgsMapLayer* 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;
}
构造函数中添加文章来源:https://www.toymoban.com/news/detail-449927.html
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:
//new
void 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用于显示标签。文章来源地址https://www.toymoban.com/news/detail-449927.html
labelcontrol.h
#ifndef LABELCONTROL_H
#define LABELCONTROL_H
#include <QWidget>
namespace Ui {
class LabelControl;
}
class LabelControl : public QWidget
{
Q_OBJECT
public:
explicit LabelControl(QWidget *parent = nullptr);
~LabelControl();
void SetItems(QStringList items); //设置combox列表内容
void SetInitInfo(bool bshow,QString name); //设置初始显示内容
QString GetSelectedItem(); //获取选中的项
bool isShowLabel(); //是否显示label
private 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);
else
ui->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);
}else
emit 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中实现图层树右键图层更改图层颜色,以及图层标注。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!