文件选择
选中本地文件方法,在根目录创建utils
包,包内创建fileUtil.py
,内容如下:
该方法会根据last_dir_key
记录本次打开的目录,每次选择会打开上次的目录
fileUtil.pyimport os
from PyQt5.QtCore import QSettings, QDir from PyQt5.QtWidgets import QFileDialog
def select_single_file(weight, suffix_filter: str, last_dir_key: str): """ 打开单个文件 :param weight: :param suffix_filter: :param last_dir_key: :return: """ settings = QSettings('PyQgisSEAPP') last_dir = settings.value(last_dir_key, QDir().homePath())
file_dialog = QFileDialog(weight) file_dialog.setWindowTitle('文件选择') file_dialog.setNameFilter(suffix_filter) file_dialog.setDirectory(last_dir) file_dialog.setFileMode(QFileDialog.FileMode.ExistingFile) file_dialog.setViewMode(QFileDialog.ViewMode.Detail)
if file_dialog.exec(): filenames = file_dialog.selectedFiles() filepath = filenames[0] settings.setValue(last_dir_key, os.path.dirname(filepath)) return filepath
return ''
|
打开栅格数据
在preview
目录创建functions
包,并在包内创建btn_func.py
,添加栅格数据代码如下:
btn_func.pyfrom os.path import basename
from qgis._core import QgsRasterLayer, QgsProject from qgis._gui import QgsMapCanvas
import utils.fileUtil as FileUtil
def open_raster_file(main): """ 打开栅格文件 :param main: :return: """ filepath = FileUtil.select_single_file(main, 'GeoTiff(*.tif;*tiff;*TIF;*TIFF)', 'last_dir_raster') if filepath == '': return
canvas: QgsMapCanvas = main.preview_canvas layer: QgsRasterLayer = QgsRasterLayer(filepath, basename(filepath), 'gdal') layer.dataProvider().setNoDataValue(1, 0) if not layer.isValid(): return False QgsProject.instance().addMapLayer(layer) is_first_add_layer = len(canvas.layers()) == 0 canvas.setLayers([layer] + canvas.layers()) if is_first_add_layer: canvas.setExtent(layer.extent()) canvas.setDestinationCrs(layer.crs()) canvas.freeze(False) canvas.setVisible(True) canvas.refresh()
|
绑定方法,回到preview.py
,给按钮绑定方法
preview.pyfrom gui.preview.functions import open_raster_file
def bind_func(main): _ui = main.ui _ui.button_add_raster.clicked.connect(lambda self: open_raster_file(main))
|
运行效果如下:
示例数据下载地址: