本文整理汇总了Python中safe.utilities.keyword_io.KeywordIO.read_keywords方法的典型用法代码示例。如果您正苦于以下问题:Python KeywordIO.read_keywords方法的具体用法?Python KeywordIO.read_keywords怎么用?Python KeywordIO.read_keywords使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类safe.utilities.keyword_io.KeywordIO
的用法示例。
在下文中一共展示了KeywordIO.read_keywords方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_issue1191
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def test_issue1191(self):
"""Test setting a layer's title in the kw directly from qgis api"""
settings = QtCore.QSettings()
settings.setValue(
'inasafe/analysis_extents_mode', 'HazardExposure')
self.dock.set_layer_from_title_flag = True
set_canvas_crs(GEOCRS, True)
set_yogya_extent(self.dock)
result, message = setup_scenario(
self.dock,
hazard='Earthquake',
exposure='Buildings',
function='Be affected',
function_id='EarthquakeBuildingFunction')
self.assertTrue(result, message)
layer = self.dock.get_hazard_layer()
keyword_io = KeywordIO()
original_title = 'Earthquake'
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
# change layer name as if done in the legend
expected_title = 'TEST'
layer.setLayerName(expected_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, expected_title)
# reset KW file to original state
layer.setLayerName(original_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
self.dock.set_layer_from_title_flag = False
示例2: test_issue1191
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def test_issue1191(self):
"""Test setting a layer's title in the kw directly from qgis api"""
DOCK.set_layer_from_title_flag = True
set_canvas_crs(GEOCRS, True)
set_yogya_extent(DOCK)
result, message = setup_scenario(
DOCK,
hazard='An earthquake in Yogyakarta like in 2006',
exposure='OSM Building Polygons',
function='Be affected',
function_id='Earthquake Building Impact Function')
self.assertTrue(result, message)
layer = DOCK.get_hazard_layer()
keyword_io = KeywordIO()
original_title = 'An earthquake in Yogyakarta like in 2006'
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
# change layer name as if done in the legend
expected_title = 'TEST'
layer.setLayerName(expected_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, expected_title)
# reset KW file to original state
layer.setLayerName(original_title)
title = keyword_io.read_keywords(layer, 'title')
self.assertEqual(title, original_title)
DOCK.set_layer_from_title_flag = False
示例3: show_keywords_editor
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def show_keywords_editor(self):
"""Show the keywords editor."""
# import here only so that it is AFTER i18n set up
from safe.gui.tools.keywords_dialog import KeywordsDialog
# Next block is a fix for #776
if self.iface.activeLayer() is None:
return
try:
keyword_io = KeywordIO()
keyword_io.read_keywords(self.iface.activeLayer())
except UnsupportedProviderError:
# noinspection PyUnresolvedReferences,PyCallByClass
# noinspection PyTypeChecker,PyArgumentList
QMessageBox.warning(
None,
self.tr("Unsupported layer type"),
self.tr(
"The layer you have selected cannot be used for " "analysis because its data type is unsupported."
),
)
return
# End of fix for #776
# Fix for #793
except NoKeywordsFoundError:
# we will create them from scratch in the dialog
pass
# End of fix for #793
# Fix for filtered-layer
except InvalidParameterError, e:
# noinspection PyTypeChecker,PyTypeChecker,PyArgumentList
QMessageBox.warning(None, self.tr("Invalid Layer"), e.message)
return
示例4: analysis_execution
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def analysis_execution():
from safe.test.utilities import get_qgis_app
# get_qgis_app must be called before importing Analysis
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()
from safe.utilities.analysis import Analysis
from safe.utilities.keyword_io import KeywordIO
analysis = Analysis()
arg = AnalysisArguments.read_arguments()
register_impact_functions()
registry = ImpactFunctionManager().registry
function = registry.get_instance(arg.impact_function_name)
hazard_layer = safe_to_qgis_layer(read_layer(arg.hazard_filename))
exposure_layer = safe_to_qgis_layer(read_layer(arg.exposure_filename))
if arg.aggregation_filename:
aggregation_layer = safe_to_qgis_layer(read_layer(
arg.aggregation_filename))
keywords_io = KeywordIO()
try:
analysis.map_canvas = IFACE.mapCanvas()
analysis.hazard_layer = hazard_layer
analysis.hazard_keyword = keywords_io.read_keywords(hazard_layer)
analysis.exposure_layer = exposure_layer
analysis.exposure_keyword = keywords_io.read_keywords(exposure_layer)
if aggregation_layer:
analysis.aggregation_layer = aggregation_layer
analysis.aggregation_keyword = keywords_io.read_keywords(
aggregation_layer)
analysis.impact_function = function
analysis.setup_analysis()
print 'Setup analysis done'
analysis.run_analysis()
print 'Analysis done'
except Exception as e:
print e.message
impact = analysis.impact_layer
qgis_impact = safe_to_qgis_layer(impact)
generate_styles(impact, qgis_impact)
copy_impact_layer(impact, arg.impact_filename)
示例5: hazard_extra_keyword
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def hazard_extra_keyword(keyword, feature, parent):
"""Given a keyword, it will return the value of the keyword
from the hazard layer's extra keywords.
For instance:
* hazard_extra_keyword( 'depth' ) -> will return the value of 'depth'
in current hazard layer's extra keywords.
"""
_ = feature, parent # NOQA
hazard_layer_path = QgsExpressionContextUtils. \
projectScope(QgsProject.instance()).variable(
'hazard_layer')
hazard_layer = load_layer(hazard_layer_path)[0]
keywords = KeywordIO.read_keywords(hazard_layer)
extra_keywords = keywords.get('extra_keywords')
if extra_keywords:
value = extra_keywords.get(keyword)
if value:
value_definition = definition(value)
if value_definition:
return value_definition['name']
return value
else:
return tr('Keyword %s is not found' % keyword)
return tr('No extra keywords found')
示例6: get_impact_function_list
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def get_impact_function_list(arguments):
"""Returns all available impact function ids.
.. versionadded:: 3.2
:returns: List of impact functions.
:rtype: list
"""
LOGGER.debug("get IF list")
manager = ImpactFunctionManager()
if arguments.hazard and arguments.exposure:
hazard = get_hazard(arguments)
exposure = get_exposure(arguments)
keyword_io = KeywordIO()
hazard_keyword = keyword_io.read_keywords(hazard)
exposure_keyword = keyword_io.read_keywords(exposure)
ifs = manager.filter_by_keywords(hazard_keyword, exposure_keyword)
else:
ifs = manager.filter()
LOGGER.debug(ifs)
return ifs
示例7: exposure_summary_layer
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def exposure_summary_layer():
"""Helper method for retrieving exposure summary layer.
If the analysis is multi-exposure, then it will return the exposure
summary layer from place exposure analysis.
"""
project_context_scope = QgsExpressionContextUtils.projectScope(
QgsProject.instance())
project = QgsProject.instance()
key = provenance_layer_analysis_impacted_id['provenance_key']
analysis_summary_layer = project.mapLayer(
project_context_scope.variable(key))
if not analysis_summary_layer:
key = provenance_layer_analysis_impacted['provenance_key']
if project_context_scope.hasVariable(key):
analysis_summary_layer = load_layer(
project_context_scope.variable(key))[0]
if not analysis_summary_layer:
return None
keywords = KeywordIO.read_keywords(analysis_summary_layer)
extra_keywords = keywords.get(property_extra_keywords['key'], {})
is_multi_exposure = extra_keywords.get(extra_keyword_analysis_type['key'])
key = provenance_layer_exposure_summary_id['provenance_key']
if is_multi_exposure:
key = ('{provenance}__{exposure}').format(
provenance=provenance_multi_exposure_summary_layers_id[
'provenance_key'],
exposure=exposure_place['key'])
if not project_context_scope.hasVariable(key):
return None
exposure_summary_layer = project.mapLayer(
project_context_scope.variable(key))
if not exposure_summary_layer:
key = provenance_layer_exposure_summary['provenance_key']
if is_multi_exposure:
key = ('{provenance}__{exposure}').format(
provenance=provenance_multi_exposure_summary_layers[
'provenance_key'],
exposure=exposure_place['key'])
if project_context_scope.hasVariable(key):
exposure_summary_layer = load_layer(
project_context_scope.variable(key))[0]
else:
return None
return exposure_summary_layer
示例8: monkey_patch_keywords
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def monkey_patch_keywords(layer):
"""In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer
"""
keyword_io = KeywordIO()
try:
layer.keywords = keyword_io.read_keywords(layer)
except (NoKeywordsFoundError, MetadataReadError):
layer.keywords = {}
if not layer.keywords.get('inasafe_fields'):
layer.keywords['inasafe_fields'] = {}
if not layer.keywords.get('layer_purpose'):
layer.keywords['layer_purpose'] = 'undefined'
示例9: monkey_patch_keywords
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def monkey_patch_keywords(layer):
"""In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer
"""
keyword_io = KeywordIO()
try:
layer.keywords = keyword_io.read_keywords(layer)
except (NoKeywordsFoundError, MetadataReadError):
layer.keywords = {}
try:
layer.keywords['inasafe_fields']
except KeyError:
layer.keywords['inasafe_fields'] = {}
示例10: QgisWrapper
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class QgisWrapper():
"""Wrapper class to add keywords functionality to Qgis layers
"""
def __init__(self, layer, name=None):
"""Create the wrapper
:param layer: Qgis layer
:type layer: QgsMapLayer
:param name: A layer's name
:type name: Basestring or None
"""
self.data = layer
self.keyword_io = KeywordIO()
self.keywords = self.keyword_io.read_keywords(layer)
if name is None:
try:
self.name = self.get_keywords(key='title')
except KeywordNotFoundError:
pass
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_keywords(self, key=None):
"""Return a copy of the keywords dictionary
Args:
* key (optional): If specified value will be returned for key only
"""
if key is None:
return self.keywords.copy()
else:
if key in self.keywords:
return self.keywords[key]
else:
msg = ('Keyword %s does not exist in %s: Options are '
'%s' % (key, self.get_name(), self.keywords.keys()))
raise KeywordNotFoundError(msg)
def get_layer(self):
return self.data
示例11: test_clip_vector_with_unicode
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
def test_clip_vector_with_unicode(self):
"""Test clipping vector layer with unicode attribute in feature.
This issue is described at Github #2262 and #2233
TODO: FIXME:
This is a hacky fix. See above ticket for further explanation.
To fix this, we should be able to specify UTF-8 encoding for
QgsVectorFileWriter
"""
# this layer contains unicode values in the
layer_path = standard_data_path(
'boundaries', 'district_osm_jakarta.shp')
vector_layer = QgsVectorLayer(layer_path, 'District Jakarta', 'ogr')
keyword_io = KeywordIO()
aggregation_keyword = get_defaults()['AGGR_ATTR_KEY']
aggregation_attribute = keyword_io.read_keywords(
vector_layer, keyword=aggregation_keyword)
source_extent = vector_layer.extent()
extent = [source_extent.xMinimum(), source_extent.yMinimum(),
source_extent.xMaximum(), source_extent.yMaximum()]
clipped_layer = clip_layer(
layer=vector_layer,
extent=extent,
explode_flag=True,
explode_attribute=aggregation_attribute)
# cross check vector layer attribute in clipped layer
vector_values = []
for f in vector_layer.getFeatures():
vector_values.append(f.attributes())
clipped_values = []
for f in clipped_layer.getFeatures():
clipped_values.append(f.attributes())
for val in clipped_values:
self.assertIn(val, vector_values)
示例12: FieldMappingWidget
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class FieldMappingWidget(QTabWidget, object):
"""Field Mapping Widget."""
def __init__(self, parent=None, iface=None):
"""Constructor."""
super(FieldMappingWidget, self).__init__(parent)
# Attributes
self.parent = parent
self.iface = iface
self.layer = None
self.metadata = {}
self.tabs = [] # Store all tabs
self.keyword_io = KeywordIO()
def set_layer(self, layer, keywords=None):
"""Set layer and update UI accordingly.
:param layer: A vector layer that has been already patched with
metadata.
:type layer: QgsVectorLayer
:param keywords: Custom keyword for the layer.
:type keywords: dict, None
"""
self.layer = layer
if keywords is not None:
self.metadata = keywords
else:
self.metadata = self.keyword_io.read_keywords(self.layer)
self.populate_tabs()
def populate_tabs(self):
"""Populating tabs based on layer metadata."""
self.delete_tabs()
layer_purpose = self.metadata.get('layer_purpose')
if not layer_purpose:
message = tr(
'Key layer_purpose is not found in the layer {layer_name}'
).format(layer_name=self.layer.name())
raise KeywordNotFoundError(message)
if layer_purpose == layer_purpose_exposure['key']:
layer_subcategory = self.metadata.get('exposure')
elif layer_purpose == layer_purpose_hazard['key']:
layer_subcategory = self.metadata.get('hazard')
else:
layer_subcategory = None
field_groups = get_field_groups(layer_purpose, layer_subcategory)
for field_group in field_groups:
tab = FieldMappingTab(field_group, self, self.iface)
tab.set_layer(self.layer, self.metadata)
self.addTab(tab, field_group['name'])
self.tabs.append(tab)
def delete_tabs(self):
"""Methods to delete tabs."""
self.clear()
self.tabs = []
def get_field_mapping(self):
"""Obtain metadata from current state of the widget.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
fields = {}
values = {}
for tab in self.tabs:
parameter_values = tab.get_parameter_value()
fields.update(parameter_values['fields'])
values.update(parameter_values['values'])
return {
'fields': fields,
'values': values
}
示例13: MetadataConverterDialog
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class MetadataConverterDialog(QDialog, FORM_CLASS):
"""Dialog implementation class for the InaSAFE metadata converter tool."""
resized = pyqtSignal()
def __init__(self, parent=None, iface=None):
"""Constructor."""
QDialog.__init__(self, parent)
self.setupUi(self)
icon = resources_path('img', 'icons', 'show-metadata-converter.svg')
self.setWindowIcon(QIcon(icon))
self.setWindowTitle(self.tr('InaSAFE Metadata Converter'))
self.parent = parent
self.iface = iface
self.keyword_io = KeywordIO()
self.layer = None
# Setup header label
self.header_label.setText(tr(
'In this tool, you can convert a metadata 4.x of a layer to '
'metadata 3.5. You will get a directory contains all the files of '
'the layer and the new 3.5 metadata. If you want to convert '
'hazard layer, you need to choose what exposure that you want to '
'work with.')
)
# Setup input layer combo box
# Filter our layers
excepted_layers = []
for i in range(self.input_layer_combo_box.count()):
layer = self.input_layer_combo_box.layer(i)
try:
keywords = self.keyword_io.read_keywords(layer)
except (KeywordNotFoundError, NoKeywordsFoundError):
# Filter out if no keywords
excepted_layers.append(layer)
continue
layer_purpose = keywords.get('layer_purpose')
if not layer_purpose:
# Filter out if no layer purpose
excepted_layers.append(layer)
continue
if layer_purpose not in accepted_layer_purposes:
# Filter out if not aggregation, hazard, or exposure layer
excepted_layers.append(layer)
continue
keyword_version = keywords.get('keyword_version')
if not keyword_version:
# Filter out if no keyword version
excepted_layers.append(layer)
continue
if not is_keyword_version_supported(keyword_version):
# Filter out if the version is not supported (4.x)
excepted_layers.append(layer)
continue
self.input_layer_combo_box.setExceptedLayerList(excepted_layers)
# Select the active layer.
if self.iface.activeLayer():
found = self.input_layer_combo_box.findText(
self.iface.activeLayer().name())
if found > -1:
self.input_layer_combo_box.setLayer(self.iface.activeLayer())
# Set current layer as the active layer
if self.input_layer_combo_box.currentLayer():
self.set_layer(self.input_layer_combo_box.currentLayer())
# Signals
self.input_layer_combo_box.layerChanged.connect(self.set_layer)
self.output_path_tool.clicked.connect(self.select_output_directory)
# Set widget to show the main page (not help page)
self.main_stacked_widget.setCurrentIndex(1)
# Set up things for context help
self.help_button = self.button_box.button(QDialogButtonBox.Help)
# Allow toggling the help button
self.help_button.setCheckable(True)
self.help_button.toggled.connect(self.help_toggled)
# Set up things for ok button
self.ok_button = self.button_box.button(QDialogButtonBox.Ok)
self.ok_button.clicked.connect(self.accept)
# Set up things for cancel button
self.cancel_button = self.button_box.button(QDialogButtonBox.Cancel)
self.cancel_button.clicked.connect(self.reject)
# The bug is fixed in QT 5.4
if QT_VERSION < 0x050400:
self.resized.connect(self.after_resize)
def set_layer(self, layer=None):
"""Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
#.........这里部分代码省略.........
示例14: SaveScenarioDialog
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
#.........这里部分代码省略.........
return is_valid, warning_message
def save_scenario(self, scenario_file_path=None):
"""Save current scenario to a text file.
You can use the saved scenario with the batch runner.
:param scenario_file_path: A path to the scenario file.
:type scenario_file_path: str
"""
# Validate Input
warning_title = self.tr('InaSAFE Save Scenario Warning')
is_valid, warning_message = self.validate_input()
if not is_valid:
# noinspection PyCallByClass,PyTypeChecker,PyArgumentList
QtGui.QMessageBox.warning(self, warning_title, warning_message)
return
# Make extent to look like:
# 109.829170982, -8.13333290561, 111.005344795, -7.49226294379
# Added in 2.2 to support user defined analysis extents
if self.dock.extent.user_extent is not None \
and self.dock.extent.user_extent_crs is not None:
extent = extent_to_array(
self.dock.extent.user_extent,
self.dock.extent.user_extent_crs)
else:
extent = viewport_geo_array(self.iface.mapCanvas())
extent_string = ', '.join(('%f' % x) for x in extent)
exposure_path = self.exposure_layer.publicSource()
hazard_path = self.hazard_layer.publicSource()
title = self.keyword_io.read_keywords(self.hazard_layer, 'title')
title = self.tr(title)
default_filename = title.replace(
' ', '_').replace('(', '').replace(')', '')
# Popup a dialog to request the filename if scenario_file_path = None
dialog_title = self.tr('Save Scenario')
if scenario_file_path is None:
# noinspection PyCallByClass,PyTypeChecker
scenario_file_path = QFileDialog.getSaveFileName(
self,
dialog_title,
os.path.join(self.output_directory, default_filename + '.txt'),
"Text files (*.txt)")
if scenario_file_path is None or scenario_file_path == '':
return
self.output_directory = os.path.dirname(scenario_file_path)
# Get relative path for each layer
relative_exposure_path = self.relative_path(
scenario_file_path, exposure_path)
relative_hazard_path = self.relative_path(
scenario_file_path, hazard_path)
# Write to file
parser = ConfigParser()
parser.add_section(title)
parser.set(title, 'exposure', relative_exposure_path)
parser.set(title, 'hazard', relative_hazard_path)
parser.set(title, 'function', self.function_id)
parser.set(title, 'extent', extent_string)
if self.dock.extent.user_extent_crs is None:
parser.set(title, 'extent_crs',
示例15: FieldMappingDialog
# 需要导入模块: from safe.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class FieldMappingDialog(QDialog, FORM_CLASS):
"""Dialog implementation class for the InaSAFE field mapping tool."""
def __init__(self, parent=None, iface=None, setting=None):
"""Constructor."""
QDialog.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle(self.tr('InaSAFE Field Mapping Tool'))
icon = resources_path('img', 'icons', 'show-mapping-tool.svg')
self.setWindowIcon(QIcon(icon))
self.parent = parent
self.iface = iface
if setting is None:
setting = QSettings()
self.setting = setting
self.keyword_io = KeywordIO()
self.layer = None
self.metadata = {}
self.layer_input_layout = QHBoxLayout()
self.layer_label = QLabel(tr('Layer'))
self.layer_combo_box = QgsMapLayerComboBox()
# Filter only for Polygon and Point
self.layer_combo_box.setFilters(
QgsMapLayerProxyModel.PolygonLayer
| QgsMapLayerProxyModel.PointLayer)
# Filter out a layer that don't have layer groups
excepted_layers = []
for i in range(self.layer_combo_box.count()):
layer = self.layer_combo_box.layer(i)
try:
keywords = self.keyword_io.read_keywords(layer)
except (KeywordNotFoundError, NoKeywordsFoundError):
excepted_layers.append(layer)
continue
layer_purpose = keywords.get('layer_purpose')
if not layer_purpose:
excepted_layers.append(layer)
continue
if layer_purpose == layer_purpose_exposure['key']:
layer_subcategory = keywords.get('exposure')
elif layer_purpose == layer_purpose_hazard['key']:
layer_subcategory = keywords.get('hazard')
else:
layer_subcategory = None
field_groups = get_field_groups(layer_purpose, layer_subcategory)
if len(field_groups) == 0:
excepted_layers.append(layer)
continue
self.layer_combo_box.setExceptedLayerList(excepted_layers)
# Select the active layer.
if self.iface.activeLayer():
found = self.layer_combo_box.findText(
self.iface.activeLayer().name())
if found > -1:
self.layer_combo_box.setLayer(self.iface.activeLayer())
self.field_mapping_widget = None
self.main_stacked_widget.setCurrentIndex(1)
# Input
self.layer_input_layout.addWidget(self.layer_label)
self.layer_input_layout.addWidget(self.layer_combo_box)
self.header_label = QLabel()
self.header_label.setWordWrap(True)
self.main_layout.addWidget(self.header_label)
self.main_layout.addLayout(self.layer_input_layout)
# Signal
self.layer_combo_box.layerChanged.connect(self.set_layer)
if self.layer_combo_box.currentLayer():
self.set_layer(self.layer_combo_box.currentLayer())
# Set up things for context help
self.help_button = self.button_box.button(QDialogButtonBox.Help)
# Allow toggling the help button
self.help_button.setCheckable(True)
self.help_button.toggled.connect(self.help_toggled)
# Set up things for ok button
self.ok_button = self.button_box.button(QDialogButtonBox.Ok)
self.ok_button.clicked.connect(self.accept)
# Set up things for cancel button
self.cancel_button = self.button_box.button(QDialogButtonBox.Cancel)
self.cancel_button.clicked.connect(self.reject)
def set_layer(self, layer=None, keywords=None):
"""Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
#.........这里部分代码省略.........