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


Python QtCore.QCoreApplication类代码示例

本文整理汇总了Python中qgis.PyQt.QtCore.QCoreApplication的典型用法代码示例。如果您正苦于以下问题:Python QCoreApplication类的具体用法?Python QCoreApplication怎么用?Python QCoreApplication使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QCoreApplication类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: execute

    def execute(self, sql, all_args=None):
        """

        :param sql:
        :param all_args: A list of lists of equal lenght to sql (if sql is a list) containing arguments for ? in the
        corresponding sql.
        :return:
        """
        if isinstance(sql, str):
            sql = [sql]
        elif not isinstance(sql, (list, tuple)):
            raise TypeError(ru(QCoreApplication.translate('DbConnectionManager', 'DbConnectionManager.execute: sql must be type string or a list/tuple of strings. Was %s'))%ru(type(sql)))
        for idx, line in enumerate(sql):
            if all_args is None:
                try:
                    self.cursor.execute(line)
                except Exception as e:
                    textstring = ru(QCoreApplication.translate('sql_load_fr_db', """DB error!\n SQL causing this error:%s\nMsg:\n%s""")) % (ru(line), ru(str(e)))
                    utils.MessagebarAndLog.warning(
                        bar_msg=utils.sql_failed_msg(),
                        log_msg=textstring)
                    raise
            elif isinstance(all_args, (list, tuple)):
                args = all_args[idx]
                try:
                    self.cursor.execute(line, args)
                except Exception as e:
                    textstring = ru(QCoreApplication.translate('sql_load_fr_db', """DB error!\n SQL causing this error:%s\nusing args %s\nMsg:\n%s""")) % (ru(line), ru(args), ru(str(e)))
                    utils.MessagebarAndLog.warning(
                        bar_msg=utils.sql_failed_msg(),
                        log_msg=textstring)
                    raise
            else:
                raise TypeError(ru(QCoreApplication.translate('DbConnectionManager', 'DbConnectionManager.execute: all_args must be a list/tuple. Was %s')) % ru(type(all_args)))
开发者ID:jkall,项目名称:qgis-midvatten-plugin,代码行数:34,代码来源:db_utils.py

示例2: addAlgorithmEntry

def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False):
    if actionText is None:
        if (QgsGui.higFlags() & QgsGui.HigMenuTextIsTitleCase) and not (alg.flags() & QgsProcessingAlgorithm.FlagDisplayNameIsLiteral):
            alg_title = QgsStringUtils.capitalize(alg.displayName(), QgsStringUtils.TitleCase)
        else:
            alg_title = alg.displayName()
        actionText = alg_title + QCoreApplication.translate('Processing', '…')
    action = QAction(icon or alg.icon(), actionText, iface.mainWindow())
    alg_id = alg.id()
    action.setData(alg_id)
    action.triggered.connect(lambda: _executeAlgorithm(alg_id))
    action.setObjectName("mProcessingUserMenu_%s" % alg_id)

    if menuName:
        menu = getMenu(menuName, iface.mainWindow().menuBar())
        submenu = getMenu(submenuName, menu)
        submenu.addAction(action)

    if addButton:
        global algorithmsToolbar
        if algorithmsToolbar is None:
            algorithmsToolbar = iface.addToolBar(QCoreApplication.translate('MainWindow', 'Processing Algorithms'))
            algorithmsToolbar.setObjectName("ProcessingAlgorithms")
            algorithmsToolbar.setToolTip(QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar'))
        algorithmsToolbar.addAction(action)
开发者ID:dmarteau,项目名称:QGIS,代码行数:25,代码来源:menus.py

示例3: __init__

    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())
开发者ID:mbernasocchi,项目名称:QGIS,代码行数:25,代码来源:AlgorithmDialog.py

示例4: show

 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)
开发者ID:warrieka,项目名称:geopunt4Qgis,代码行数:34,代码来源:geopunt4QgisPoidialog.py

示例5: testLayerRemovalBeforeRun

    def testLayerRemovalBeforeRun(self):
        """test behavior when layer is removed before task begins"""
        path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif')
        raster_layer = QgsRasterLayer(path, "test")
        self.assertTrue(raster_layer.isValid())

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(raster_layer.dataProvider().clone()))

        tmp = create_temp_filename('remove_layer.tif')
        writer = QgsRasterFileWriter(tmp)

        task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs())

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        # remove layer
        raster_layer = None

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        # in this case will still get a positive result - since the pipe is cloned before the task
        # begins the task is no longer dependent on the original layer
        self.assertTrue(self.success)
        self.assertFalse(self.fail)
        self.assertTrue(os.path.exists(tmp))
开发者ID:phborba,项目名称:QGIS,代码行数:29,代码来源:test_qgsrasterfilewritertask.py

示例6: startServerPlugin

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
开发者ID:volaya,项目名称:QGIS,代码行数:26,代码来源:utils.py

示例7: __init__

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save a reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'NNJoin_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.NNJOIN = self.tr('NNJoin')
        self.NNJOINAMP = self.tr('&NNJoin')
        self.toolbar = None
开发者ID:JiaqiLiu,项目名称:qgisnnjoinplugin,代码行数:30,代码来源:NNJoin_plugin.py

示例8: defineCharacteristicsFromFile

    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.name = line
        self.i18n_name = QCoreApplication.translate("TAUDEMAlgorithm", line)
        line = lines.readline().strip('\n').strip()
        self.cmdName = line
        line = lines.readline().strip('\n').strip()
        self.group = line
        self.i18n_group = QCoreApplication.translate("TAUDEMAlgorithm", line)

        line = lines.readline().strip('\n').strip()
        while line != '':
            try:
                line = line.strip('\n').strip()
                if line.startswith('Parameter'):
                    param = getParameterFromString(line)
                    self.addParameter(param)
                else:
                    self.addOutput(getOutputFromString(line))
                line = lines.readline().strip('\n').strip()
            except Exception as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not load TauDEM algorithm: %s\n%s' % (self.descriptionFile, line)))
                raise e
        lines.close()
开发者ID:DHI-GRAS,项目名称:ESA_Processing,代码行数:26,代码来源:TauDEMAlgorithm.py

示例9: __init__

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GBIFOccurrences_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dlg = GBIFOccurrencesDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&GBIF Occurrences')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'GBIFOccurrences')
        self.toolbar.setObjectName(u'GBIFOccurrences')
开发者ID:BelgianBiodiversityPlatform,项目名称:qgis-gbif-api,代码行数:35,代码来源:qgis_occurrences.py

示例10: import_foreign_keys

    def import_foreign_keys(self, dbconnection, goal_table, temptablename, foreign_keys, existing_columns_in_temptable):
        #TODO: Empty foreign keys are probably imported now. Must add "case when...NULL" to a couple of sql questions here

        #What I want to do:
        # import all foreign keys from temptable that doesn't already exist in foreign key table
        # insert into fk_table (to1, to2) select distinct from1(cast as), from2(cast as) from temptable where concatted_from_and_case_when_null not in concatted_to_and_case_when_null

        for fk_table, from_to_fields in foreign_keys.items():
            from_list = [x[0] for x in from_to_fields]
            to_list = [x[1] for x in from_to_fields]
            if not all([_from in existing_columns_in_temptable for _from in from_list]):
                utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('midv_data_importer', 'Import of foreign keys failed, see log message panel')), log_msg=ru(QCoreApplication.translate('midv_data_importer', 'There were keys missing for importing to fk_table %s, so no import was done.'))%fk_table)
                continue

            nr_fk_before = dbconnection.execute_and_fetchall('''select count(*) from %s''' % fk_table)[0][0]
            table_info = db_utils.db_tables_columns_info(table=fk_table, dbconnection=dbconnection)[fk_table]
            column_headers_types = dict([(row[1], row[2]) for row in table_info])

            null_replacement_string = 'NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL'
            concatted_from_string = '||'.join(["CASE WHEN %s is NULL THEN '%s' ELSE %s END"%(x, null_replacement_string, x) for x in from_list])
            concatted_to_string = '||'.join(["CASE WHEN %s is NULL THEN '%s' ELSE %s END"%(x, null_replacement_string, x) for x in to_list])
            sql = u'INSERT INTO %s (%s) SELECT DISTINCT %s FROM %s AS b WHERE %s NOT IN (SELECT %s FROM %s) AND %s'%(fk_table,
                                                                                                         u', '.join([u'"{}"'.format(k) for k in to_list]),
                                                                                                         u', '.join([u'''CAST("b"."%s" as "%s")'''%(k, column_headers_types[to_list[idx]]) for idx, k in enumerate(from_list)]),
                                                                                                         temptablename,
                                                                                                         concatted_from_string,
                                                                                                         concatted_to_string,
                                                                                                         fk_table,
                                                                                                         ' AND '.join([''' b.{} IS NOT NULL and b.{} != '' '''.format(k, k, k) for k in from_list]))
            dbconnection.execute(sql)

            nr_fk_after = dbconnection.execute_and_fetchall('''select count(*) from %s''' % fk_table)[0][0]
            if nr_fk_after > nr_fk_before:
                utils.MessagebarAndLog.info(log_msg=ru(QCoreApplication.translate('midv_data_importer', 'In total %s rows were imported to foreign key table %s while importing to %s.'))%(str(nr_fk_after - nr_fk_before), fk_table, goal_table))
开发者ID:jkall,项目名称:qgis-midvatten-plugin,代码行数:34,代码来源:import_data_to_db.py

示例11: __init__

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QLocale(QSettings().value('locale/userLocale'))
        locale_path = os.path.join(self.plugin_dir, 'i18n')
        self.translator = QTranslator()
        self.translator.load(locale, 'QFieldSync', '_', locale_path)

        QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&QFieldSync')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QFieldSync')
        self.toolbar.setObjectName(u'QFieldSync')

        # instance of the QgsOfflineEditing
        self.offline_editing = QgsOfflineEditing()
        self.preferences = Preferences()

        QgsProject.instance().readProject.connect(self.update_button_enabled_status)

        # store warnings from last run
        self.last_action_warnings = []
开发者ID:opengisch,项目名称:QFieldSync,代码行数:35,代码来源:qfield_sync.py

示例12: __init__

    def __init__(self, iface):
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            os.path.dirname(__file__),
            'i18n',
            'qdraw_{}.qm'.format(locale))

        self.translator = None
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.iface = iface
        self.sb = self.iface.statusBarIface()
        self.tool = None
        self.toolname = None

        self.bGeom = None

        self.actions = []
        self.menu = '&Qdraw'
        self.toolbar = self.iface.addToolBar('Qdraw')
        self.toolbar.setObjectName('Qdraw')

        self.settings = QdrawSettings()
开发者ID:jeremyk6,项目名称:qdraw,代码行数:28,代码来源:qdraw.py

示例13: __init__

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save a reference to the QGIS interface
        self.iface = iface
        # initialize the plugin directory
        pluginPath = os.path.dirname(__file__)
        # initialize the locale using the QGIS locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            pluginPath,
            'i18n',
            '{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep the reference
        self.dlg = linedirectionhistogramDialog(self.iface)

        # Declare instance attributes
        self.menuname = self.tr(u'&Line Direction Histogram')
开发者ID:havatv,项目名称:qgislinedirectionhistogramplugin,代码行数:29,代码来源:linedirectionhistogram.py

示例14: startProcessingPlugin

def startProcessingPlugin(packageName):
    """ initialize only the Processing components of a plugin """
    global plugins, active_plugins, iface, plugin_times
    start = time.process_time()
    if not _startPlugin(packageName):
        return False

    errMsg = QCoreApplication.translate("Python", "Couldn't load plugin '{0}'").format(packageName)
    if not hasattr(plugins[packageName], 'initProcessing'):
        del plugins[packageName]
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate("Python", "{0} - plugin has no initProcessing() method").format(errMsg)
        showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
        return False

    # initProcessing
    try:
        plugins[packageName].initProcessing()
    except:
        del plugins[packageName]
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate("Python", "{0} due to an error when calling its initProcessing() method").format(errMsg)
        showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
        return False

    end = time.process_time()
    _addToActivePlugins(packageName, end - start)

    return True
开发者ID:m-kuhn,项目名称:QGIS,代码行数:29,代码来源:utils.py

示例15: write

    def write(self, m):
        if self.style == "_traceback":
            # Show errors in red
            stderrColor = QColor(self.sO.settings.value("pythonConsole/stderrFontColor", QColor(Qt.red)))
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETFORE, 0o01, stderrColor)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETITALIC, 0o01, True)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETBOLD, 0o01, True)
            pos = self.sO.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS)
            self.sO.SendScintilla(QsciScintilla.SCI_STARTSTYLING, pos, 31)
            self.sO.append(m)
            self.sO.SendScintilla(QsciScintilla.SCI_SETSTYLING, len(m), 0o01)
        else:
            self.sO.append(m)

        if self.out:
            self.out.write(m)

        self.move_cursor_to_end()

        if self.style != "_traceback":
            QCoreApplication.processEvents()

        if self.fire_keyboard_interrupt:
            self.fire_keyboard_interrupt = False
            raise KeyboardInterrupt
开发者ID:Cracert,项目名称:Quantum-GIS,代码行数:25,代码来源:console_output.py


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