本文整理汇总了Python中qgis.core.QgsApplication.instance方法的典型用法代码示例。如果您正苦于以下问题:Python QgsApplication.instance方法的具体用法?Python QgsApplication.instance怎么用?Python QgsApplication.instance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qgis.core.QgsApplication
的用法示例。
在下文中一共展示了QgsApplication.instance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_app
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def start_app(cleanup=True):
"""
Will start a QgsApplication and call all initialization code like
registering the providers and other infrastructure. It will not load
any plugins.
You can always get the reference to a running app by calling `QgsApplication.instance()`.
The initialization will only happen once, so it is safe to call this method repeatedly.
Parameters
----------
cleanup: Do cleanup on exit. Defaults to true.
Returns
-------
QgsApplication
A QgsApplication singleton
"""
global QGISAPP
try:
QGISAPP
except NameError:
myGuiFlag = True # All test will run qgis in gui mode
try:
sys.argv
except:
sys.argv = ['']
# In python3 we need to convert to a bytes object (or should
# QgsApplication accept a QString instead of const char* ?)
try:
argvb = list(map(os.fsencode, sys.argv))
except AttributeError:
argvb = sys.argv
# Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
# no need to mess with it here.
QGISAPP = QgsApplication(argvb, myGuiFlag)
QGISAPP.initQgis()
print(QGISAPP.showSettings())
def debug_log_message(message, tag, level):
print('{}({}): {}'.format(tag, level, message))
QgsApplication.instance().messageLog().messageReceived.connect(debug_log_message)
if cleanup:
import atexit
@atexit.register
def exitQgis():
QGISAPP.exitQgis()
return QGISAPP
示例2: testOwnership
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def testOwnership(self):
"""
Test that registered color schemes do not require that a reference to them is kept.
They should be parented to the registry (on transfer) and even if there's no reference
to the registry around (see the `del` below) this childship should continue to exist.
"""
class TestColorScheme(QgsColorScheme):
def schemeName(self):
return "TestScheme"
def fetchColors(self, context, baseColors):
return None
def clone(self):
return TestColorScheme()
def flags(self):
return 1
reg = QgsApplication.instance().colorSchemeRegistry()
reg.addColorScheme(TestColorScheme())
del reg
reg = QgsApplication.instance().colorSchemeRegistry()
self.assertIn('TestScheme', [scheme.schemeName() for scheme in reg.schemes()])
示例3: load
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def load(self):
success = super().load()
if success:
self.parameterTypeFieldsMapping = FieldsMapper.ParameterFieldsMappingType()
QgsApplication.instance().processingRegistry().addParameterType(self.parameterTypeFieldsMapping)
return success
示例4: threadCleanup
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def threadCleanup(self):
''' cleanup after thread run
'''
# restore cursor
QgsApplication.instance().restoreOverrideCursor()
if self.alg:
self.alg.deleteLater()
self.alg = None
self.thread.wait()
self.thread.deleteLater()
# remove progress bar
if self.progressMessageBarItem:
iface.messageBar().popWidget(self.progressMessageBarItem)
self.progressMessageBarItem = None
示例5: unmodalWidget
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def unmodalWidget(objectName, repeatTimes=10, repeatInterval=500, step=0):
"""Look for a widget in the QGIS hierarchy to set it as
not modal.
If the widget is not found try agail after a "repeatInterval"
and repeat no more that "repeatTimes"
"""
if not objectName:
return
l = QgsApplication.instance().topLevelWidgets()
for d in l:
for dd in d.findChildren(QDialog):
if dd.objectName() != objectName:
continue
dd.setWindowModality(False)
return
if repeatTimes == step:
return
# if here => not found
QTimer.singleShot(repeatInterval,
lambda: unmodalWidget(objectName, repeatTimes, repeatInterval,
step + 1))
示例6: __init__
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("PythonConsole")
self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
# self.setAllowedAreas(Qt.BottomDockWidgetArea)
self.console = PythonConsoleWidget(self)
self.setWidget(self.console)
self.setFocusProxy(self.console)
# try to restore position from stored main window state
if iface and not iface.mainWindow().restoreDockWidget(self):
iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
# closeEvent is not always called for this widget -- so we also trigger a settings
# save on application exit
QgsApplication.instance().aboutToQuit.connect(self.console.saveSettingsConsole)
示例7: fetchFiles
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def fetchFiles(self, urls, renderContext):
downloader = Downloader(None, self.maxConnections, self.cacheExpiry, self.userAgent)
downloader.moveToThread(QgsApplication.instance().thread())
downloader.timer.moveToThread(QgsApplication.instance().thread())
self.logT("TileLayer.fetchFiles() starts")
# create a QEventLoop object that belongs to the current worker thread
eventLoop = QEventLoop()
downloader.allRepliesFinished.connect(eventLoop.quit)
if self.iface:
# for download progress
downloader.replyFinished.connect(self.networkReplyFinished)
self.downloader = downloader
# create a timer to watch whether rendering is stopped
watchTimer = QTimer()
watchTimer.timeout.connect(eventLoop.quit)
# fetch files
QMetaObject.invokeMethod(self.downloader, "fetchFilesAsync", Qt.QueuedConnection, Q_ARG(list, urls), Q_ARG(int, self.plugin.downloadTimeout))
# wait for the fetch to finish
tick = 0
interval = 500
timeoutTick = self.plugin.downloadTimeout * 1000 / interval
watchTimer.start(interval)
while tick < timeoutTick:
# run event loop for 0.5 seconds at maximum
eventLoop.exec_()
if downloader.unfinishedCount() == 0 or renderContext.renderingStopped():
break
tick += 1
watchTimer.stop()
if downloader.unfinishedCount() > 0:
downloader.abort(False)
if tick == timeoutTick:
downloader.errorStatus = Downloader.TIMEOUT_ERROR
self.log("fetchFiles(): timeout")
# watchTimer.timeout.disconnect(eventLoop.quit)
# downloader.allRepliesFinished.disconnect(eventLoop.quit)
self.logT("TileLayer.fetchFiles() ends")
return downloader.fetchedFiles
示例8: __run_test
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def __run_test():
"""
Run the test specified as last argument in the command line.
"""
# Disable modal handler for bad layers
QgsProject.instance().setBadLayerHandler(QgsProjectBadLayerDefaultHandler())
eprint("QGIS Test Runner Inside - starting the tests ...")
try:
test_module_name = QgsApplication.instance().arguments()[-1]
function_name = __get_test_function(test_module_name)
eprint("QGIS Test Runner Inside - executing function %s" % function_name)
function_name()
except Exception as e:
eprint("QGIS Test Runner Inside - [FAILED] Exception: %s" % e)
# Print tb
traceback.print_exc(file=sys.stdout)
app = QgsApplication.instance()
os.kill(app.applicationPid(), signal.SIGTERM)
示例9: setUpClass
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def setUpClass(cls):
"""Run before all tests"""
QCoreApplication.setOrganizationName("QGIS_Test")
QCoreApplication.setOrganizationDomain(
"QGIS_TestPyQgsProcessingInPlace.com")
QCoreApplication.setApplicationName("QGIS_TestPyQgsProcessingInPlace")
QgsSettings().clear()
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
cls.registry = QgsApplication.instance().processingRegistry()
示例10: _dropEvent
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def _dropEvent(event):
if event.mimeData().hasText():
itemId = event.mimeData().text()
if itemId in [param.id() for param in QgsApplication.instance().processingRegistry().parameterTypes()]:
self.addInputOfType(itemId, event.pos())
else:
alg = QgsApplication.processingRegistry().createAlgorithmById(itemId)
if alg is not None:
self._addAlgorithm(alg, event.pos())
event.accept()
else:
event.ignore()
示例11: setUp
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def setUp(self):
self.ran_errored = False
self.ran_finished = False
self.ran_progress = False
self.qgs = None
# Duh... there can only be one QApplication at a time
# http://stackoverflow.com/questions/10888045/simple-ipython-example-raises-exception-on-sys-exit
# if you do create >1 QgsApplications (QtApplications) then you will have non exit code 0
self.qgs = QgsApplication.instance() # checks if QApplication already exists
if not self.qgs: # create QApplication if it doesnt exist
self.qgs = QgsApplication(sys.argv, False)
self.qgs.initQgis() # nessecary for opening auth db etc etc
示例12: run
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def run(self):
geojson = self.geojson()
projestions = []
if geojson:
try:
projestions = projestions_api.get_projestions(geojson)
except URLError as e:
msg = 'URLError while loading projestions: %s' % str(e)
QgsApplication.instance().messageLog().logMessage(msg, tag="Projestions",
level=Qgis.MessageLevel(1))
self.warningSent.emit('Failed to get projestions from API. '
'Please try again and see the error log '
'for details.')
except Exception as e:
msg = '%s while loading projections' % type(e).__name__
QgsApplication.instance().messageLog().logMessage(msg, tag="Projestions",
level=Qgis.MessageLevel(1))
QgsApplication.instance().messageLog().logMessage(traceback.format_exc(),
tag="Projestions",
level=Qgis.MessageLevel(1))
self.warningSent.emit('Failed to get projestions from API. '
'Please try again and see the error log '
'for details.')
self.taskFinished.emit(projestions)
self.quit()
示例13: __run_test
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def __run_test():
"""
Run the test specified as last argument in the command line.
"""
eprint("QGIS Test Runner Inside - starting the tests ...")
try:
test_module_name = QgsApplication.instance().argv()[-1]
function_name = __get_test_function(test_module_name)
if function_name is None:
eprint("QGIS Test Runner Inside - [ERROR] cannot load test function from %s" % test_module_name)
function_name()
except Exception, e:
eprint("QGIS Test Runner Inside - [ERROR] Exception: %s" % e)
示例14: setUpClass
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def setUpClass(cls):
"""Run before all tests"""
QCoreApplication.setOrganizationName("QGIS_Test")
QCoreApplication.setOrganizationDomain(
"QGIS_TestPyQgsExportToPostgis.com")
QCoreApplication.setApplicationName("QGIS_TestPyQgsExportToPostgis")
QgsSettings().clear()
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
cls.registry = QgsApplication.instance().processingRegistry()
# Create DB connection in the settings
settings = QgsSettings()
settings.beginGroup('/PostgreSQL/connections/qgis_test')
settings.setValue('service', 'qgis_test')
settings.setValue('database', 'qgis_test')
示例15: loop_qgis
# 需要导入模块: from qgis.core import QgsApplication [as 别名]
# 或者: from qgis.core.QgsApplication import instance [as 别名]
def loop_qgis(kernel):
"""QGIS event loop for IPython kernels.
Based on loop_qt in IPython.zmq.eventloops, but uses the special QGIS main
application instance and avoids trying to launch a new instance. Using
loop_qt will cause starting the kernel to hang QGIS with IPython 0.12 or
later.
"""
from qgis.core import QgsApplication
from PyQt4 import QtCore
kernel.app = QgsApplication.instance()
kernel.timer = QtCore.QTimer()
kernel.timer.timeout.connect(kernel.do_one_iteration)
# Units for the timer are in milliseconds
kernel.timer.start(1000*kernel._poll_interval)