在preview
目录创建functions
包,并在包内创建btn_func.py
,添加矢量数据代码如下:
btn_func.pyfrom os.path import basename
from PyQt5.QtGui import QFont, QColor from osgeo import gdal from qgis._core import QgsRasterLayer, QgsProject, QgsVectorLayer, QgsPalLayerSettings, QgsTextFormat, Qgis, \ QgsVectorLayerSimpleLabeling from qgis._gui import QgsMapCanvas
import utils.fileUtil as FileUtil
def open_shp_file(main): filepath = FileUtil.select_single_file(main, '等深线数据(*.shp)', 'last_dir_contour_shp') if filepath == '' or not filepath.endswith('.shp'): return
gdal.SetConfigOption('SHAPE_RESTORE_SHX', 'YES') layer = QgsVectorLayer(filepath, basename(filepath), 'ogr')
if not layer.isValid(): return False
layer_setting = QgsPalLayerSettings() layer_setting.drawLabels = True layer_setting.fieldName = layer.fields()[1].name()
text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setColor(QColor(255, 255, 255)) layer_setting.setFormat(text_format) layer_setting.placement = Qgis.LabelPlacement.Line layer_setting.placementFlags = QgsPalLayerSettings.AboveLine
layer.setLabelsEnabled(True) layer.setLabeling(QgsVectorLayerSimpleLabeling(layer_setting)) layer.triggerRepaint(True)
canvas: QgsMapCanvas = main.preview_canvas QgsProject.instance().addMapLayer(layer) canvas.setLayers([layer] + canvas.layers()) canvas.setDestinationCrs(layer.crs()) canvas.setExtent(layer.extent()) canvas.refresh()
|
绑定方法,回到preview.py
,给按钮绑定方法
preview.pyfrom gui.preview.functions import open_raster_file, open_shp_file
def bind_func(main): _ui = main.ui _ui.button_add_raster.clicked.connect(lambda self: open_raster_file(main)) _ui.button_add_shp.clicked.connect(lambda self: open_shp_file(main))
|
运行效果如下:
示例数据下载地址: