pyqt5 addLegend使用例子
时间: 2023-05-25 12:04:02 浏览: 178
PyQt5 example code
以下是一个使用pyqt5中QgsMapCanvas和QgsLayerTreeView添加图例的例子:
```python
from PyQt5.QtWidgets import QMainWindow, QToolBar, QDockWidget, QVBoxLayout, QWidget
from qgis.gui import QgsMapCanvas, QgsLayerTreeView
from qgis.core import QgsProject, QgsLayerDefinition
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Add Legend')
self.setGeometry(100, 100, 800, 600)
# 创建图层
self.layer = QgsLayerDefinition()
self.layer.setType(QgsMapLayerType.RasterLayer)
self.layer.setProviderType('gdal')
self.layer.setDataSource('path/to/your/raster/image')
QgsProject.instance().addMapLayer(self.layer)
# 创建地图画布
self.canvas = QgsMapCanvas()
self.canvas.setLayers([self.layer])
self.setCentralWidget(self.canvas)
# 创建图层树窗口
tree_widget = QWidget()
tree_layout = QVBoxLayout()
tree_widget.setLayout(tree_layout)
self.tree_view = QgsLayerTreeView()
tree_layout.addWidget(self.tree_view)
dock = QDockWidget()
dock.setWindowTitle('Layer Tree')
dock.setWidget(tree_widget)
self.addDockWidget(1, dock)
# 添加工具栏
toolbar = QToolBar()
self.addToolBar(toolbar)
# 创建图例并添加到工具栏
legend = self.canvas.layerTreeCanvasBridge().legendInterface()
toolbar.addWidget(legend)
# 更新界面
self.show()
self.tree_view.setCanvas(self.canvas)
```
阅读全文