版权声明:未经作者允许不得转载,此插件不得用于商业用途。
目录
开发环境
QGIS 3.2
python(QGIS自带)
插件开发
__init__.py
from .map_swipe_plugin import MapSwipePlugin
def classFactory(iface):
return MapSwipePlugin(iface)
map_swipe_plugin.py
import os
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QComboBox, QPushButton
from qgis.core import QgsProject
from qgis.gui import QgsMapToolPan
from .map_swipe_tool import MapSwipeTool
plugin_path = os.path.dirname(__file__)
class MapSwipePlugin:
def __init__(self, iface):
self.iface = iface
self.canvas = iface.mapCanvas()
# 图层变化信号
QgsProject.instance().layerTreeRoot().layerOrderChanged.connect(self.combobox_add_items)
def initGui(self):
self.menu = self.title = "卷帘工具"
self._create_widget()
self.tool = MapSwipeTool(plugin_path, self.combobox, self.iface)
self.tool.deactivated.connect(self.tool_deactivated)
self.widget_action = self.iface.addToolBarWidget(self.widget)
def unload(self):
self.canvas.setMapTool(QgsMapToolPan(self.iface.mapCanvas()))
self.iface.removeToolBarIcon(self.widget_action)
del self.widget_action
def run(self):
if self.canvas.mapTool() != self.tool:
self.prevTool = self.canvas.mapTool()
self.canvas.setMapTool(self.tool)
else:
self.canvas.setMapTool(self.prevTool)
if self.pushbutton.isChecked() and self.combobox.isHidden():
self.combobox.show()
self.combobox_add_items()
else:
self.combobox.hide()
def _create_widget(self):
icon = QIcon(os.path.join(plugin_path, 'icon.png'))
# 新建widget
self.widget = QWidget(self.iface.mainWindow())
self.hlayout = QHBoxLayout(self.widget)
self.hlayout.setContentsMargins(0, 0, 0, 0)
self.pushbutton = QPushButton(icon, '', self.widget)
self.pushbutton.setCheckable(True)
self.pushbutton.setFlat(True)
self.combobox = QComboBox(self.widget)
self.hlayout.addWidget(self.pushbutton)
self.hlayout.addWidget(self.combobox)
self.combobox.hide()
self.combobox_add_items()
self.pushbutton.clicked.connect(self.run)
def combobox_add_items(self):
self.combobox.clear()
layers = QgsProject.instance().layerTreeRoot().layerOrder()
self.combobox.addItems([layer.name() for layer in layers])
def tool_deactiv