当前位置: 首页>>代码示例>>Python>>正文


Python QgsApplication.instance方法代码示例

本文整理汇总了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
开发者ID:AlisterH,项目名称:Quantum-GIS,代码行数:62,代码来源:__init__.py

示例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()])
开发者ID:pblottiere,项目名称:QGIS,代码行数:29,代码来源:test_qgscolorschemeregistry.py

示例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
开发者ID:jonnyforestGIS,项目名称:QGIS,代码行数:10,代码来源:QgisAlgorithmProvider.py

示例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
开发者ID:QTrafficmodel,项目名称:QTraffic,代码行数:18,代码来源:output_tab_manager.py

示例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))
开发者ID:gioman,项目名称:qgis-lessons-plugin,代码行数:29,代码来源:utils.py

示例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)
开发者ID:DelazJ,项目名称:QGIS,代码行数:19,代码来源:console.py

示例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
开发者ID:gueguenster,项目名称:TileLayerPlugin,代码行数:47,代码来源:tilelayer.py

示例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)
开发者ID:blazek,项目名称:QGIS,代码行数:20,代码来源:qgis_testrunner.py

示例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()
开发者ID:dmarteau,项目名称:QGIS,代码行数:12,代码来源:test_qgsprocessingalgrunner.py

示例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()
开发者ID:tomchadwin,项目名称:QGIS,代码行数:14,代码来源:ModelerDialog.py

示例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
开发者ID:rduivenvoorde,项目名称:jrodos,代码行数:14,代码来源:test_provider_base.py

示例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()
开发者ID:ebrelsford,项目名称:qgis-projestions,代码行数:28,代码来源:projestions.py

示例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)
开发者ID:elpaso,项目名称:qgis-desktop-docker,代码行数:15,代码来源:qgis_testrunner.py

示例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')
开发者ID:alexbruy,项目名称:QGIS,代码行数:18,代码来源:test_processing_importintopostgis.py

示例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)
开发者ID:carriercomm,项目名称:qgis-ipython,代码行数:18,代码来源:internal_ipkernel.py


注:本文中的qgis.core.QgsApplication.instance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。