本文整理汇总了Python中qgis.PyQt.QtCore.QCoreApplication.translate方法的典型用法代码示例。如果您正苦于以下问题:Python QCoreApplication.translate方法的具体用法?Python QCoreApplication.translate怎么用?Python QCoreApplication.translate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qgis.PyQt.QtCore.QCoreApplication
的用法示例。
在下文中一共展示了QCoreApplication.translate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: showSurvey
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def showSurvey(self):
#lyr = self.iface.activeLayer() # THIS IS TSPLOT-method, GETS THE SELECTED LAYER
lyr = self.layer
ids = lyr.selectedFeatureIds()
if len(ids) == 0:
utils.pop_up_info(ru(QCoreApplication.translate(' Stratigraphy', "No selection")), ru(QCoreApplication.translate(' Stratigraphy', "No features are selected")))
return
# initiate the datastore if not yet done
self.initStore()
utils.start_waiting_cursor() # Sets the mouse cursor to wait symbol
try: # return from store.getData is stored in data only if no object belonging to DataSanityError class is created
self.data = self.store.getData(ids, lyr) # added lyr as an argument!!!
except DataSanityError as e: # if an object 'e' belonging to DataSanityError is created, then do following
print("DataSanityError %s"%str(e))
utils.stop_waiting_cursor()
utils.pop_up_info(ru(QCoreApplication.translate(' Stratigraphy', "Data sanity problem, obsid: %s\n%s")) % (e.sond_id, e.message))
return
except Exception as e: # if an object 'e' belonging to DataSanityError is created, then do following
print("exception : %s"%str(e))
utils.stop_waiting_cursor()
utils.MessagebarAndLog.critical(bar_msg=ru(QCoreApplication.translate(' Stratigraphy', "The stratigraphy plot failed, check Midvatten plugin settings and your data!")))
return
utils.stop_waiting_cursor() # Restores the mouse cursor to normal symbol
# show widget
w = SurveyDialog()
#w.widget.setData2_nosorting(data) #THIS IS IF DATA IS NOT TO BE SORTED!!
w.widget.setData(self.data) #THIS IS ONLY TO SORT DATA!!
w.show()
self.w = w # save reference so it doesn't get deleted immediately This has to be done both here and also in midvatten instance
示例2: sanityCheck
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def sanityCheck(self, _surveys):
""" does a sanity check on retreived data """
surveys = {}
for (obsid, survey) in _surveys.items():
# check whether there's at least one strata information
if len(survey.strata) == 0:
#raise DataSanityError(str(obsid), "No strata information")
try:
print(str(obsid) + " has no strata information")
except:
pass
continue
#del surveys[obsid]#simply remove the item without strata info
else:
# check whether the depths are valid
top1 = survey.strata[0].depthTop
bed1 = survey.strata[0].depthBot
for strato in survey.strata[1:]:
# top (n) < top (n+1)
if top1 > strato.depthTop:
raise DataSanityError(str(obsid), ru(QCoreApplication.translate('SurveyStore', "Top depth is incorrect (%.2f > %.2f)")) % (top1, strato.depthTop))
# bed (n) < bed (n+1)
if bed1 > strato.depthBot:
raise DataSanityError(str(obsid), ru(QCoreApplication.translate('SurveyStore', "Bed depth is incorrect (%.2f > %.2f)")) % (bed1, strato.depthBot))
# bed (n) = top (n+1)
if bed1 != strato.depthTop:
raise DataSanityError(str(obsid), ru(QCoreApplication.translate('SurveyStore', "Top and bed depth don't match (%.2f != %.2f)")) % (bed1, strato.depthTop))
top1 = strato.depthTop
bed1 = strato.depthBot
surveys[obsid] = survey
return surveys
示例3: initAlgorithm
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def initAlgorithm(self, config=None):
class ParameterVrtDestination(QgsProcessingParameterRasterDestination):
def __init__(self, name, description):
super().__init__(name, description)
def clone(self):
copy = ParameterVrtDestination(self.name(), self.description())
return copy
def type(self):
return 'vrt_destination'
def defaultFileExtension(self):
return 'vrt'
self.addParameter(QgsProcessingParameterMultipleLayers(self.INPUT,
QCoreApplication.translate("ParameterVrtDestination", 'Input layers'),
QgsProcessing.TypeRaster))
self.addParameter(QgsProcessingParameterEnum(self.RESOLUTION,
QCoreApplication.translate("ParameterVrtDestination", 'Resolution'),
options=self.RESOLUTION_OPTIONS,
defaultValue=0))
self.addParameter(QgsProcessingParameterBoolean(self.SEPARATE,
QCoreApplication.translate("ParameterVrtDestination", 'Layer stack'),
defaultValue=True))
self.addParameter(QgsProcessingParameterBoolean(self.PROJ_DIFFERENCE,
QCoreApplication.translate("ParameterVrtDestination", 'Allow projection difference'),
defaultValue=False))
self.addParameter(ParameterVrtDestination(self.OUTPUT, QCoreApplication.translate("ParameterVrtDestination", 'Virtual')))
示例4: __init__
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def __init__(self, alg, in_place=False, parent=None):
super().__init__(parent)
self.feedback_dialog = None
self.in_place = in_place
self.active_layer = None
self.context = None
self.feedback = None
self.setAlgorithm(alg)
self.setMainWidget(self.getParametersPanel(alg, self))
if not self.in_place:
self.runAsBatchButton = QPushButton(QCoreApplication.translate("AlgorithmDialog", "Run as Batch Process…"))
self.runAsBatchButton.clicked.connect(self.runAsBatch)
self.buttonBox().addButton(self.runAsBatchButton, QDialogButtonBox.ResetRole) # reset role to ensure left alignment
else:
self.active_layer = iface.activeLayer()
self.runAsBatchButton = None
has_selection = self.active_layer and (self.active_layer.selectedFeatureCount() > 0)
self.buttonBox().button(QDialogButtonBox.Ok).setText(QCoreApplication.translate("AlgorithmDialog", "Modify Selected Features")
if has_selection else QCoreApplication.translate("AlgorithmDialog", "Modify All Features"))
self.buttonBox().button(QDialogButtonBox.Close).setText(QCoreApplication.translate("AlgorithmDialog", "Cancel"))
self.setWindowTitle(self.windowTitle() + ' | ' + self.active_layer.name())
示例5: restoreTimeLayers
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def restoreTimeLayers(self, layerInfos):
"""Restore all time layers"""
if layerInfos:
if len(layerInfos) > 0:
self.guiControl.enableAnimationExport()
for l in layerInfos: # for every layer entry
try:
settings = layer_settings.getSettingsFromSaveStr(l)
if settings.layer is None:
error_msg = QCoreApplication.translate('TimeManager', "Could not restore layer with id {} from saved project line {}").format(
settings.layerId, l
)
error(error_msg)
self.showMessage(error_msg)
continue
timeLayer = TimeLayerFactory.get_timelayer_class_from_settings(settings)(
settings, iface=self.iface)
except Exception as e:
layerId = "unknown"
try:
layerId = settings.layerId
except Exception:
pass
error_msg = QCoreApplication.translate('TimeManager', "An error occured while trying to restore layer {} to TimeManager. {}").format(
layerId, str(e)
)
error(error_msg + traceback.format_exc(e))
self.showMessage(error_msg)
continue
self.timeLayerManager.registerTimeLayer(timeLayer)
self.guiControl.refreshMapCanvas('restoreTimeLayer')
示例6: delete_selected_range
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def delete_selected_range(self, table_name):
""" Deletes the current selected range from the database from w_levels_logger
:return: De
"""
current_loaded_obsid = self.obsid
selected_obsid = self.load_obsid_and_init()
if current_loaded_obsid != selected_obsid:
utils.pop_up_info(ru(QCoreApplication.translate('Calibrlogger', "Error!\n The obsid selection has been changed but the plot has not been updated. No deletion done.\nUpdating plot.")))
self.update_plot()
return
elif selected_obsid is None:
utils.pop_up_info(ru(QCoreApplication.translate('Calibrlogger', "Error!\n No obsid was selected. No deletion done.\nUpdating plot.")))
self.update_plot()
return
fr_d_t = str((self.FromDateTime.dateTime().toPyDateTime() - datetime.datetime(1970,1,1)).total_seconds())
to_d_t = str((self.ToDateTime.dateTime().toPyDateTime() - datetime.datetime(1970,1,1)).total_seconds())
sql_list = []
sql_list.append(r"""DELETE FROM "%s" """%table_name)
sql_list.append(r"""WHERE obsid = '%s' """%selected_obsid)
# This %s is db formatting for seconds. It is not used as python formatting!
sql_list.append(r"""AND CAST(strftime('%s', date_time) AS NUMERIC) """)
sql_list.append(r""" > '%s' """%fr_d_t)
# This %s is db formatting for seconds. It is not used as python formatting!
sql_list.append(r"""AND CAST(strftime('%s', date_time) AS NUMERIC) """)
sql_list.append(r""" < '%s' """%to_d_t)
sql = ''.join(sql_list)
really_delete = utils.Askuser("YesNo", ru(QCoreApplication.translate('Calibrlogger', "Do you want to delete the period %s to %s for obsid %s from table %s?"))%(str(self.FromDateTime.dateTime().toPyDateTime()), str(self.ToDateTime.dateTime().toPyDateTime()), selected_obsid, table_name)).result
if really_delete:
utils.start_waiting_cursor()
db_utils.sql_alter_db(sql)
utils.stop_waiting_cursor()
self.update_plot()
示例7: update_settings
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def update_settings(self, _db_settings):
db_settings = None
if not _db_settings or _db_settings is None:
return
try:
db_settings = ast.literal_eval(_db_settings)
except:
utils.MessagebarAndLog.warning(log_msg=ru(QCoreApplication.translate('DatabaseSettings', 'Reading db_settings failed using string %s'))%_db_settings)
else:
pass
for setting in [db_settings, _db_settings]:
if isinstance(setting, str):
# Assume that the db_settings is an old spatialite database
if os.path.isfile(setting) and setting.endswith('.sqlite'):
db_settings = {'spatialite': {'dbpath': setting}}
break
if isinstance(db_settings, dict):
for dbtype, settings in db_settings.items():
self.dbtype_combobox = dbtype
self.choose_dbtype()
for setting_name, value in settings.items():
try:
if hasattr(self.db_settings_obj, str(setting_name)):
setattr(self.db_settings_obj, str(setting_name), value)
else:
utils.MessagebarAndLog.warning(log_msg=ru(QCoreApplication.translate('DatabaseSettings', "Databasetype %s didn' t have setting %s"))%(dbtype, setting_name))
except:
print(str(setting_name))
raise
else:
utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('DatabaseSettings', "Could not load database settings. Select database again!")), log_msg=ru(QCoreApplication.translate('DatabaseSettings', 'Tried to load db_settings string %s'))%_db_settings)
示例8: print_selected_features
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def print_selected_features(self):
""" Returns a list of obsid as unicode
thelayer is an optional argument, if not given then activelayer is used
"""
activelayer = utils.get_active_layer()
if activelayer is not self.activelayer:
self.reload_combobox()
utils.MessagebarAndLog.warning(
bar_msg=ru(QCoreApplication.translate('ValuesFromSelectedFeaturesGui', 'Column list reloaded. Select column and press Ok.')))
return None
self.selected_column = self.columns.currentText()
selected_values = utils.getselectedobjectnames(thelayer=self.activelayer, column_name=self.selected_column)
if not selected_values:
utils.MessagebarAndLog.info(bar_msg=ru(QCoreApplication.translate('ValuesFromSelectedFeaturesGui',
'No features selected!')))
else:
if self.unique_sorted_list_checkbox.isChecked():
selected_values = sorted(set(selected_values))
nr = len(selected_values)
utils.MessagebarAndLog.info(bar_msg=ru(
QCoreApplication.translate('ValuesFromSelectedFeaturesGui',
'List of %s selected %s written to log'))%(str(nr), self.selected_column),
log_msg='{} IN ({})'.format(self.selected_column,
', '.join(["'{}'".format(value) if value is not None else 'NULL'
for value in selected_values])))
self.close()
示例9: removeDir
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def removeDir(path):
result = ""
if not QFile(path).exists():
result = QCoreApplication.translate("QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path
elif QFile(path).remove(): # if it is only link, just remove it without resolving.
pass
else:
fltr = QDir.Dirs | QDir.Files | QDir.Hidden
iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
while iterator.hasNext():
item = iterator.next()
if QFile(item).remove():
pass
fltr = QDir.Dirs | QDir.Hidden
iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
while iterator.hasNext():
item = iterator.next()
if QDir().rmpath(item):
pass
if QFile(path).exists():
result = QCoreApplication.translate("QgsPluginInstaller", "Failed to remove the directory:") + "\n" + path + "\n" + QCoreApplication.translate("QgsPluginInstaller", "Check permissions or remove it manually")
# restore plugin directory if removed by QDir().rmpath()
pluginDir = qgis.utils.home_plugin_path
if not QDir(pluginDir).exists():
QDir().mkpath(pluginDir)
return result
示例10: initGui
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def initGui(self):
"""startup"""
# run
run_icon = QIcon('%s/%s' % (self.context.ppath,
'images/MetaSearch.png'))
self.action_run = QAction(run_icon, 'MetaSearch',
self.iface.mainWindow())
self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch',
'MetaSearch plugin'))
self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch',
'Search Metadata Catalogs'))
self.action_run.triggered.connect(self.run)
self.iface.addWebToolBarIcon(self.action_run)
self.iface.addPluginToWebMenu(self.web_menu, self.action_run)
# help
help_icon = QgsApplication.getThemeIcon('/mActionHelpContents.svg')
self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow())
self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch',
'MetaSearch plugin help'))
self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch',
'Get Help on MetaSearch'))
self.action_help.triggered.connect(self.help)
self.iface.addPluginToWebMenu(self.web_menu, self.action_help)
# prefab the dialog but not open it yet
self.dialog = MetaSearchDialog(self.iface)
示例11: createMenu
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def createMenu(self):
self.menu.clear()
self.menu.setMinimumWidth(self.width())
fill_down_action = QAction(self.tr('Fill Down'), self.menu)
fill_down_action.triggered.connect(self.fillDown)
fill_down_action.setToolTip(self.tr('Copy the first value down to all other rows'))
self.menu.addAction(fill_down_action)
calculate_by_expression = QAction(QCoreApplication.translate('BatchPanel', 'Calculate by Expression…'),
self.menu)
calculate_by_expression.setIcon(QgsApplication.getThemeIcon('/mActionCalculateField.svg'))
calculate_by_expression.triggered.connect(self.calculateByExpression)
calculate_by_expression.setToolTip(self.tr('Calculates parameter values by evaluating an expression'))
self.menu.addAction(calculate_by_expression)
add_by_expression = QAction(QCoreApplication.translate('BatchPanel', 'Add Values by Expression…'),
self.menu)
add_by_expression.triggered.connect(self.addByExpression)
add_by_expression.setToolTip(self.tr('Adds new parameter values by evaluating an expression'))
self.menu.addAction(add_by_expression)
if isinstance(self.parameterDefinition, (QgsProcessingParameterFile,
QgsProcessingParameterMapLayer,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterMeshLayer,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterFeatureSource)):
self.menu.addSeparator()
find_by_pattern_action = QAction(QCoreApplication.translate('BatchPanel', 'Add Files by Pattern…'),
self.menu)
find_by_pattern_action.triggered.connect(self.addFilesByPattern)
find_by_pattern_action.setToolTip(self.tr('Adds files by a file pattern match'))
self.menu.addAction(find_by_pattern_action)
示例12: startServerPlugin
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def startServerPlugin(packageName):
""" initialize the plugin """
global server_plugins, server_active_plugins, serverIface
if packageName in server_active_plugins:
return False
if packageName not in sys.modules:
return False
package = sys.modules[packageName]
errMsg = QCoreApplication.translate("Python", "Couldn't load server plugin %s") % packageName
# create an instance of the plugin
try:
server_plugins[packageName] = package.serverClassFactory(serverIface)
except:
_unloadPluginModules(packageName)
msg = QCoreApplication.translate("Python",
"%s due to an error when calling its serverClassFactory() method") % errMsg
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg)
return False
# add to active plugins
server_active_plugins.append(packageName)
return True
示例13: show
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def show(self):
QDialog.show(self)
self.setWindowModality(0)
if self.firstShow:
inet = internet_on(proxyUrl=self.proxy, timeout=self.timeout)
#filters
if inet:
self.poiThemes = dict( self.poi.listPoiThemes() )
poiThemes = [""] + list(self.poiThemes.keys())
poiThemes.sort()
self.ui.filterPoiThemeCombo.addItems( poiThemes )
self.poiCategories = dict( self.poi.listPoiCategories() )
poiCategories = [""] + list(self.poiCategories.keys())
poiCategories.sort()
self.ui.filterPoiCategoryCombo.addItems( poiCategories )
self.poiTypes = dict( self.poi.listPoitypes() )
poiTypes = [""] + list(self.poiTypes.keys())
poiTypes.sort()
self.ui.filterPoiTypeCombo.addItems( poiTypes )
gemeentes = json.load( open(os.path.join(os.path.dirname(__file__), "data/gemeentenVL.json")) )
self.NIScodes= { n["Naam"] : n["Niscode"] for n in gemeentes }
gemeenteNamen = [n["Naam"] for n in gemeentes]
gemeenteNamen.sort()
self.ui.filterPoiNIS.addItems( gemeenteNamen )
#connect when inet on
self.ui.filterPoiThemeCombo.activated.connect(self.onThemeFilterChange)
self.ui.filterPoiCategoryCombo.activated.connect(self.onCategorieFilterChange)
self.firstShow = False
else:
self.bar.pushMessage(
QCoreApplication.translate("geopunt4QgisPoidialog", "Waarschuwing "),
QCoreApplication.translate("geopunt4QgisPoidialog", "Kan geen verbing maken met het internet."),
level=Qgis.Warning, duration=3)
示例14: selectExtent
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def selectExtent(self):
popupmenu = QMenu()
useCanvasExtentAction = QAction(
QCoreApplication.translate("ExtentSelectionPanel", 'Use Canvas Extent'),
self.btnSelect)
useLayerExtentAction = QAction(
QCoreApplication.translate("ExtentSelectionPanel", 'Use Layer Extent…'),
self.btnSelect)
selectOnCanvasAction = QAction(
self.tr('Select Extent on Canvas'), self.btnSelect)
popupmenu.addAction(useCanvasExtentAction)
popupmenu.addAction(selectOnCanvasAction)
popupmenu.addSeparator()
popupmenu.addAction(useLayerExtentAction)
selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
useLayerExtentAction.triggered.connect(self.useLayerExtent)
useCanvasExtentAction.triggered.connect(self.useCanvasExtent)
if self.param.flags() & QgsProcessingParameterDefinition.FlagOptional:
useMincoveringExtentAction = QAction(
self.tr('Use Min Covering Extent from Input Layers'),
self.btnSelect)
useMincoveringExtentAction.triggered.connect(
self.useMinCoveringExtent)
popupmenu.addAction(useMincoveringExtentAction)
popupmenu.exec_(QCursor.pos())
示例15: showPopupMenu
# 需要导入模块: from qgis.PyQt.QtCore import QCoreApplication [as 别名]
# 或者: from qgis.PyQt.QtCore.QCoreApplication import translate [as 别名]
def showPopupMenu(self, point):
item = self.algorithmTree.itemAt(point)
popupmenu = QMenu()
if isinstance(item, TreeAlgorithmItem):
alg = item.alg
executeAction = QAction(QCoreApplication.translate('ProcessingToolbox', 'Execute…'), self.algorithmTree)
executeAction.triggered.connect(self.executeAlgorithm)
popupmenu.addAction(executeAction)
if alg.flags() & QgsProcessingAlgorithm.FlagSupportsBatch:
executeBatchAction = QAction(
QCoreApplication.translate('ProcessingToolbox', 'Execute as Batch Process…'),
self.algorithmTree)
executeBatchAction.triggered.connect(
self.executeAlgorithmAsBatchProcess)
popupmenu.addAction(executeBatchAction)
popupmenu.addSeparator()
editRenderingStylesAction = QAction(
QCoreApplication.translate('ProcessingToolbox', 'Edit Rendering Styles for Outputs…'),
self.algorithmTree)
editRenderingStylesAction.triggered.connect(
self.editRenderingStyles)
popupmenu.addAction(editRenderingStylesAction)
actions = ProviderContextMenuActions.actions
if len(actions) > 0:
popupmenu.addSeparator()
for action in actions:
action.setData(item.alg, self)
if action.isEnabled():
contextMenuAction = QAction(action.name,
self.algorithmTree)
contextMenuAction.triggered.connect(action.execute)
popupmenu.addAction(contextMenuAction)
popupmenu.exec_(self.algorithmTree.mapToGlobal(point))