首页 > 代码库 > QGis(二)添加缩放漫游工具栏

QGis(二)添加缩放漫游工具栏

QGis添加图层后可以用鼠标滚动缩放,如果想添加图标到工具栏实现相同的效果,如图:


(1)在QMainWindow中添加如下变量:

QToolBar *mpMapToolBar;	///<地图操作相关的工具栏
QgsMapTool *mpPanTool;	///<漫游
QgsMapTool *mpZoomInTool;///<放大
QgsMapTool *mpZoomOutTool;///<缩小
QgsMapTool *mpZoomFull;	///<全图显示

在Qt设计师里面添加Action:


(2)然后在初始化函数里添加:

//添加工具栏上按钮
mpMapToolBar = addToolBar(tr("Tools"));
mpMapToolBar->addSeparator();
mpMapToolBar->addAction(ui.mpActionPan);
mpMapToolBar->addAction(ui.mpActionZoomIn);
mpMapToolBar->addAction(ui.mpActionZoomOut);
mpMapToolBar->addAction(ui.mpActionZoomFull);

mpPanTool= new QgsMapToolPan(mainMapCanvas);  
mpPanTool->setAction(ui.mpActionPan);  
mpZoomInTool = new QgsMapToolZoom(mainMapCanvas,false);  
mpZoomInTool->setAction(ui.mpActionZoomIn);  
mpZoomOutTool = new QgsMapToolZoom(mainMapCanvas,true);  
mpZoomOutTool->setAction(ui.mpActionZoomOut);  
(3)添加信号槽函数连接:

connect(ui.mpActionPan,SIGNAL(triggered()),this,SLOT(panMode()));  
connect(ui.mpActionZoomIn,SIGNAL(triggered()),this,SLOT(zoomInMode()));  
connect(ui.mpActionZoomOut,SIGNAL(triggered()),this,SLOT(zoomOutMode()));  
connect(ui.mpActionZoomFull, SIGNAL(triggered()), this, SLOT(zoomFull()));
(4)槽函数实现:

void MainWindow::zoomInMode()
{
	mainMapCanvas->setMapTool(mpZoomInTool);
	if ( mainMapCanvas->layer(0)->type() == QgsMapLayer::RasterLayer)
	{
		return;
	}
	QgsVectorLayer *pLayer=(QgsVectorLayer *)mainMapCanvas->layer(0);
	pLayer->removeSelection(true);
}

void MainWindow::zoomOutMode()
{
	mainMapCanvas->setMapTool(mpZoomOutTool);
	if ( mainMapCanvas->layer(0)->type() == QgsMapLayer::RasterLayer)
	{
		return;
	}
	QgsVectorLayer *pLayer=(QgsVectorLayer *)mainMapCanvas->layer(0);
	pLayer->removeSelection(true);
}

void MainWindow::panMode()
{
	mainMapCanvas->setMapTool(mpPanTool);
	ui.mpActionPan->setCheckable(true);
	ui.mpActionPan->setChecked(true);
	if ( mainMapCanvas->layer(0)->type() == QgsMapLayer::RasterLayer)
	{
		return;
	}
	QgsVectorLayer *pLayer=(QgsVectorLayer *)mainMapCanvas->layer(0);
	pLayer->removeSelection(true);
}

void MainWindow::zoomFull()
{
	mainMapCanvas->zoomToFullExtent();
	if ( mainMapCanvas->layer(0)->type() == QgsMapLayer::RasterLayer)
	{
		return;
	}
	QgsVectorLayer *pLayer=(QgsVectorLayer *)mainMapCanvas->layer(0);
	pLayer->removeSelection(true);
}
上面的mainMapCanvas就是已经加载了矢量图层的。