class Translate: def __init__(self): # 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", "PluginMapotempo_{}.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) def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate("PluginMapotempo", message)
class __Translator: def __init__(self): self.dff = QTranslator() self.generic = QTranslator() self.Conf = Conf() self.loadLanguage() def loadLanguage(self): """ Load DFF translation + a Qt translation file FIXME need to check if qt4 directory exists in /usr/share or /usr/local/share """ l1 = self.generic.load("/usr/share/qt4/translations/qt_" + str(self.Conf.getLanguage()).lower()[:2]) l2 = self.dff.load( sys.modules["ui.gui"].__path__[0] + "/i18n/Dff_" + str(self.Conf.getLanguage()).lower()[:2] ) return l1 and l2 def getDFF(self): return self.dff def getGeneric(self): return self.generic
def correr_interfaz(app): ESettings().cargar() import src.ui.inicio # lint:ok # Traductor local = QLocale.system().name() qtraductor = QTranslator() qtraductor.load("qt_" + local, QLibraryInfo.location( QLibraryInfo.TranslationsPath)) edis = EDIS() app.setWindowIcon(QIcon(paths.ICONOS['icon'])) # Aplicar estilo with open(os.path.join(paths.PATH, "extras", "temas", "default.qss")) as tema: estilo = tema.read() app.setStyleSheet(estilo) # Archivos de última sesión archivos = ESettings.get('general/archivos') # Archivos recientes recents_files = ESettings.get('general/recientes') if recents_files is None: recents_files = [] edis.cargar_archivos(archivos, recents_files) edis.show() sys.exit(app.exec_())
def Translate(self, lang): translator = QTranslator(qApp) translator.load(":Translations/dc_" + lang + ".qm") qApp.installTranslator(translator) self.basename = self.tr("Data Centers GUI") self.demandGraphEditor.basename = self.demandGraphEditor.tr("Request Graph Editor") self.resourcesGraphEditor.basename = self.resourcesGraphEditor.tr("Resources Graph Editor") self.ui.retranslateUi(self) self.settingsDialog.ui.retranslateUi(self.settingsDialog) self.demandGraphEditor.ui.retranslateUi(self.demandGraphEditor) self.resourcesGraphEditor.ui.retranslateUi(self.resourcesGraphEditor) self.randomDialog.ui.retranslateUi(self.randomDialog) self.Vis.ui.retranslateUi(self.Vis) self.graphvis.ui.retranslateUi(self.graphvis) self.showStats() for k in self.demands.keys(): cb = QComboBox() cb.addItems([self.tr("No"),self.tr("Yes")]) cb.setCurrentIndex(0 if self.demands[k].critical else 1) QObject.connect(cb, SIGNAL("currentIndexChanged(int)"), k.emitDataChanged) self.ui.demands.setItemWidget(k,3,cb) if self.demands[k].assigned: k.setText(4, self.tr("Yes")) else: k.setText(4, self.tr("No"))
def setup_locale(application, name, language=None, format="%s.%s"): """ Load the translation for the current user locale. The name argument is the file name without the suffix (eg. ".fr.qm"). So use the name "ufwi_rpcd" to load "ufwi_rpcd.fr.qm". """ # Add language as suffix if not language: language = get_language() if not language: # No locale: do nothing return True filename = format % (name, language) translator = QTranslator(application) if filename.startswith(":"): ret = translator.load(filename) if ret: application.installTranslator(translator) debug("Load locale from resources: %s" % filename) return True else: for directory in ('.', '/usr/share/ufwi_rpcd/i18n'): ret = translator.load(filename, directory) if not ret: continue debug("Load locale file: %s" % path_join(directory, filename)) application.installTranslator(translator) return True error("Unable to load translation file: %s" % filename) return False
class QtTranslator(GetTextTranslator): """This deals with translating Qt itself. The rest of the strings are still translated using the gettext mechanism, as we've modified pyuic4 to use gettext too. """ def __init__(self, component_manager): GetTextTranslator.__init__(self, component_manager) self.qt_translator = QTranslator(QCoreApplication.instance()) try: self.qt_dir = os.environ["QTDIR"] except: if sys.platform == "win32": self.qt_dir = os.path.join(sys.exec_prefix, "share", "qt4") else: self.qt_dir = os.path.join("/usr", "share", "qt4") # Avoid stuff like Thai numerals if the language is not explicitly # set to Thai. QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates)) def translate_ui(self, language): app = QCoreApplication.instance() # We always need to remove a translator, to make sure we generate a # LanguageChange event even if their is no Qt translation for that # language installed. app.removeTranslator(self.qt_translator) self.qt_translator.load(os.path.join(self.qt_dir, "translations", "qt_" + language + ".qm")) app.installTranslator(self.qt_translator) # The title can also contain the database name. self.controller().update_title()
class GenericTool(): def __init__(self, iface): self.toolLabel = '' self.toolName = self.__class__.__name__ self.iface = iface self.plugin_dir = os.path.dirname(__file__) self.icon_path = ":/plugins/LAPIGTools/icons/" + self.toolName + ".png" locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'CalculateRegion_{}.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) def initGui(self): self.obtainAction = QAction(QIcon(self.icon_path),QCoreApplication.translate(self.toolLabel,"&"+self.labelName), self.iface.mainWindow()) QObject.connect(self.obtainAction, SIGNAL("triggered()"), self.run) return self.obtainAction,self.labelName def unload(self): #self.iface.removePluginMenu(self.toolLabel, self.obtainAction) self.iface.removeToolBarIcon(self.obtainAction)
def init(self, logo, title): from qgis.core import QgsApplication from PyQt4.QtGui import QApplication, QFont, QIcon from PyQt4.QtCore import QLocale, QTranslator try: import PyQt4.QtSql except ImportError: pass self.app = QgsApplication(self.sysargv, True) import roam.roam_style self.app.setStyleSheet(roam.roam_style.appstyle) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) QApplication.setWindowIcon(QIcon(logo)) QApplication.setApplicationName(title) import roam.editorwidgets.core roam.editorwidgets.core.registerallwidgets() return self
def main(): app = QApplication([i.encode('utf-8') for i in sys.argv]) app.setOrganizationName(ffmc.__name__) app.setOrganizationDomain(ffmc.__url__) app.setApplicationName('FF Muli Converter') app.setWindowIcon(QIcon(':/ffmulticonverter.png')) locale = QLocale.system().name() qtTranslator = QTranslator() if qtTranslator.load('qt_' + locale, ':/'): app.installTranslator(qtTranslator) appTranslator = QTranslator() if appTranslator.load('ffmulticonverter_' + locale, ':/'): app.installTranslator(appTranslator) if not os.path.exists(config.log_dir): os.makedirs(config.log_dir) logging.basicConfig( filename=config.log_file, level=logging.DEBUG, format=config.log_format, datefmt=config.log_dateformat ) converter = MainWindow() converter.show() app.exec_()
class MapSwipePlugin: def __init__(self, iface): def translate(): # # For create file 'qm' # 1) Define that files need for translation: mapswipetool.pro # 2) Create 'ts': pylupdate4 -verbose mapswipetool.pro # 3) Edit your translation: QtLinquist # 4) Create 'qm': lrelease *.ts # dirname = os.path.dirname( os.path.abspath(__file__) ) locale = QSettings().value("locale/userLocale") localePath = os.path.join( dirname, "i18n", "%s_%s.qm" % ( name_src, locale ) ) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.iface = iface self.canvas = iface.mapCanvas() self.action = None # Define by initGui self.tool = MapSwipeTool( self.iface ) self.prevTool = None # Define by run name_src = "mapswipetool" translate() def initGui(self): title = "Map swipe tool" icon = QIcon( os.path.join( os.path.dirname(__file__), 'mapswipetool.png' ) ) self.action = QAction( icon, title, self.iface.mainWindow() ) self.action.setObjectName( "MapSwipeTool" ) self.action.setWhatsThis( title ) self.action.setStatusTip( title ) self.action.triggered.connect( self.run ) self.menu = "&Map swipe tool" # Maptool self.action.setCheckable( True ) self.tool.setAction( self.action ) self.iface.addToolBarIcon( self.action ) self.iface.addPluginToMenu( self.menu, self.action ) def unload(self): self.canvas.unsetMapTool( self.tool ) self.iface.removeToolBarIcon( self.action ) self.iface.removePluginMenu( self.menu, self.action ) del self.action @pyqtSlot() def run(self): if self.canvas.mapTool() != self.tool: self.prevTool = self.canvas.mapTool() self.canvas.setMapTool( self.tool ) else: self.canvas.setMapTool( self.prevTool )
class qWat(): def __init__(self, iface): self.iface = iface self.settings = MySettings() self.mainDialog = MainDialog() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()+"/python/plugins/qwat" systemPluginPath = QgsApplication.prefixPath()+"/share/qgis/python/plugins/qwat" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = userPluginPath+"/i18n/qwat_"+myLocale+".qm" elif QFileInfo(systemPluginPath).exists(): pluginPath = systemPluginPath+"/i18n/qwat_"+myLocale+".qm" self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) def initGui(self): self.uiAction = QAction(QIcon(":/plugins/qWat/icons/qwat.svg"), "settings", self.iface.mainWindow()) self.uiAction.triggered.connect(self.showDialog) self.iface.addPluginToMenu("&qWat", self.uiAction) self.iface.addToolBarIcon(self.uiAction) def unload(self): self.iface.removePluginMenu("&qWat", self.uiAction) self.iface.removeToolBarIcon(self.uiAction) def showDialog(self): self.mainDialog.show()
def main(): global app, aboutData import setproctitle setproctitle.setproctitle("iosshy") from PyQt4.QtCore import QCoreApplication, QTranslator, QLocale, QSettings from PyQt4.QtGui import QApplication, QSystemTrayIcon, QImage from tunneldialog import TunnelDialog try: from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs from PyKDE4.kdeui import KApplication, KIcon aboutData = KAboutData( name, #appName name, #catalogName ki18n(name), #programName version, ki18n(description), #shortDescription KAboutData.License_BSD, #licenseKey ki18n("© 2010 Massimiliano Torromeo"), #copyrightStatement ki18n(""), #text url #homePageAddress ) aboutData.setBugAddress("http://github.com/mtorromeo/iosshy/issues") aboutData.addAuthor( ki18n("Massimiliano Torromeo"), #name ki18n("Main developer"), #task "*****@*****.**" #email ) aboutData.setProgramLogo(QImage(":icons/network-server.png")) KCmdLineArgs.init(sys.argv, aboutData) app = KApplication() app.setWindowIcon(KIcon("network-server")) if app.isSessionRestored(): sys.exit(0) except ImportError: app = QApplication(sys.argv) app.setOrganizationName("MTSoft") app.setApplicationName(name) if QSystemTrayIcon.isSystemTrayAvailable(): translator = QTranslator() qmFile = "tunneller_%s.qm" % QLocale.system().name() if os.path.isfile(qmFile): translator.load(qmFile) app.installTranslator(translator) dialog = TunnelDialog() sys.exit(app.exec_()) else: print "System tray not available. Exiting." sys.exit(1)
def __init__(self, args=[], **kw): QApplication.__init__(self, args) locale = QLocale.system().name() translator=QTranslator () translator.load("qt_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) self.installTranslator(translator) self._print_signal.connect(self._print)
class BigSearch (): def __init__(self, iface): self.iface = iface self.process = SearchProcess() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()+"/python/plugins/bigsearch" systemPluginPath = QgsApplication.prefixPath()+"/share/qgis/python/plugins/bigsearch" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = userPluginPath+"/i18n/bigsearch_"+myLocale+".qm" elif QFileInfo(systemPluginPath).exists(): pluginPath = systemPluginPath+"/i18n/bigsearch_"+myLocale+".qm" self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) def initGui(self): # # dock # self.dockAction = QAction(QIcon(":/plugins/bigsearch/icons/bigsearch.svg"), "Big Search", # self.iface.mainWindow()) # self.dockAction.setCheckable(True) # self.dockAction.triggered.connect(self.dock.setVisible) # self.iface.addPluginToMenu("&Big Search", self.dockAction) # self.iface.addToolBarIcon(self.dockAction) # self.dock.visibilityChanged.connect(self.dockAction.setChecked) # settings self.settingsAction = QAction(QIcon(":/plugins/bigsearch/icons/settings.svg"), "Configuration", self.iface.mainWindow()) self.settingsAction.triggered.connect(self.showSettings) self.iface.addPluginToMenu("&Big Search", self.settingsAction) # help self.helpAction = QAction(QIcon(":/plugins/bigsearch/icons/help.svg"), "Help", self.iface.mainWindow()) self.helpAction.triggered.connect(lambda: QDesktopServices().openUrl(QUrl("http://io.github.com/3nids/bigsearch/"))) self.iface.addPluginToMenu("&Big Search", self.helpAction) self.searchEdit = QLineEdit() self.searchEdit.textChanged.connect(self.doSearch) self.searchEditAction = self.iface.addToolBarWidget(self.searchEdit) def unload(self): # Remove the plugin menu item and icon # self.iface.removePluginMenu("&Big Search", self.dockAction) self.iface.removePluginMenu("&Big Search", self.helpAction) self.iface.removePluginMenu("&Big Search", self.settingsAction) # self.iface.removeToolBarIcon(self.dockAction) self.iface.removeToolBarIcon(self.searchEditAction) def doSearch(self, searchText): self.process.newSearch(searchText) def showSettings(self): ConfigurationDialog(self.iface).exec_()
class RuGeocoderPlugin: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.__converter_dlg = ConverterDialog() self.__geocoder_dlg = BatchGeocodingDialog() # i18n support override_locale = QSettings().value('locale/overrideFlag', False, type=bool) if not override_locale: locale_full_name = QLocale.system().name() else: locale_full_name = QSettings().value('locale/userLocale', '', type=unicode) self.locale_path = '%s/i18n/rugeocoder_%s.qm' % (_current_path, locale_full_name[0:2]) if QFileInfo(self.locale_path).exists(): self.translator = QTranslator() self.translator.load(self.locale_path) QCoreApplication.installTranslator(self.translator) def initGui(self): # Setup signals self.action_convert = QAction(QIcon(':/plugins/rugeocoderplugin/convert.png'), QCoreApplication.translate('RuGeocoder', 'Convert CSV to SHP'), self.iface.mainWindow()) QObject.connect(self.action_convert, SIGNAL("triggered()"), self.run_convert) self.action_batch_geocoding = QAction(QIcon(':/plugins/rugeocoderplugin/icon.png'), QCoreApplication.translate('RuGeocoder', 'Batch geocoding'), self.iface.mainWindow()) QObject.connect(self.action_batch_geocoding, SIGNAL('triggered()'), self.run_batch) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action_convert) self.iface.addPluginToMenu('&RuGeocoder', self.action_convert) self.iface.addToolBarIcon(self.action_batch_geocoding) self.iface.addPluginToMenu('&RuGeocoder', self.action_batch_geocoding) def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu('&RuGeocoder', self.action_convert) self.iface.removeToolBarIcon(self.action_convert) self.iface.removePluginMenu('&RuGeocoder', self.action_batch_geocoding) self.iface.removeToolBarIcon(self.action_batch_geocoding) def run_convert(self): if not self.__converter_dlg.isVisible(): self.__converter_dlg = ConverterDialog() self.__converter_dlg.show() self.__converter_dlg.exec_() def run_batch(self): if not self.__geocoder_dlg.isVisible(): self.__geocoder_dlg = BatchGeocodingDialog() self.__geocoder_dlg.show() self.__geocoder_dlg.exec_()
def __init__(self, args=[], **kw): QApplication.__init__(self, args) locale = QLocale.system().name() translator=QTranslator () translator.load("qt_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) self.installTranslator(translator) if param.style_Qt: self.setStyle(param.style_Qt)
class FieldPyculatorPlugin: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # i18n support override_locale = QSettings().value('locale/overrideFlag', False, type=bool) if not override_locale: locale_full_name = QLocale.system().name() else: locale_full_name = QSettings().value('locale/userLocale', '', type=unicode) self.locale_path = currentPath + '/i18n/field_pyculator_' + locale_full_name[0:2] + '.qm' if path.exists(self.locale_path): self.translator = QTranslator() self.translator.load(self.locale_path) QCoreApplication.installTranslator(self.translator) def tr(self, text): return QCoreApplication.translate('FieldPyculatorPlugin', text) def initGui(self): # Create action that will start plugin configuration self.action = QAction(QIcon(':/plugins/fieldpyculatorplugin/icon.png'), self.tr('FieldPyculator'), self.iface.mainWindow()) # connect the action to the run method QObject.connect(self.action, SIGNAL('triggered()'), self.run) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(self.tr('&FieldPyculator'), self.action) # track layer changing QObject.connect(self.iface, SIGNAL('currentLayerChanged( QgsMapLayer* )'), self.layer_changed) # check already selected layers self.layer_changed() def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu(self.tr('&FieldPyculator'), self.action) self.iface.removeToolBarIcon(self.action) # Remove layer changing tracking QObject.disconnect(self.iface, SIGNAL('currentLayerChanged( QgsMapLayer* )'), self.layer_changed) def layer_changed(self): layer = self.iface.activeLayer() if (layer is None) or (layer.type() != QgsMapLayer.VectorLayer): self.action.setEnabled(False) else: self.action.setEnabled(True) def run(self): # create and show the dialog self.dlg = FieldPyculatorDialog(self.iface) # show the dialog self.dlg.show()
class kuw_filter: def __init__(self, iface): # Save reference to the QGIS interface self.outdir = '' self.ilayers = QgsMapLayerRegistry.instance() self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/kuw_filter" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:5] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/kuw_filter_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = kuw_filterDialog() def initGui(self): # Create action that will start plugin configuration self.action = QAction(QIcon(":/plugins/kuw_filter/icon.png"), \ QCoreApplication.translate("kuw_filter", "Kuwahara Filter", None, QApplication.UnicodeUTF8), self.iface.mainWindow()) # connect the action to the run method QObject.connect(self.action, SIGNAL("triggered()"), self.run) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(QCoreApplication.translate("kuw_filter","&Kuwahara Filter", None, QApplication.UnicodeUTF8), self.action) def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu(QCoreApplication.translate("kuw_filter","&Kuwahara Filter", None, QApplication.UnicodeUTF8), self.action) self.iface.removeToolBarIcon(self.action) # run method that performs all the real work def run(self): # show the dialog self.dlg.show() # Run the dialog event loop # See if OK was pressed if True: # do something useful (delete the line containing pass and # substitute with your code) self.dlg.output.setText('') self.dlg.progressBar.setValue(0) self.dlg.refb.setText('1') self.dlg.mem.setText('100') self.dlg.inputbox.clear() for (key, layer) in self.ilayers.mapLayers().iteritems(): if layer.type() == 1: self.dlg.inputbox.addItem(unicode(layer.name()), key) pass
def __init__(self, args=[], **kw): QApplication.__init__(self, args) locale = QLocale.system().name() translator=QTranslator () translator.load("qt_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) self.installTranslator(translator) self._print_signal.connect(self._print) # Pour Mac OS X self.setAttribute(Qt.AA_DontUseNativeMenuBar)
class GeoHealthPlugin(object): def __init__(self, iface): self.iface = iface self.plugin_dir = dirname(__file__) # initialize locale locale = QSettings().value("locale/userLocale")[0:2] locale_path = join( self.plugin_dir, 'i18n', 'GeoHealth_{}.qm'.format(locale)) if exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QCoreApplication.installTranslator(self.translator) self.plugin_menu = None self.geohealth_menu = None self.main_action = None self.xy_action = None self.blur_action = None self.incidence_action = None self.density_action = None self.histogram_action = None # Add to processing self.provider = Provider() Processing.addProvider(self.provider, True) def initGui(self): self.plugin_menu = self.iface.pluginMenu() # Main window icon = QIcon(resource('icon-32.png')) self.main_action = QAction(icon, 'GeoHealth', self.iface.mainWindow()) self.plugin_menu.addAction(self.main_action) # noinspection PyUnresolvedReferences self.main_action.triggered.connect(self.open_main_window) def unload(self): self.plugin_menu.removeAction(self.main_action) Processing.removeProvider(self.provider) @staticmethod def open_main_window(): dialog = MainDialog() dialog.show() dialog.exec_()
class QGISTester: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(QFile.decodeName(__file__)) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'QGISTester_{}.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.menu = self.tr("&QGIS Tester") def tr(self, message): """Get the translation for a string using Qt translation API.""" return QCoreApplication.translate('QGISTester', message) def initGui(self): # Create action that will start plugin configuration icon_path = os.path.join(self.plugin_dir, "icon.png") self.action = QAction(QIcon(icon_path), self.tr("Test your QGIS!"), self.iface.mainWindow()) self.action.setObjectName("QGISTester_Test") # Connect the action to the run method self.action.triggered.connect(self.run) # Add toolbar button and menu item self.iface.addPluginToMenu(self.menu, self.action) if debug_mode: self.iface.addToolBarIcon(self.action) def unload(self): """Remove the plugin menu item and icon""" self.iface.removePluginMenu(self.menu, self.action) if debug_mode: self.iface.removeToolBarIcon(self.action) def run(self): # Import the code for the dialog from qgis_tester_dialog import QGISTesterDialog # Create the dialog dlg = QGISTesterDialog() # show the dialog dlg.show() # Run the dialog event loop dlg.exec_()
class SupervisedClassification: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface QGisLayers.setInterface(iface) # initialize plugin directory self.plugin_dir = ( QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/supervisedclassification" ) # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/supervisedclassification_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > "4.3.3": QCoreApplication.installTranslator(self.translator) def initGui(self): # Create action that will start plugin configuration self.action = QAction( QIcon(":/plugins/supervisedclassification/icon.png"), "Classification Supervisée", self.iface.mainWindow() ) # connect the action to the run method QObject.connect(self.action, SIGNAL("triggered()"), self.run) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu("&Classification Supervisée", self.action) def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu("&Classification Supervisée", self.action) self.iface.removeToolBarIcon(self.action) # run method that performs all the real work def run(self): # create the dialog dlg = SupervisedClassificationDialog() # show the dialog dlg.show() # Run the dialog event loop result = dlg.exec_() # See if OK was pressed if result == 1: # do something useful (delete the line containing pass and # substitute with your code) pass
def test_qgis_translations(self): parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir) dir_path = os.path.abspath(parent_path) file_path = os.path.join(dir_path, "i18n", "inasafe_id.qm") translator = QTranslator() translator.load(file_path) QCoreApplication.installTranslator(translator) expected_msg = "Tidak ada informasi gaya yang ditemukan pada lapisan %s" real_msg = QCoreApplication.translate("@default", "No styleInfo was found for layer %s") msg = "expected %s but got %s" % (expected_msg, real_msg) assert expected_msg == real_msg, msg
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.sysConfigFilter = self.tr("System Configuration files (*.xml)") self.algConfigFilter = self.tr("Algorithm Configuration files (*.xml)") self.ui.result_filename.setText("result"+str(time.time())+".csv") self.best = None translator = QTranslator(qApp) translator.load("GUI/Windows/Translations/relopt_ru.qm") qApp.installTranslator(translator) self.ui.retranslateUi(self)
class EditableGeoCsv: def __init__(self, iface): # pydevd.settrace() self._iface = iface self.plugin_dir = os.path.dirname(__file__) locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir,'i18n','geocsv_{}.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) NotificationHandler.configureIface(iface) self.settings = QSettings("Editable GeoCSV","editablegeocsv") #container for all csv vector layers self.csvVectorLayers = [] #if the project file is successfully read, reconnect all CsvVectorLayers with its datasource self._iface.projectRead.connect(lambda: GeoCsvReconnectController.getInstance().reconnectCsvVectorLayers(self.csvVectorLayers)) #connect to the qgis refresh button self._connectToRefreshAction() def initGui(self): addGeoCsvLayerIcon = QIcon(':/plugins/editablegeocsv/geocsv.png') addGeoCsvLayerText = QCoreApplication.translate('EditableGeoCsv', 'Add GeoCSV layer') self.addGeoCsvLayerAction = QAction(addGeoCsvLayerIcon, addGeoCsvLayerText, self._iface.mainWindow()) self.addGeoCsvLayerAction.triggered.connect(lambda: GeoCsvNewController(self.settings).createCsvVectorLayer(self.csvVectorLayers)) try: self._iface.layerToolBar().addAction(self.addGeoCsvLayerAction) except: self._iface.addToolBarIcon(self.addGeoCsvLayerAction) self._iface.addPluginToVectorMenu(QCoreApplication.translate('EditableGeoCsv', 'Editable GeoCSV'), self.addGeoCsvLayerAction) def unload(self): self._iface.removePluginMenu( QCoreApplication.translate('EditableGeoCsv', 'Editable GeoCSV'), self.addGeoCsvLayerAction) self._iface.removeToolBarIcon(self.addGeoCsvLayerAction) def _connectToRefreshAction(self): for action in self._iface.mapNavToolToolBar().actions(): if action.objectName() == "mActionDraw": action.triggered.connect(lambda: self._refreshCsvVectorLayers()) break def _refreshCsvVectorLayers(self): newCsvVectorLayers = [] GeoCsvReconnectController.getInstance().reconnectCsvVectorLayers(newCsvVectorLayers) self.csvVectorLayers = newCsvVectorLayers self._iface.mapCanvas().refresh()
class Interlis: def __init__(self, iface): # 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] localePath = os.path.join( self.plugin_dir, 'i18n', 'interlis_{}.qm'.format(locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) if ogr_version_num() < 2000200: raise ImportError("GDAL/OGR 2.0.2 or newer required") # Create the dialog (after translation) and keep reference self.dlg = InterlisDialog(self) # Processing provider self.provider = InterlisProvider() def initGui(self): # Create action that will start plugin configuration self.action = QAction( QIcon(":/plugins/interlis/icon.png"), u"Interlis", self.iface.mainWindow()) # connect the action to the run method self.action.triggered.connect(self.run) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u"&Interlis", self.action) Processing.addProvider(self.provider) def unload(self): Processing.removeProvider(self.provider) # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&Interlis", self.action) self.iface.removeToolBarIcon(self.action) def messageLogWidget(self): return self.iface.mainWindow().findChild(QDockWidget, 'MessageLog') def run(self): self.dlg.setup() self.dlg.exec_()
def main(): """ loader function to start the application """ app = QApplication(sys.argv) locale = QLocale.system().name() translator = QTranslator() translator.load("texteditor_%s.qm" % locale) app.installTranslator(translator) main_window = MainWindow() main_window.show() app.exec_()
def run(self): from puding.ui.qt.main_window import MainWindow app = QApplication(sys.argv) locale = QLocale.system().name() translator = QTranslator() translator.load("%s/translations/puding_%s.qm" % (self.res.DEV_HOME, locale)) app.installTranslator(translator) main_window = MainWindow() main_window.show() sys.exit(app.exec_())
def test_qgis_translations(self): """Test that translations work.""" parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir) dir_path = os.path.abspath(parent_path) file_path = os.path.join( dir_path, 'i18n', 'PosiView_de.qm') translator = QTranslator() translator.load(file_path) QCoreApplication.installTranslator(translator) expected_message = 'Guten Morgen' real_message = QCoreApplication.translate("@default", 'Good morning') self.assertEqual(real_message, expected_message)
def test_qgis_translations(self): """Test for qgis translations.""" file_path = safe_dir('i18n/inasafe_id.qm') translator = QTranslator() translator.load(file_path) QCoreApplication.installTranslator(translator) expected_message = ( 'Tidak ada informasi gaya yang ditemukan pada lapisan %s') real_message = QCoreApplication.translate( '@default', 'No styleInfo was found for layer %s') message = 'expected %s but got %s' % (expected_message, real_message) self.assertEqual(expected_message, real_message, message)
class CoordLister: """QGIS Plugin Implementation.""" 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', 'CoordLister_{}.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.actions = [] self.menu = self.tr(u'&CoordLister') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'CoordLister') self.toolbar.setObjectName(u'CoordLister') # check if already a layer is selected on Plugin Load (probably only during testing) currentLayer = self.iface.mapCanvas().currentLayer() if currentLayer: self.listen_layerChanged(currentLayer) # connect to geometry changes (test) QObject.connect(self.iface.mapCanvas(), SIGNAL("currentLayerChanged(QgsMapLayer *)"), self.listen_layerChanged) # set db connector for topology tests self.topologyConnector = TopologyConnector() # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('CoordLister', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ # Create the dialog (after translation) and keep reference self.dlg = CoordListerDialog() icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToVectorMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/CoordLister/icon.png' self.add_action(icon_path, text=self.tr(u'Coordinate Lister'), callback=self.coordList, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginVectorMenu(self.tr(u'&CoordLister'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass def coordList(self): """List the coordinates of the selected geometry""" selected = self.checkSelection() if selected: self.listAllCoordinates(selected) def checkSelection(self): toolname = "CoordinateList" # check that a layer is selected layer = self.iface.mapCanvas().currentLayer() if not layer: QMessageBox.information(None, toolname, "A layer must be selected") return # check that the selected layer is a postgis one if layer.providerType() != 'postgres': QMessageBox.information(None, toolname, "A PostGIS layer must be selected") return uri = QgsDataSourceURI(layer.source()) # get the layer schema schema = str(uri.schema()) if not schema: QMessageBox.information( None, toolname, "Selected layer must be a table, not a view\n" "(no schema set in datasource " + str(uri.uri()) + ")") return # get the layer table table = str(uri.table()) if not table: QMessageBox.information( None, toolname, "Selected layer must be a table, not a view\n" "(no table set in datasource)") return # get the selected features selected = layer.selectedFeatures() if not selected: QMessageBox.information( None, toolname, "Select the geometry you want to see the coordinate list from") return return selected def listAllCoordinates(self, selected): # toDo: loop over all selected geometries aFeature = selected[0] aGeometry = aFeature.geometry() # check different geometry types aType = aGeometry.wkbType() aCoordList = [] if aType == QGis.WKBPoint: aCoordList = [aGeometry.asPoint()] if aType == QGis.WKBLineString: aCoordList = aGeometry.asPolyline() coordString = "" for aCoord in aCoordList: coordX = "{:10.3f}".format(aCoord.x()) coordY = "{:10.3f}".format(aCoord.y()) coordString = coordString + str(coordX) + " , " + str( coordY) + "\n" QMessageBox.information( None, toolname, "Coordinates of selected geometry:\n\n" + coordString) def findTopology(self): ''' find topological related geometries of selected geometry ''' selected = self.checkSelection() if selected: aFeature = selected[0] aGeometry = aFeature.geometry() # check different geometry types aType = aGeometry.wkbType() if aType == QGis.WKBPoint: topoNodeId = self.topologyConnector.get_nodeid_for_point( aFeature) # if topoNodeId: connectedEdgeIds = self.topologyConnector.all_edges_for_node( topoNodeId) relatedLineIds = [] for connectedEdgeId in connectedEdgeIds: # find related line object relatedLineId = self.topologyConnector.get_line_for_edgeid( connectedEdgeId) if relatedLineId: relatedLineIds.append(relatedLineId) # now we could return a list of line object ids. # We still need to find the layer/table name dummy = 0 def listen_layerChanged(self, layer): # listens to change of current layer #QObject.connect(layer, SIGNAL("geometryChanged(QgsFeatureId, const QgsGeometry &)"), self.listen_geometryChange) # does not work self.selectedLayer = layer if layer: layer.geometryChanged.connect(self.listen_geometryChange) def listen_geometryChange(self, fid, geometry): # listens to geometry changes toolname = "Geometry Changed" if fid: idRequest = QgsFeatureRequest(fid) self.selectedFeature = self.selectedLayer.getFeatures(idRequest) QMessageBox.information(None, toolname, "Geometry was changed for " + str(fid))
class ImportBidang: """QGIS Plugin Implementation.""" 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', 'ImportBidang_{}.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 = ImportBidangDialog() # connect slot self.dlg.cboLayer.currentIndexChanged.connect(self.index_changed) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Import Bidang') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'ImportBidang') self.toolbar.setObjectName(u'ImportBidang') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('ImportBidang', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/ImportBidang/icon.png' self.add_action(icon_path, text=self.tr(u'Import Bidang'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Import Bidang'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def daftar_layer(self): """Function to get layer list from table of content :return: list of layer """ daftar_layer = [] for layer in self.iface.mapCanvas().layers(): daftar_layer.append(layer) return daftar_layer def daftar_kolom(self, layer): """Function to get fields list of a layer :param layer: :return: """ self.dlg.cboField.clear() if layer.type() == QgsMapLayer.VectorLayer: layer_fields = layer.pendingFields() for field in layer_fields: self.dlg.cboField.addItem(field.name(), field) def index_changed(self): """Mengakomodir perubahan layer terpilih terhadap daftar field yang akan ditampilkan""" current_index = self.dlg.cboLayer.currentIndex() layer = self.dlg.cboLayer.itemData(current_index) self.daftar_kolom(layer) def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop self.dlg.cboLayer.clear() daftar_layer = self.daftar_layer() for layer in daftar_layer: self.dlg.cboLayer.addItem(layer.name(), layer) result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. selectedLayerIndex = self.dlg.cboLayer.currentIndex() selectedLayer = self.iface.mapCanvas().layers()[selectedLayerIndex] #selectedLayer.setCrs(QgsCoordinateReferenceSystem(32750)) #fields = selectedLayer.pendingFields() fieldname = str(self.dlg.cboField.currentText()) for feature in selectedLayer.getFeatures(): idx = selectedLayer.fieldNameIndex(fieldname) nop = feature.attributes()[idx] geom = feature.geometry() geom_wkt = geom.exportToWkt() #multipolygon = "MULTIPOLYGON(((" geom_wkt_str = geom_wkt[10:-2] #st_geom = """ST_GeomFromText('""" #srid = """)', 32750)""" #geom_wkb_postgis = st_geom + multipolygon +geom_wkt_str + srid #wkb version, just return geometry, doesn't include SRID #geom_wkb = geom.asWkb() #geom_wkb_postgis = geom_wkb.encode('hex') query1 = '''INSERT INTO gis.tm_bidang3(d_nop,geom) VALUES (%s, ST_GeomFromText(%s, 32750));''' #query = """INSERT INTO gis.tm_bidang2(d_nop,geom) VALUES (%s, ST_GeomFromText('MULTIPOLYGON(((%s)))', 32750));""" data = [nop, geom_wkt] #Parameter Connection to database host_name = "localhost" port_name = "5433" db_name = "db_pbb" user_name = "postgres" user_pass = "******" #Connection conn = psycopg2.connect( "user='******' password='******' host='%s' port='%s' dbname='%s'" % (user_name, user_pass, host_name, port_name, db_name)) cur = conn.cursor() cur.execute(query1, data) conn.commit() cur.close() conn.close()
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if sys.platform != 'win32': app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = QSettings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists( file_manager.create_path(resources.LANGS_DOWNLOAD, lang)): settings.LANGUAGE = file_manager.create_path(resources.LANGS_DOWNLOAD, lang) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA__THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE(start_server) #Showing GUI ide.show() #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab main_files = qsettings.value('openFiles/mainTab', []) if main_files is not None: mainFiles = list(main_files) else: mainFiles = list() tempFiles = [] for file_ in mainFiles: fileData = list(file_) if fileData: tempFiles.append((fileData[0], int(fileData[1]))) mainFiles = tempFiles #Files in Secondary Tab sec_files = qsettings.value('openFiles/secondaryTab', []) if sec_files is not None: secondaryFiles = list(sec_files) else: secondaryFiles = list() tempFiles = [] for file_ in secondaryFiles: fileData = list(file_) tempFiles.append((fileData[0], int(fileData[1]))) secondaryFiles = tempFiles # Recent Files recent = qsettings.value('openFiles/recentFiles', []) if recent is not None: recent_files = list(recent) else: recent_files = list() recent_files = [file_ for file_ in recent_files] #Current File current_file = qsettings.value('openFiles/currentFile', '', type='QString') #Projects projects_list = qsettings.value('openFiles/projects', []) if projects_list is not None: projects = list(projects_list) else: projects = list() projects = [project for project in projects] #Include files received from console args file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0) for f in filenames[len(linenos):]]) mainFiles += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects, current_file, recent_files) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() sys.exit(app.exec_())
class ValorInformativo: """QGIS Plugin Implementation.""" 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', 'ValorInformativo_{}.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 = ValorInformativoDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Valor Informativo') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'ValorInformativo') self.toolbar.setObjectName(u'ValorInformativo') self.dlg.lineEdit_2.clear() self.dlg.lineEdit_3.clear() self.dlg.lineEdit_4.clear() self.dlg.lineEdit_5.clear() self.dlg.toolButton_2.clicked.connect(lambda: self.VariavelDependente( self.dlg.lineEdit_2, self.dlg.lineEdit_4)) self.dlg.toolButton_3.clicked.connect(self.SelecionarOutputPath) self.dlg.toolButton_4.clicked.connect( self.SelecionarVariaveisIndependentes) self.dlg.toolButton_5.clicked.connect(self.RemoverVariavelIndependente) self.dlg.toolButton_6.clicked.connect(lambda: self.RasterValidacao( self.dlg.lineEdit_5, self.dlg.lineEdit_6)) # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('ValorInformativo', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToVectorMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/ValorInformativo/icon.png' self.add_action(icon_path, text=self.tr(u'Calcula o Valor Informativo'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginVectorMenu(self.tr(u'&Valor Informativo'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar # PARAMETRO 1 - "VARIAVEIS INDEPENDENTES" def SelecionarVariaveisIndependentes(self): VarIndepInputLista = QFileDialog.getOpenFileNames( self.dlg, "Selecionar um ou mais rasters", "/Users/bsargento/Desktop/TesteVC/DADOS_BASE/", "TIFF / BigTIFF / GeoTIFF (*.tif);;Arc/Info Binary Grid (*.adf)") if VarIndepInputLista is not None: for VarIndepInput in VarIndepInputLista: VarIndepLayerName = os.path.basename(VarIndepInput).rsplit( ".")[0] InFileObject = processing.getObject(VarIndepInput) if InFileObject.type() == QgsMapLayer.RasterLayer: rowPosition = self.dlg.tableWidget.rowCount() self.dlg.tableWidget.insertRow(rowPosition) NrColunas = self.dlg.tableWidget.columnCount() NrLinhas = self.dlg.tableWidget.rowCount() self.dlg.tableWidget.setRowCount(NrLinhas) self.dlg.tableWidget.setColumnCount(NrColunas) self.dlg.tableWidget.setItem( NrLinhas - 1, 0, QTableWidgetItem(VarIndepInput)) self.dlg.tableWidget.setItem( NrLinhas - 1, 1, QTableWidgetItem(VarIndepLayerName)) def RemoverVariavelIndependente(self): self.dlg.tableWidget.currentRow() self.dlg.tableWidget.removeRow(self.dlg.tableWidget.currentRow()) # PARAMETRO 2 - "VARIAVEL DEPENDENTE" def VariavelDependente(self, lineEdit_2, lineEdit_4): VarDepInput = str( QFileDialog.getOpenFileNames( self.dlg, "Selecionar um ficehiro raster", "/Users/bsargento/Desktop/TesteVC/DADOS_BASE/", "TIFF / BigTIFF / GeoTIFF (*.tif);;Arc/Info Binary Grid (*.adf)" )[0]) if VarDepInput is not None: VarDepLayerName = os.path.basename(VarDepInput).rsplit(".")[0] InFileObject = processing.getObject(VarDepInput) if InFileObject.type() == QgsMapLayer.RasterLayer: lineEdit_2.setText(VarDepInput) lineEdit_4.setText(VarDepLayerName) # PARAMETRO 3 - "OUTPUT FOLDER" def SelecionarOutputPath(self): OutputPath = QFileDialog.getExistingDirectory( self.dlg, "Guardar em", "/Users/bsargento/Desktop/") self.dlg.lineEdit_3.setText(OutputPath) # PARAMETRO 4 - "VARIAVEL DE VALIDACAO" def RasterValidacao(self, lineEdit_5, lineEdit_6): RasterValidacaoInput = str( QFileDialog.getOpenFileNames( self.dlg, "Selecionar um ficehiro raster", "/Users/bsargento/Desktop/TesteVC/DADOS_BASE/", "TIFF / BigTIFF / GeoTIFF (*.tif);;Arc/Info Binary Grid (*.adf)" )[0]) if RasterValidacaoInput is not None: VarValidacaoLayerName = os.path.basename( RasterValidacaoInput).rsplit(".")[0] InFileObject = processing.getObject(RasterValidacaoInput) if InFileObject.type() == QgsMapLayer.RasterLayer: lineEdit_5.setText(RasterValidacaoInput) lineEdit_6.setText(VarValidacaoLayerName) # EXECUCAO DO MODELO: def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # CARREGAR VALORES DOS PARAMETROS: #PARAMETRO 1 ListaVarIndep = [] ListaLayerName = [] NrLinhasTabela = self.dlg.tableWidget.rowCount() for Linhas in range(NrLinhasTabela): VarIndepPath = self.dlg.tableWidget.item(Linhas, 0).text() VarIndepLayerName = self.dlg.tableWidget.item(Linhas, 1).text() ListaVarIndep.append(VarIndepPath) ListaLayerName.append(VarIndepLayerName) #PARAMETRO 2 VarDep = self.dlg.lineEdit_2.text() VarDepDisplayName = self.dlg.lineEdit_4.text() #PARAMETRO 3 InputOutputFolder = self.dlg.lineEdit_3.text() #PARAMETRO 4 RasterValidacao = self.dlg.lineEdit_5.text() ValidacaoDisplayName = self.dlg.lineEdit_6.text() # INICIO DOS PROCESSOS: # CRIAR PASTA OUTPUT PastaOutput = os.path.join(InputOutputFolder, "Output") if not os.path.exists(PastaOutput): os.makedirs(PastaOutput) else: for NrPastas in range(1, 10): sufixo = "_" + str(NrPastas) PastaOutput = os.path.join(InputOutputFolder, "Output" + sufixo) if not os.path.exists(PastaOutput): os.makedirs(PastaOutput) break # CRIAR SUBPASTA TABELAS PastaTabelas = os.path.join(PastaOutput, "Tabelas") os.makedirs(PastaTabelas) # CARREGAR VARIAVEL DEPENDENTE E ADICIONAR LAYER AO QGIS LoadVarDep = QgsRasterLayer(VarDep, VarDepDisplayName) ListaVarIndepVI = [] # PROPRIEDADES DOS FICHEIROS DE INPUT for VarIndep, VarIndepLayerName in zip(ListaVarIndep, ListaLayerName): # CARREGAR VARIAVEL INDEPENDENTE E ADICIONAR LAYER AO QGIS LoadVarIndep = QgsRasterLayer(VarIndep, VarIndepLayerName) AddVarIndep = QgsMapLayerRegistry.instance().addMapLayer( LoadVarIndep) # DEFINIR EXTENSAO ext = AddVarIndep.extent() xmin = ext.xMinimum() xmax = ext.xMaximum() ymin = ext.yMinimum() ymax = ext.yMaximum() Mask = "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax) # DEFINIR CELL SIZE PixelSizeX = LoadVarIndep.rasterUnitsPerPixelX() PixelSizeY = LoadVarIndep.rasterUnitsPerPixelY() CellSize = PixelSizeX * PixelSizeY # CRIAR REPORT E CALCULAR VALORES UNICOS CountUniqueValues = os.path.join( PastaTabelas, VarIndepLayerName + "_CountUniqueValues.txt") processing.runalg("grass7:r.report", VarIndep, 5, "*", 255, True, True, True, True, Mask, None, CountUniqueValues) ReportReadLines = open(CountUniqueValues).readlines() ReportSelectLines = ReportReadLines[4:-4] UniqueValues = len(ReportSelectLines) # DEFINIR CAMINHO DO OUTPUT E EXECUTAR R.COIN RCoinFile = os.path.join( PastaTabelas, VarIndepLayerName + "_x_" + VarDepDisplayName + "_Original.txt") processing.runalg("grass7:r.coin", VarIndep, VarDep, 0, False, Mask, None, RCoinFile) # LER RCOINFILE E SELECIONAR AS LINHAS COM INFORMACAO UTIL ReadLines = open(RCoinFile).readlines() SelectLines = ReadLines[22:UniqueValues + 22] # FORMATAR DADOS PARA IMPORTACAO EM CSV ListaValores = [] for row in SelectLines: RemoverEspacos = re.sub(' +', ' ', row) SubstituirEspacos = RemoverEspacos.replace(' ', ';') SepararPontoVirgula = SubstituirEspacos.split(";") SelecionarColunas = itemgetter(1, 3, 5, 7)(SepararPontoVirgula) JuntarColunas = ';'.join(SelecionarColunas) ListaValores.append(JuntarColunas) if UniqueValues <= 2: JuntarLinhas = ';'.join(ListaValores) SepararValores = JuntarLinhas.split(";") ConversaoInteiros = map(int, SepararValores) Linha0 = "V;V0;V1;T\n" Linha1 = str(ConversaoInteiros[0] + 1) + ";" + str( ConversaoInteiros[1]) + ";" + str( ConversaoInteiros[5]) + ";" + str( ConversaoInteiros[1] + ConversaoInteiros[5]) + "\n" Linha2 = str(ConversaoInteiros[4] + 1) + ";" + str( ConversaoInteiros[2]) + ";" + str( ConversaoInteiros[6]) + ";" + str( ConversaoInteiros[2] + ConversaoInteiros[6]) ValoresImportar = [Linha0, Linha1, Linha2] else: ListaValores.insert(0, 'V;V0;V1;T') ValoresImportar = '\n'.join(ListaValores) # ESCREVER DADOS FORMATADOS NUM NOVO FICHEIRO TXT RCoinTemp = os.path.join( PastaTabelas, VarIndepLayerName + "_x_" + VarDepDisplayName + "_Tratado.txt") open(RCoinTemp, 'wb').writelines(ValoresImportar) # IMPORTAR PARA FICHEIRO CSV TabulateAreaCSV = os.path.join( PastaTabelas, VarIndepLayerName + "_x_" + VarDepDisplayName + ".csv") csv.writer(open(TabulateAreaCSV, 'wb')).writerows( csv.reader(open(RCoinTemp, 'rb'))) # EXPORTAR PARA DBF LoadTabulateAreaCSV = QgsVectorLayer( TabulateAreaCSV, VarIndepLayerName + "_x_" + VarDepDisplayName, "ogr") DbfTablePath = os.path.join( PastaTabelas, VarIndepLayerName + "_x_" + VarDepDisplayName) QgsVectorFileWriter.writeAsVectorFormat( LoadTabulateAreaCSV, DbfTablePath, "System", None, "ESRI Shapefile") os.remove(DbfTablePath + ".prj") os.remove(DbfTablePath + ".qpj") # CARREGAR TABELA DBF PARA o QGIS DbfTable = QgsVectorLayer( DbfTablePath + ".dbf", VarIndepLayerName + "_x_" + VarDepDisplayName + ".dbf", "ogr") AddDbfTable = QgsMapLayerRegistry.instance().addMapLayer( DbfTable) # OBTER INDEXs DOS CAMPOS EXISTENTES IndexCampoV = DbfTable.fieldNameIndex("V") IndexCampoV0 = DbfTable.fieldNameIndex("V0") IndexCampoV1 = DbfTable.fieldNameIndex("V1") IndexCampoT = DbfTable.fieldNameIndex("T") # CRIAR CAMPOS A CALCULAR CampoVALUE = DbfTable.dataProvider().addAttributes( [QgsField("VALUE", QVariant.Int)]) CampoVALUE_0 = DbfTable.dataProvider().addAttributes( [QgsField("VALUE_0", QVariant.Int)]) CampoVALUE_1 = DbfTable.dataProvider().addAttributes( [QgsField("VALUE_1", QVariant.Int)]) CampoARCLASSE = DbfTable.dataProvider().addAttributes( [QgsField("ARCLASSE", QVariant.Int)]) CampoPROBCOND = DbfTable.dataProvider().addAttributes( [QgsField("PROBCOND", QVariant.Double)]) CampoSUM_VALUE0 = DbfTable.dataProvider().addAttributes( [QgsField("SUM_VALUE0", QVariant.Int)]) CampoSUM_VALUE1 = DbfTable.dataProvider().addAttributes( [QgsField("SUM_VALUE1", QVariant.Int)]) CampoAR_TOTAL = DbfTable.dataProvider().addAttributes( [QgsField("AR_TOTAL", QVariant.Int)]) CampoPRIORI = DbfTable.dataProvider().addAttributes( [QgsField("PRIORI", QVariant.Double)]) CampoSINI_SN = DbfTable.dataProvider().addAttributes( [QgsField("SINI_SN", QVariant.Double)]) CampoVI = DbfTable.dataProvider().addAttributes( [QgsField("VI", QVariant.Double)]) DbfTable.updateFields() # OBTER INDEXs DOS CAMPOS CRIADOS IndexCampoVALUE = DbfTable.fieldNameIndex("VALUE") IndexCampoVALUE_0 = DbfTable.fieldNameIndex("VALUE_0") IndexCampoVALUE_1 = DbfTable.fieldNameIndex("VALUE_1") IndexCampoARCLASSE = DbfTable.fieldNameIndex("ARCLASSE") IndexCampoPROBCOND = DbfTable.fieldNameIndex("PROBCOND") IndexCampoSUM_VALUE0 = DbfTable.fieldNameIndex("SUM_VALUE0") IndexCampoSUM_VALUE1 = DbfTable.fieldNameIndex("SUM_VALUE1") IndexCampoAR_TOTAL = DbfTable.fieldNameIndex("AR_TOTAL") IndexCampoPRIORI = DbfTable.fieldNameIndex("PRIORI") IndexCampoSINI_SN = DbfTable.fieldNameIndex("SINI_SN") IndexCampoVI = DbfTable.fieldNameIndex("VI") # COPIAR VALORES PARA OS CAMPOS BASE DbfTable.startEditing() for Valores in processing.features(DbfTable): DbfTable.changeAttributeValue(Valores.id(), IndexCampoVALUE, Valores[IndexCampoV]) DbfTable.changeAttributeValue( Valores.id(), IndexCampoVALUE_0, int(Valores[IndexCampoV0]) * CellSize) DbfTable.changeAttributeValue( Valores.id(), IndexCampoVALUE_1, int(Valores[IndexCampoV1]) * CellSize) DbfTable.changeAttributeValue( Valores.id(), IndexCampoARCLASSE, int(Valores[IndexCampoT]) * CellSize) DbfTable.commitChanges() DbfTable.updateFields() ListaVALUE_0 = [] ListaVALUE_1 = [] DbfTable.startEditing() for Valores in processing.features(DbfTable): DbfTable.changeAttributeValue( Valores.id(), IndexCampoPROBCOND, float(Valores[IndexCampoVALUE_1]) / float(Valores[IndexCampoARCLASSE])) ListaVALUE_0.append(int(Valores[IndexCampoVALUE_0])) ListaVALUE_1.append(int(Valores[IndexCampoVALUE_1])) DbfTable.commitChanges() DbfTable.updateFields() # CALCULAR CAMPOS 'SUM_VALUE0' e 'SUM_VALUE1' SomaVALUE_0 = sum(ListaVALUE_0) SomaVALUE_1 = sum(ListaVALUE_1) DbfTable.startEditing() for Valores in processing.features(DbfTable): DbfTable.changeAttributeValue(Valores.id(), IndexCampoSUM_VALUE0, SomaVALUE_0) DbfTable.changeAttributeValue(Valores.id(), IndexCampoSUM_VALUE1, SomaVALUE_1) DbfTable.commitChanges() DbfTable.updateFields() # CALCULAR CAMPO 'AR_TOTAL' DbfTable.startEditing() [ DbfTable.changeAttributeValue( Valores.id(), IndexCampoAR_TOTAL, float(Valores[IndexCampoSUM_VALUE0]) + float(Valores[IndexCampoSUM_VALUE1])) for Valores in processing.features(DbfTable) ] DbfTable.commitChanges() DbfTable.updateFields() # CALCULAR CAMPO 'PRIORI' DbfTable.startEditing() [ DbfTable.changeAttributeValue( Valores.id(), IndexCampoPRIORI, float(Valores[IndexCampoSUM_VALUE1]) / float(Valores[IndexCampoAR_TOTAL])) for Valores in processing.features(DbfTable) ] DbfTable.commitChanges() DbfTable.updateFields() # CALCULAR CAMPO 'SINI_SN' DbfTable.startEditing() [ DbfTable.changeAttributeValue( Valores.id(), IndexCampoSINI_SN, float(Valores[IndexCampoPROBCOND]) / float(Valores[IndexCampoPRIORI])) for Valores in processing.features(DbfTable) ] DbfTable.commitChanges() DbfTable.updateFields() # CALCULAR CAMPO 'VI' DbfTable.startEditing() ListaVI_Min = [] for Valores in processing.features(DbfTable): if float(Valores[IndexCampoSINI_SN]) > 0: DbfTable.changeAttributeValue( Valores.id(), IndexCampoVI, math.log(float(Valores[IndexCampoSINI_SN]))) ListaVI_Min.append( math.log(float(Valores[IndexCampoSINI_SN]))) ListaVI_Min.sort() VI_MIN = (ListaVI_Min[0]) for Valores in processing.features(DbfTable): if float(Valores[IndexCampoSINI_SN]) == 0: DbfTable.changeAttributeValue(Valores.id(), IndexCampoVI, float(VI_MIN)) DbfTable.commitChanges() DbfTable.updateFields() # CRIAR EXPRESSAO E FICHEIRO TXT PARA RECLASSIFICACAO COM VALORES DE VI ListaReclass = [] for Valores in processing.features(DbfTable): ListaReclass.append( str(Valores[IndexCampoVALUE]) + "=" + str(int(round(Valores[IndexCampoVI], 9) * (10**8)))) ExpressaoReclass = '\n'.join(ListaReclass) ReclassVITxt = os.path.join( PastaTabelas, VarIndepLayerName + "_ReclassVI.txt") open(ReclassVITxt, 'wb').writelines(ExpressaoReclass) # RECLASSIFICACAO DAS VARIAVEIS INDEPENDENTES COM VALORES DE VI VarIndepVI = os.path.join(PastaOutput, VarIndepLayerName + "_VI.tif") processing.runalg("grass7:r.reclass", VarIndep, ReclassVITxt, Mask, 0, VarIndepVI) ListaVarIndepVI.append(VarIndepVI) # APAGAR CAMPOS INICIAIS PROVENIENTES DO CSV DbfTable.dataProvider().deleteAttributes( [IndexCampoV, IndexCampoV0, IndexCampoV1, IndexCampoT]) DbfTable.updateFields() # REMOVER VARIAVEIS INDEPENDENTES DO QGIS QgsMapLayerRegistry.instance().removeMapLayers( [AddVarIndep.id()]) # SOMAR RASTERS DAS VARIAVEIS INDEPENDENTES NO RASTER CALCULATOR PARA OBTER O MAPA VI FINAL EntriesVIRaster = [] ListaVIRasterRef = [] for Index, VarIndepVI, VarIndepLayerName in zip( range(0, len(ListaVarIndepVI)), ListaVarIndepVI, ListaLayerName): LoadVarIndepVI = QgsRasterLayer(VarIndepVI, VarIndepLayerName + "_VI") AddVarIndepVI = QgsMapLayerRegistry.instance().addMapLayer( LoadVarIndepVI) VIRasterObject = processing.getObject(ListaVarIndepVI[Index]) VIRaster = QgsRasterCalculatorEntry() VIRaster.raster = VIRasterObject VIRaster.ref = str(VarIndepLayerName + '_VI@1') VIRaster.bandNumber = 1 EntriesVIRaster.append(VIRaster) ListaVIRasterRef.append(VIRaster.ref) ExpressaoCalculateVI = "(" + " + ".join(ListaVIRasterRef) + ")" VI = os.path.join(PastaOutput, "VI.tif") CalculateVI = QgsRasterCalculator(ExpressaoCalculateVI, VI, 'GTiff', VIRasterObject.extent(), VIRasterObject.width(), VIRasterObject.height(), EntriesVIRaster) CalculateVI.processCalculation() # ADICIONAR RASTER DO VALOR INFORMATIVO AO QGIS LoadVI = QgsRasterLayer(VI, "VI") AddVI = QgsMapLayerRegistry.instance().addMapLayer(LoadVI) ####VALIDACAO:#### # CONVERTER RASTER DO VI PARA VALORES INTEIROS VIint = os.path.join(PastaOutput, "VIint.tif") processing.runalg("gdalogr:rastercalculator", VI, "1", None, "1", None, "1", None, "1", None, "1", None, "1", "rint(A)", "", 4, "", VIint) # CRIAR REPORT E CALCULAR VALORES UNICOS DE VI VI_CountUniqueValues = os.path.join(PastaTabelas, "VI_CountUniqueValues.txt") processing.runalg("grass7:r.report", VIint, 5, "*", 255, True, True, True, True, Mask, None, VI_CountUniqueValues) VI_ReportReadLines = open(VI_CountUniqueValues).readlines() VI_ReportSelectLines = VI_ReportReadLines[4:-4] VI_UniqueValues = len(VI_ReportSelectLines) # DEFINIR CAMINHO DO OUTPUT E EXECUTAR R.COIN DE VALIDACAO VI_RCoin = os.path.join( PastaTabelas, "VI_x_" + ValidacaoDisplayName + "_Original.txt") processing.runalg("grass7:r.coin", VIint, RasterValidacao, 0, False, Mask, None, VI_RCoin) # LER VI_RCOIN E SELECIONAR AS LINHAS COM INFORMACAO UTIL ValidacaoReadLines = open(VI_RCoin).readlines() ValidacaoSelectLines = ValidacaoReadLines[22:VI_UniqueValues + 22] # FORMATAR DADOS PARA IMPORTACAO EM CSV ValidacaoListaValores = [] for row in ValidacaoSelectLines: RemoverEspacos = re.sub(' +', ' ', row) SubstituirEspacos = RemoverEspacos.replace(' ', ';') SepararPontoVirgula = SubstituirEspacos.split(";") SelecionarColunas = itemgetter(1, 5, 7)(SepararPontoVirgula) ConversaoInteiros = map(int, SelecionarColunas) ValidacaoListaValores.append(ConversaoInteiros) ValidacaoListaValores = sorted(ValidacaoListaValores, reverse=True) ListaOrdenada = [] for row in ValidacaoListaValores: SubstituirEspacos = str(row).replace(', ', ';') RemoverParentese1 = SubstituirEspacos.replace('[', '') RemoverParentese2 = RemoverParentese1.replace(']', '') ListaOrdenada.append(RemoverParentese2) ListaOrdenada.insert(0, 'V;V1;T') ValidacaoValoresImportar = '\n'.join(ListaOrdenada) # ESCREVER DADOS FORMATADOS NUM NOVO FICHEIRO TXT VI_RCoinTemp = os.path.join( PastaTabelas, "VI_x_" + ValidacaoDisplayName + "_Tratado.txt") open(VI_RCoinTemp, 'wb').writelines(ValidacaoValoresImportar) # IMPORTAR PARA FICHEIRO CSV TS_CSV = os.path.join(PastaTabelas, "VI_x_" + ValidacaoDisplayName + ".csv") csv.writer(open(TS_CSV, 'wb')).writerows( csv.reader(open(VI_RCoinTemp, 'rb'))) # EXPORTAR PARA DBF LoadTSCSV = QgsVectorLayer(TS_CSV, "TS", "ogr") DbfTSPath = os.path.join(PastaTabelas, "TS") QgsVectorFileWriter.writeAsVectorFormat(LoadTSCSV, DbfTSPath, "System", None, "ESRI Shapefile") os.remove(DbfTSPath + ".prj") os.remove(DbfTSPath + ".qpj") # CARREGAR TABELA DBF PARA o QGIS DbfTS = QgsVectorLayer(DbfTSPath + ".dbf", "TS.dbf", "ogr") AddDbfTS = QgsMapLayerRegistry.instance().addMapLayer(DbfTS) # OBTER INDEXs DOS CAMPOS EXISTENTES TS_IndexCampoV = DbfTS.fieldNameIndex("V") TS_IndexCampoV1 = DbfTS.fieldNameIndex("V1") TS_IndexCampoT = DbfTS.fieldNameIndex("T") # CRIAR CAMPOS A CALCULAR TS_CampoVI = DbfTS.dataProvider().addAttributes( [QgsField("VI", QVariant.Double)]) TS_CampoARESTUDO = DbfTS.dataProvider().addAttributes( [QgsField("ARESTUDO", QVariant.Int)]) TS_CampoARFENOM = DbfTS.dataProvider().addAttributes( [QgsField("ARFENOM", QVariant.Int)]) TS_CampoArEstudAc = DbfTS.dataProvider().addAttributes( [QgsField("ArEstudAc", QVariant.Double)]) TS_CampoArFenomAc = DbfTS.dataProvider().addAttributes( [QgsField("ArFenomAc", QVariant.Double)]) TS_CampoLsi_Li = DbfTS.dataProvider().addAttributes( [QgsField("Lsi_Li", QVariant.Double)]) TS_Campoai_b1_2 = DbfTS.dataProvider().addAttributes( [QgsField("ai_b1_2", QVariant.Double)]) TS_CampoACC = DbfTS.dataProvider().addAttributes( [QgsField("ACC", QVariant.Double)]) DbfTS.updateFields() # OBTER INDEXs DOS CAMPOS CRIADOS TS_IndexCampoVI = DbfTS.fieldNameIndex("VI") TS_IndexCampoARESTUDO = DbfTS.fieldNameIndex("ARESTUDO") TS_IndexCampoARFENOM = DbfTS.fieldNameIndex("ARFENOM") TS_IndexCampoArEstudAc = DbfTS.fieldNameIndex("ArEstudAc") TS_IndexCampoArFenomAc = DbfTS.fieldNameIndex("ArFenomAc") TS_IndexCampoLsi_Li = DbfTS.fieldNameIndex("Lsi_Li") TS_IndexCampoai_b1_2 = DbfTS.fieldNameIndex("ai_b1_2") TS_IndexCampoACC = DbfTS.fieldNameIndex("ACC") # COPIAR VALORES PARA OS CAMPOS BASE DbfTS.startEditing() for Valores in processing.features(DbfTS): DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoVI, float(Valores[TS_IndexCampoV]) / float(10**8)) DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoARESTUDO, int(Valores[TS_IndexCampoT]) * CellSize) DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoARFENOM, int(Valores[TS_IndexCampoV1]) * CellSize) DbfTS.commitChanges() DbfTS.updateFields() # CPRIAR LISTAS DE VALORES PARA AS SOMAS ACUMULADAS ListaARESTUDO = [] ListaARFENOM = [] for Valores in processing.features(DbfTS): ListaARESTUDO.append(int(Valores[TS_IndexCampoARESTUDO])) ListaARFENOM.append(int(Valores[TS_IndexCampoARFENOM])) # CALCULAR CAMPOS 'ArEstudAc', 'ArFenomAc' SomaARESTUDO = sum(ListaARESTUDO) SomaARFENOM = sum(ListaARFENOM) DbfTS.startEditing() for Valores, SomaAcARESTUDO, SomaAcARFENOM in zip( processing.features(DbfTS), numpy.cumsum(ListaARESTUDO), numpy.cumsum(ListaARFENOM)): if Valores.id() == 0: DbfTS.changeAttributeValue(Valores.id(), TS_IndexCampoArFenomAc, 0) DbfTS.changeAttributeValue(Valores.id(), TS_IndexCampoArEstudAc, 0) else: DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoArEstudAc, float(SomaAcARESTUDO) / float(SomaARESTUDO)) DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoArFenomAc, float(SomaAcARFENOM) / float(SomaARFENOM)) DbfTS.commitChanges() # CALCULAR CAMPOS 'Lsi_Li', 'ai_b1_2' ListaArEstudAc = [] ListaArFenomAc = [] for Valores in processing.features(DbfTS): ListaArEstudAc.append(float(Valores[TS_IndexCampoArEstudAc])) ListaArFenomAc.append(float(Valores[TS_IndexCampoArFenomAc])) ListaArEstudAc.insert(0, 0) ListaArFenomAc.insert(0, 0) DbfTS.startEditing() for Valores, ValoresArEstudAc, ValoresArFenomAc in zip( processing.features(DbfTS), ListaArEstudAc, ListaArFenomAc): if Valores.id() == 0: DbfTS.changeAttributeValue(Valores.id(), TS_IndexCampoLsi_Li, 0) DbfTS.changeAttributeValue(Valores.id(), TS_IndexCampoai_b1_2, 0) else: DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoLsi_Li, float(Valores[TS_IndexCampoArEstudAc]) - float(ValoresArEstudAc)) DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoai_b1_2, float( float(Valores[TS_IndexCampoArFenomAc]) + float(ValoresArFenomAc)) / float(2)) DbfTS.commitChanges() # CALCULAR CAMPO 'AAC' DbfTS.startEditing() for Valores in processing.features(DbfTS): DbfTS.changeAttributeValue( Valores.id(), TS_IndexCampoACC, float(Valores[TS_IndexCampoai_b1_2]) * float(Valores[TS_IndexCampoLsi_Li])) DbfTS.commitChanges() # SOMAR VALORES DE ACC PARA ESCREVER A MENSAGEM ListaACC = [] for Valores in DbfTS.getFeatures(): ListaACC.append(Valores[TS_IndexCampoACC]) SomaACC = round(sum(ListaACC), 4) # APAGAR CAMPOS INICIAIS PROVENIENTES DO CSV DbfTS.dataProvider().deleteAttributes( [TS_IndexCampoV, TS_IndexCampoV1, TS_IndexCampoT]) DbfTS.updateFields() msgBar = self.iface.messageBar() msgBar.pushWidget( msgBar.createMessage( "########### O MODELO FOI VALIDADO COM UMA TAXA DE SUCESSO DE " + str(SomaACC) + "! ###########"), QgsMessageBar.INFO ) #"...INFO, 5)" para defenir o tempo da mensagem
class skkn_tool: def __init__(self, iface): # 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', 'skkn_tool_{}.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 = skkn_toolDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&SKKN tool') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'skkn_tool') self.toolbar.setObjectName(u'skkn_tool') # data self.dlg.buttonConvert.setEnabled(False) self.dlg.lineData.clear() self.dlg.buttonData.clicked.connect(self.select_data) # database and schema self.dlg.dataBase.setEnabled(False) self.dlg.comboBox_2.currentIndexChanged.connect(self.db_changed) # conversation self.dlg.progressBarData.setMinimum(0) self.dlg.progressBarData.setMaximum(100) self._active = False self.dlg.buttonConvert.clicked.connect(self.convertData) # ukoncenie konverzie self.dlg.buttonKill.clicked.connect(self.stopConvert) self.dlg.buttonKill.setEnabled(False) # about message self.dlg.buttonAbout.clicked.connect(self.showError) self.dlg.buttonClear.clicked.connect(self.clear) # nieco ako Popen, nativne pre Qt self.process = QProcess(self.dlg) self.process.readyRead.connect(self.writeData) # vytvorenie schemy self.dlg.buttonCreate.clicked.connect(self.db_createSchema) # import dat do schemy self.dlg.buttonImport.clicked.connect(self.db_importToSchema) # vymazanie schemy self.dlg.buttonDelete.clicked.connect(self.db_deleteSchema) # test self.dlg.buttonTest.setEnabled(False) self.dlg.buttonTest.clicked.connect(self.testImport) # cancel self.dlg.buttonCancel.clicked.connect(self.closelt) # noinspection PyMethodMayBeStatic def tr(self, message): # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('skkn_tool', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/skkn_tool/icons/icon.png' self.add_action(icon_path, text=self.tr(u'SKKN tool'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&SKKN tool'), action) self.iface.removeToolBarIcon(action) # remove the toolbarself.dlg.dataBase.setEnabled(False) del self.toolbar def select_data(self): self.foldername = QFileDialog.getExistingDirectory( self.dlg, "Select data folder with SPI and VGI data", "/home") # nahradenie v pripade medzery # self.foldername = re.sub('\s+', '', self.foldername) # self.foldername = os.rename(self.foldername,self.foldername) self.dlg.lineData.setText(self.foldername) self.buttonConvertName() self.dlg.buttonConvert.setEnabled(True) self.dlg.progressBarData.setValue(0) self.clear() def convertData(self): #self.dlg.textEditData.setText(self.foldername) ## spustenie pomocou call a Popen # subprocess.call([os.path.join(self.plugin_dir,'kataster-import','kt-sql'),self.foldername]) # subprocess.Popen([os.path.join(self.plugin_dir,'kataster-import','kt-sql'),self.foldername],shell = True) self.clear() self.process.start( os.path.join(self.plugin_dir, 'kataster-import', 'kt-sql'), [self.foldername]) self.dlg.buttonConvert.setText('Converting ...') self.dlg.buttonKill.setEnabled(True) #funkcia na zapisovanie do GUI okna, vola funkciu insertText def writeData(self): text = str(self.process.readAll()) for line in text.splitlines(): if len(line) == 0: continue if not line.startswith('PROGRESS'): self.insertText(line + os.linesep) else: try: self.pvalue = int(line.split(':', 1)[1].strip()) except: return self.dlg.progressBarData.setValue(self.pvalue) if self.pvalue == 100: self.dlg.buttonConvert.setText( 'Conversation successfully completed') self.dlg.buttonConvert.setEnabled(False) self.dlg.buttonKill.setEnabled(False) self.dlg.dataBase.setEnabled(True) def insertText(self, text): cursor = self.dlg.textEditData.textCursor() cursor.movePosition(cursor.End) cursor.insertText(text) self.dlg.textEditData.ensureCursorVisible() def stopConvert(self): self.process.kill() self.clear() self.insertText('Conversation interrupted!') self.buttonConvertName() self.dlg.buttonKill.setEnabled(False) self.dlg.progressBarData.setValue(0) def buttonConvertName(self): self.dlg.buttonConvert.setText('Convert all data') def db_changed(self, index): self.dlg.comboBox_3.clear() self.clear() self.dlg.comboBox_3.addItems(self.db_getSchema(index)) # naplnenie comboboxu schemami def db_getSchema(self, index): schemas = [] self.dbconn = self.dbconnections[index] self.dbconn.connect() # zabraniene zobrazeniu schem public a topology for schema in self.dbconn.database().schemas(): if schema.name in ('public', 'topology'): continue schemas.append(schema.name) return schemas # vytvorenie novej schemy kataster def db_createSchema(self): self.clear() db = self.dlg.comboBox_2.currentText() schema = self.dlg.comboBox_3.currentText() if not schema == 'kataster': s = os.path.join(self.plugin_dir, 'kataster-import', 'kt-vytvor_db') + ' | ' + 'psql' + ' ' + db call(s, shell=True) self.insertText( 'New schema and related SQL statements have been created successfully.\nTo see schema in combo box refresh database connection!\n\n' ) else: self.insertText('Schema already exists.') def db_importToSchema(self): self.clear() db = self.dlg.comboBox_2.currentText() s = self.dlg.comboBox_3.currentText() gsql = os.path.join(self.foldername, 'sql', 'graficke_udaje.sql') psql = os.path.join(self.foldername, 'sql', 'popisne_udaje.sql') glog = os.path.join(self.plugin_dir, 'kataster-import', 'info_g.log') plog = os.path.join(self.plugin_dir, 'kataster-import', 'info_p.log') self.goptions = "PGOPTIONS='-c search_path=%s,public' psql %s -f %s 2>%s" % ( s, db, gsql, glog) call(self.goptions, shell=True) #self.insertText(os.path.join(self.plugin_dir,'kataster-import') + self.goptions) self.poptions = "PGOPTIONS='-c search_path=%s,public' psql %s -f %s 2>%s" % ( s, db, psql, plog) call(self.poptions, shell=True) self.writeLog() self.dlg.buttonTest.setEnabled(True) #funkcia na výpis log do GUI pri tvorbe schemy def writeLog(self): gfilelog = os.path.join(self.plugin_dir, 'kataster-import', 'info_g.log') gtext = open(gfilelog).read() pfilelog = os.path.join(self.plugin_dir, 'kataster-import', 'info_p.log') ptext = open(pfilelog).read() self.insertText('GRAPHICAL DATA LOG:\n**********************\n') self.logText(gfilelog, gtext) self.insertText('\nATTRIBUTIVE DATA LOG:\n************************\n') self.logText(pfilelog, ptext) # vymazanie LOG pre graficke a popisne data os.remove(gfilelog) os.remove(pfilelog) # testovanie prazdneho log suboru def logText(self, file, opfile): if (os.stat(file).st_size == 0 or os.stat(file).st_size == 1): self.insertText( 'Import has been successfully finished with no message.') else: for line in opfile.splitlines(): if len(line) == 0: continue else: self.insertText(line + os.linesep) def testImport(self): self.clear() db = self.dlg.comboBox_2.currentText() s = self.dlg.comboBox_3.currentText() tsql = os.path.join(self.plugin_dir, 'kataster-import', 'katastertools', 'sql', 'test-import.sql') tlog = os.path.join(self.plugin_dir, 'kataster-import', 'info_t.log') self.toptions = "PGOPTIONS='-c search_path=%s,public' psql %s -f %s > %s 2>&1" % ( s, db, tsql, tlog) call(self.toptions, shell=True) tfilelog = os.path.join(self.plugin_dir, 'kataster-import', 'info_t.log') ttext = open(tfilelog).read() self.insertText( 'TEST LOG related to imported data:\n**********************************\n' ) if (os.stat(tfilelog).st_size == 0 or os.stat(tfilelog).st_size == 1): self.insertText('Unfortunately, there are no results.') else: for line in ttext.splitlines(): if len(line) == 0: continue else: self.insertText(line + os.linesep) # vymazanie TEST LOG os.remove(tfilelog) # vymazanie schemy def db_deleteSchema(self): # vycistenie dialógu so správami self.clear() index = self.dlg.comboBox_3.currentIndex() schema = self.dlg.comboBox_3.currentText() db = self.dbconn.database() # vlozenie chybovej hlasky v pripade problemu try: db.sqlResultModel('DROP schema {0} CASCADE'.format(schema), db) except DbError as e: self.insertText(str(e)) # vymazanie z comboboxu self.dlg.comboBox_3.removeItem(index) def showError(self): QMessageBox.about( None, "About SKKN Plugin", "This tool helps users to use Slovak land \ registry data (cadastral data) in exchange formats created by The Geodesy, Cartography and \ Cadastre Authority of Slovak republic, in QGIS. \nIt is only usefull and dedicated for processing \ in Slovak republic for people having access to Cadastre data. \nThere is no reason to use it for \ other purposes.") def clear(self): self.dlg.textEditData.clear() def closelt(self): self.dlg.close() def run(self): # add connections to combobox self.dlg.comboBox_2.clear() dbpluginclass = createDbPlugin('postgis') connection_list = [] self.dbconnections = dbpluginclass.connections() for c in self.dbconnections: connection_list.append(unicode(c.connectionName())) c.connect() self.dlg.comboBox_2.addItems(connection_list) dbpluginclass.typeName() # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class SwitchesAlarms: """QGIS Plugin Implementation.""" 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 """ self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) self.layer = None self.data_list = None self.check_table_info = None self.stop = False self.timer_restart = 0 # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'SwitchesAlarms_{}.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.city = '' self.actions = [] self.menu = self.tr(u'&Switches Alarms') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'SwitchesAlarms') self.toolbar.setObjectName(u'SwitchesAlarms') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('SwitchesAlarms', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ # Create the dialog (after translation) and keep reference self.dlg = SwitchesAlarmsDialog() icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/SwitchesAlarms/icon.png' self.add_action(icon_path, text=self.tr(u'Switches Alarms'), callback=self.run, parent=self.iface.mainWindow()) def search_city_name(self): for item in QgsMapLayerRegistry.instance().mapLayers(): if '_ctv_topology' in item: self.city = item[0:item.find('_')] def surch_data(self): project = QgsProject.instance() with open(project.fileName()) as f: content = f.readlines() for line in content: if ("datasource" in line) & ("host" in line) & ("port" in line) & ( "user" in line): list_properties = line.split(" ") break def searching(i): if "'" in i: find = i[i.find("=") + 2:len(i) - 1:] else: find = i[i.find("=") + 1::] return find final_list = [] for i in list_properties: if "host" in i: final_list.append(searching(i)) if "port" in i: final_list.append(searching(i)) if "user" in i: final_list.append(searching(i)) if "password" in i: final_list.append(searching(i)) newstr = "dbname='postgres' host=" + final_list[ 0] + " port=" + final_list[1] + " user="******" password="******"SELECT street, cubic_house_num, doorway, ip_address, switch_model, mon_ping_state,mon_ports_state, mon_traffic_state,mon_ping_ignore FROM " + self.city + "." + self.city + "_switches_working where mon_ping_state is not NULL or mon_traffic_state is not NULL" ) self.check_table_info = query_db("SELECT mon_traffic_state FROM " + self.city + "." + self.city + "_switches_working LIMIT 1 ") def dbData(self): self.dlg.objectBrowser.clear() for i in self.data_list: if i['mon_traffic_state'] == '0': i['mon_traffic_state'] = 'noTRAFF' elif i['mon_traffic_state'] == '1': i['mon_traffic_state'] = 'bothTRAFF' elif i['mon_traffic_state'] == '2': i['mon_traffic_state'] = 'parentTRAFF' elif i['mon_traffic_state'] == '3': i['mon_traffic_state'] = 'childTRAFF' elif i['mon_traffic_state'] == '' or i['mon_traffic_state'] == None: i['mon_traffic_state'] = 'None' if i['mon_ports_state'] == '0': i['mon_ports_state'] = 'allDOWN' elif i['mon_ports_state'] == '1': i['mon_ports_state'] = 'bothUP' elif i['mon_ports_state'] == '2': i['mon_ports_state'] = 'parentUP' elif i['mon_ports_state'] == '3': i['mon_ports_state'] = 'childUP' elif i['mon_ports_state'] == '' or i['mon_traffic_state'] == None: i['mon_ports_state'] = 'None' if i['mon_ping_ignore'] == '0': i['mon_ping_state'] = 'ignore' else: if i['mon_ping_state'] == '0': i['mon_ping_state'] = 'NOping' elif i['mon_ping_state'] == '1': i['mon_ping_state'] = 'pingOK' elif i['mon_ping_state'] == '': i['mon_ping_state'] = 'Empty' elif i['mon_ping_state'] == '' or i['mon_ping_state'] == None: i['mon_ping_state'] = 'None' if i['doorway'] == None: i['doorway'] = 'Empty' newItem = QTreeWidgetItem([ i['street'], i['cubic_house_num'], i['doorway'], i['ip_address'], i['switch_model'], i['mon_ping_state'], i['mon_traffic_state'], i['mon_ports_state'] ]) self.dlg.objectBrowser.addTopLevelItem(newItem) self.dlg.stateLabel.setText('work') ''' if self.stop: self.timer= 299 while self.timer> 0: sec = '' if int(self.timer%60) < 10 : sec = '0' + str(int(self.timer%60)) else : sec = str(int(self.timer%60)) self.dlg.stateLabel.setText("Time to restart..." + str(int(self.timer//60)) + ":" + sec + " min") time.sleep(1.0) self.timer= self.timer-1.0 if self.stop : self.dlg.stateLabel.setText("restart...") self.dlg.objectBrowser.clear() self.startSlot() ''' def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Switches Alarms'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def stopSlot(self): self.dlg.stateLabel.setText('stopped') pass def startSlot(self): pass def onMapSlot(self, action): for i in self.switches_all: if unicode(i["ip_address"]) == unicode(action.text(3)): ids = [] ids.append(i.id()) self.iface.mapCanvas().setSelectionColor(QColor( 255, 0, 0, 200)) self.layer.setSelectedFeatures(ids) self.iface.mapCanvas().zoomToSelected(self.layer) def run(self): self.dlg.close() self.search_city_name() self.dlg.objectBrowser.clear() self.dlg.stateLabel.setText('') for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if '"' + self.city + '"' + "." + '"' + self.city + "_switches_working" + '"' in lyr.source( ): self.layer = lyr break if self.layer != None: self.surch_data() self.switches_all = filter(lambda i: True, self.layer.getFeatures()) """Run method that performs all the real work""" self.stop = True self.dlg.stopButton.clicked.connect(self.stopSlot) self.dlg.startButton.clicked.connect(self.dbData) self.dlg.objectBrowser.itemClicked.connect(self.onMapSlot) ##--------------------------------------------------------- # Run the dialog event loop if self.check_table_info == []: self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Critical) self.msg.setText(u"Info about \"комутатори\" is absent") self.msg.setInformativeText("Wait for the new information...") self.msg.setWindowTitle("Error") result = self.msg.exec_() elif self.data_list == []: self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Critical) self.msg.setText(u"Info about layer is absent") self.msg.setInformativeText("Wait for the new information...") self.msg.setWindowTitle("Message") result = self.msg.exec_() else: self.stop = False self.dlg.setWindowModality(True) result = self.dlg.show() # See if OK was pressed else: pass
class DataImport: """QGIS Plugin Implementation.""" 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', 'DataImport_{}.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 = DataImportDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Location Intelligence') ## Add to LI tooblar or create if doesn't exist toolbarName = 'Location Intelligence' self.toolbar = self.iface.mainWindow().findChild(QToolBar, toolbarName) if self.toolbar is None: self.toolbar = self.iface.addToolBar(toolbarName) self.toolbar.setObjectName(toolbarName) ## self.url = 'http://127.0.0.1:5000' ## Read API keys from QSettings self.readKeys() # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('DataImport', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/DataImport/icon.png' self.add_action(icon_path, text=self.tr(u'Import data'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Data Import'), action) self.iface.removeToolBarIcon(action) ## remove the toolbar if len(self.toolbar.actions()) == 0: del self.toolbar def fileWindow(self): """ Prepare window for file saving """ self.fileDialog = QFileDialog() self.fileDialog.setWindowTitle('Save file') self.fileDialog.setAcceptMode(QFileDialog.AcceptSave) self.fileDialog.setFileMode(QFileDialog.AnyFile) self.fileDialog.setViewMode(QFileDialog.Detail) def readKeys(self): """ Load API key from global QGIS settings """ s = QSettings() self.dlg.lineEdit.setText(s.value("data_import/gs_key")) def saveKeys(self): """ Save API key to global QGIS settings, so user doesn't need to input it every time """ gs_key = 'none' if self.dlg.lineEdit.text( ) == '' else self.dlg.lineEdit.text() s = QSettings() s.setValue("data_import/gs_key", gs_key) def prepareList(self): """ Fill list of available layers """ self.dlg.comboBox.clear() queryString = '%s/layers' % self.url response = urllib.urlopen(queryString) data = json.loads(response.read()) self.dlg.comboBox.addItems(data) def getGeometry(self, path, key): """ Run server query and load returned file by its path """ ## Get layer name region = self.dlg.comboBox.currentText() ## Append 'path' to path, so Flask won't cut '/home' in case of unix path ## Strips 'path' on the Flask side. path = 'path' + path queryString = '%s/%s/%s/%s' % (self.url, key, region, path) ## If any path specified if len(path) > 5: try: ## Run query urllib.urlopen(queryString) ## Load file to QGIS self.openFile(path[4:]) except: print 'couldnt get the data' def openFile(self, path): """ Load file to QGIS """ layer = self.iface.addVectorLayer(path, self.dlg.comboBox.currentText(), "ogr") if not layer: print "Layer failed to load!" def run(self): """Run method that performs all the real work""" try: ## Prepare "Save file" window self.fileWindow() ## Fill list of available layers self.prepareList() # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: ## Get selected download path and API key dl_path = self.fileDialog.getSaveFileName(self.fileDialog, 'Save file', filter='*.shp') key = self.dlg.lineEdit.text() ## Main function here self.getGeometry(dl_path, key) ## Save API keys self.saveKeys() except IOError: self.iface.messageBar().pushMessage("Error", "Service not available", level=QgsMessageBar.CRITICAL, duration=5)
class timetablecreater: """QGIS Plugin Implementation.""" 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: QgisInterface """ # 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', 'timetablecreater_{}.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.actions = [] self.menu = self.tr(u'&MSRTC PHC Time Table Creater') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'timetablecreater') self.toolbar.setObjectName(u'timetablecreater') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('timetablecreater', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ # Create the dialog (after translation) and keep reference self.dlg = timetablecreaterDialog() icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/timetablecreater/icon.png' self.add_action(icon_path, text=self.tr(u''), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&MSRTC PHC Time Table Creater'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" #clearing all comboBox values self.dlg.comboBox.clear() self.dlg.comboBox_2.clear() self.dlg.comboBox_3.clear() #setting all comboBox UI fields self.dlg.comboBox.addItems(['Maharashtra']) self.dlg.comboBox_2.addItems(['Nashik']) self.dlg.comboBox_3.addItems([ 'Nashik', 'Sinnar', 'Igatpuri', 'Trimbak', 'Niphad', 'Yeola', 'Peth', 'Dindori', 'Chandwad', 'Baglan', 'Deola', 'Kalwan', 'Malegaon', 'Nandgaon', 'Surgana' ]) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: print "State ", self.dlg.comboBox.currentIndex() print "District ", self.dlg.comboBox_2.currentIndex() print "Taluka ", self.dlg.comboBox_3.currentIndex() from qgis.core import QgsMessageLog from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import QgsMessageLog from qgis.core import QgsVectorLayer, QgsDataSourceURI, QgsMapLayerRegistry, QgsRasterLayer from qgis.utils import * if self.dlg.comboBox.currentIndex( ) != 0 or self.dlg.comboBox_2.currentIndex( ) != 0 or self.dlg.comboBox_3.currentIndex() != 1: QMessageBox.information(None, "Error", "Data Not Found for selected Taluka ") else: import pandas df = pandas.read_csv( '~/.qgis2/python/plugins/timetablecreater/abc.csv') import time time.sleep(2) df.to_csv('~/Desktop/form4.csv', index=False) df = pandas.read_csv( '~/.qgis2/python/plugins/timetablecreater/bcd.csv') df.to_csv('~/Desktop/PHCTimeTable.csv', index=False) QMessageBox.information( None, "Operation completed", "Form4 and PHCTimeTable has been created and saved to Form4.csv, PHCTimeTable.csv respectively on Desktop" ) pass
class SpatialDecision: """QGIS Plugin Implementation.""" 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', 'SpatialDecision_{}.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.actions = [] self.menu = self.tr(u'&SDSS Template') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'SpatialDecision') self.toolbar.setObjectName(u'SpatialDecision') #print "** INITIALIZING SpatialDecision" if has_pydevd and is_debug: pydevd.settrace('localhost', port=53100, stdoutToServer=True, stderrToServer=True, suspend=False) self.pluginIsActive = False self.dockwidget = None # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('SpatialDecision', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = self.plugin_dir + '/icons/icon.png' self.add_action(icon_path, text=self.tr(u'SDSS Template'), callback=self.run, parent=self.iface.mainWindow()) # -------------------------------------------------------------------------- def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" #print "** CLOSING SpatialDecision" # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.pluginIsActive = False def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" #print "** UNLOAD SpatialDecision" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&SDSS Template'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar # -------------------------------------------------------------------------- def run(self): """Run method that loads and starts the plugin""" if not self.pluginIsActive: self.pluginIsActive = True #print "** STARTING SpatialDecision" # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = SpatialDecisionDockWidget(self.iface) # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) # show the dockwidget # TODO: fix to allow choice of dock location self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget) self.dockwidget.show()
class SDB: """QGIS Plugin Implementation.""" 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', 'SDB_{}.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 = SDBDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&SDB') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'SDB') self.toolbar.setObjectName(u'SDB') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('SDB', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/SDB/icon.png' self.add_action( icon_path, text=self.tr(u'SDB'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&SDB'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class HexUtilsQGis: """QGIS Plugin Implementation.""" 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', 'HexUtilsQGis_{}.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.actions = [] self.menu = self.tr(u'&Hexagonal Rasters') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'HexUtilsQGis') self.toolbar.setObjectName(u'HexUtilsQGis') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('HexUtilsQGis', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/HexUtilsQGis/icons/Load.png' self.add_action(icon_path, text=self.tr(u'Load HexASCII raster'), callback=self.run, parent=self.iface.mainWindow()) # Create the dialog (after translation) and keep reference self.dlg = DialogueLoad() # Activate file search button self.dlg.lineEdit.clear() self.dlg.pushButton.clicked.connect(self.select_file) self.add_action(':/plugins/HexUtilsQGis/icons/New.png', text=self.tr(u'Create new HexASCII raster'), callback=self.runNew, parent=self.iface.mainWindow()) # Create New dialogue self.dlgNew = DialogueNew() def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Hexagonal Rasters'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. fileName = self.dlg.lineEdit.text() # Load the HexASCII file hexASCII = HASC() try: hexASCII.loadFromFile(fileName) hexASCII.saveAsGML(fileName + ".gml") except (ValueError, IOError) as ex: self.iface.messageBar().pushMessage( "Error", "Failed to load the raster %s: %s" % (fileName, ex), level=QgsMessageBar.CRITICAL) # Add HexASCII to the layer heap vector = fileName.split("/") layerName = vector[len(vector) - 1] layerName = layerName.split(".")[0] layer = self.iface.addVectorLayer(fileName + ".gml", layerName, "ogr") if not layer: self.iface.messageBar().pushMessage( "Error", "Failed to add raster to the layer heap", level=QgsMessageBar.CRITICAL) self.createChoropleth(layer, hexASCII.min, hexASCII.max) def runNew(self): """Run method that performs all the real work""" # Show the dialog and set the interface instance # Dialogue interaction is handed by the class itself self.dlgNew.show() self.dlgNew.iface = self.iface def createChoropleth(self, layer, min, max, num_classes=10): myTargetField = HASC().valueField myRangeList = [] myOpacity = 1 step = (max - min) / num_classes col_step = 256 / (num_classes - 1) for i in range(num_classes): label = str(min + step * i) + " - " + str(min + step * (i + 1)) hex_level = hex(int(col_step * i)).split('x')[1] if (len(hex_level) < 2): hex_level = "0" + hex_level colour = "#" + hex_level + hex_level + hex_level symbol = QgsFillSymbolV2.createSimple({ 'color': colour, 'color_border': colour, 'width_border': '0' }) symbol.setAlpha(myOpacity) myRangeList.append( QgsRendererRangeV2(min + step * i, min + step * (i + 1), symbol, label)) renderer = QgsGraduatedSymbolRendererV2('', myRangeList) renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) renderer.setClassAttribute(myTargetField) layer.setRendererV2(renderer) def select_file(self): fileName = QFileDialog.getOpenFileName(self.dlg, "Select file ", "", '*.hasc') self.dlg.lineEdit.setText(fileName)
class Marsis: """Implement the main Plug in interface *Methods* * __init__ - Inizialize the plug in * initGui - Create the menu entries and toolbar icons inside the QGIS GUI * marsis_viewer - Launch the MARSIS/SHARAD viewer * marsis_free - Remove reference to MARSIS/SHARAD viewer dialog * radar_3d - Export 3D data in CSV format * radar_fetch - Fetch radargrams (To be implemented) * settings - Launch the preferences settings dialog * update_prefs - Update the plug in preferences * unload - Remove the plugin menu item and icon from QGIS GUI """ def __init__(self, iface): """Inizialize the plug in :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 #set preferences self.prefs = prefs.RadarPrefs() self.prefs.set_prefs() # 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', 'Marsis_{}.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) # self.iface = iface self.marsis_menu = None def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI """ self.marsis_menu = QMenu( QCoreApplication.translate("marsissharadviewer", "Mars Radars")) self.iface.mainWindow().menuBar().insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.marsis_menu) icon = QIcon(':/plugins/marsissharadviewer/icon.png') self.marsis_viewer_action = QAction(icon, "MARSIS/SHARAD Viewer", self.iface.mainWindow()) QObject.connect(self.marsis_viewer_action, SIGNAL("triggered()"), self.marsis_viewer) self.marsis_menu.addAction(self.marsis_viewer_action) self.depth_map_action = QAction(icon, "Make depth map", self.iface.mainWindow()) QObject.connect(self.depth_map_action, SIGNAL("triggered()"), self.depth_map) self.marsis_menu.addAction(self.depth_map_action) # self.polar_viewer_action = QAction(icon, "Polar viewer", self.iface.mainWindow()) # QObject.connect(self.marsis_viewer_action, SIGNAL("triggered()"), self.polar_viewer) # self.marsis_menu.addAction(self.polar_viewer_action) # icon = QIcon(':/plugins/Marsis/icon.png') # self.radar_3d_action = QAction(icon, "Radar 3D", self.iface.mainWindow()) # QObject.connect(self.radar_3d_action, SIGNAL("triggered()"), self.radar_3d) # self.marsis_menu.addAction(self.radar_3d_action) # icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png") # self.track_fetch_action = QAction(icon, "Marsis tracks fetch", self.iface.mainWindow()) # QObject.connect(self.track_fetch_action, SIGNAL("triggered()"), self.track_fetch) # self.marsis_menu.addAction(self.track_fetch_action) # icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png") # self.radar_fetch_action = QAction(icon, "Marsis radargrams fetch", self.iface.mainWindow()) # QObject.connect(self.radar_fetch_action, SIGNAL("triggered()"), self.radar_fetch) # self.marsis_menu.addAction(self.radar_fetch_action) # icon = QIcon(os.path.dirname(__file__) + ":/plugins/Marsis/icon.png") self.settings_action = QAction(icon, "Settings", self.iface.mainWindow()) QObject.connect(self.settings_action, SIGNAL("triggered()"), self.settings) self.marsis_menu.addAction(self.settings_action) # Add toolbar button # self.iface.addToolBarIcon(self.marsis_viewer_action) self.toolbar = self.iface.addToolBar(u'MarsisViewer') self.toolbar.setObjectName(u'MarsisViewer') self.toolbar.addAction(self.marsis_viewer_action) def marsis_viewer(self): """Launch the MARSIS/SHARAD viewer """ gc.collect() self.dialog = MarsisViewerDialog(self.iface, self.prefs, free_routine=self.marsis_free) # dialog.exec_() def marsis_free(self): """Remove reference to MARSIS/SHARAD viewer dialog """ self.dialog = None # gc.collect() # def polar_viewer(self): # pass def depth_map(self): """ """ self.depth_map_run = DepthMap(self.iface) def radar_3d(self): """Export 3D data in CSV format """ Radar3D(self.iface) # def track_fetch(self): # pass def radar_fetch(self): """Fetch radargrams #TODO(To be implemented) """ pass def settings(self): """Launch the preferences settings dialog """ self.set_dialog = SettingsDialog(self.prefs) def update_prefs(self): """Update the plug in preferences """ self.prefs.set_prefs() def unload(self): """Removes the plugin menu item and icon from QGIS GUI """ if self.marsis_menu != None: self.iface.mainWindow().menuBar().removeAction( self.marsis_menu.menuAction()) else: self.iface.removePluginMenu("&mmqgis", self.marsis_viewer.menuAction()) self.iface.removeToolBarIcon(self.marsis_viewer_action)
class Frames: """QGIS Plugin Implementation.""" 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', 'Frames_{}.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.actions = [] self.menu = self.tr(u'&Frames from video') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'Frames') self.toolbar.setObjectName(u'Frames') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('Frames', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ # Create the dialog (after translation) and keep reference self.dlg = FramesDialog() icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/Frames/icon.png' self.add_action(icon_path, text=self.tr(u'Frames from video'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Frames from video'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def video(self): root = Tkinter.Tk() root.withdraw() # use to hide tkinter window self.file = tkFileDialog.askopenfile(parent=root, mode='rb', title='Choose a file') if self.file != None: data = self.file.read() print "You chose %s" % self.file.name print "I got %d bytes from this file." % len(data) print "" self.dlg.textEdit.setText(str(self.file.name)) def directory(self): root = Tkinter.Tk() root.withdraw() # use to hide tkinter window currdir = os.getcwd() self.tempdir = tkFileDialog.askdirectory( parent=root, initialdir=currdir, title='Please select a directory') if len(self.tempdir) > 0: print "You chose %s" % self.tempdir print "" self.dlg.textEdit_5.setText(str(self.tempdir)) def currentTime(self): videoFile = self.file imagesFolder = self.tempdir x = float(self.dlg.textEdit_4.toPlainText()) y = x * 1000 vidcap = cv2.VideoCapture(str(videoFile.name)) vidcap.set(cv2.CAP_PROP_POS_MSEC, y) # just cue to x sec. position success, image = vidcap.read() if success: print 'Read a new frame: ', success cv2.imwrite(imagesFolder + "/image_%d.jpg" % x, image) vidcap.release() print "" print "Done!" def everySecond(self): videoFile = self.file imagesFolder = self.tempdir vidcap = cv2.VideoCapture(str(videoFile.name)) frameRate = vidcap.get(5) # frame rate while (vidcap.isOpened()): frameId = vidcap.get(1) # current frame number success, image = vidcap.read() if (success != True): break if (frameId % math.floor(frameRate) == 0): filename = imagesFolder + "/image_" + str( int(frameId)) + ".jpg" print 'Read a new frame: ', success cv2.imwrite(filename, image) vidcap.release() print "" print "Done!" def all(self): videoFile = self.file imagesFolder = self.tempdir vidcap = cv2.VideoCapture(str(videoFile.name)) count = 0 success = True while success: success, image = vidcap.read() print 'Read a new frame: ', success cv2.imwrite(imagesFolder + "/image_%d.jpg" % count, image) # save frame as JPEG file count += 1 vidcap.release() print "" print "Done!" def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() self.dlg.pushButton.clicked.connect(self.video) self.dlg.pushButton_3.clicked.connect(self.directory) self.dlg.pushButton_2.clicked.connect(self.currentTime) self.dlg.pushButton_5.clicked.connect(self.everySecond) self.dlg.pushButton_8.clicked.connect(self.all) # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: pass
class Plugin: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/geoserver_bridge" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/geoserverqgis_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) def initGui(self): #------------------------------------ # Create action for Download dialog #------------------------------------ self.actionDownloadDialog = QAction( QIcon(":/plugins/geoserver_bridge/download_icon.png"), u"Geoserver Bridge Download", self.iface.mainWindow()) QObject.connect(self.actionDownloadDialog, SIGNAL("triggered()"), self.showDownloadDialog) # Add toolbar button and menu item self.iface.addToolBarIcon(self.actionDownloadDialog) self.iface.addPluginToMenu(u"&Geoserver QGIS Bridge", self.actionDownloadDialog) #------------------------------------ # Create action for Upload dialog #------------------------------------ self.actionUploadDialog = QAction( QIcon(":/plugins/geoserver_bridge/upload_icon.png"), u"Geoserver Bridge Upload", self.iface.mainWindow()) QObject.connect(self.actionUploadDialog, SIGNAL("triggered()"), self.showUploadDialog) self.iface.addToolBarIcon(self.actionUploadDialog) self.iface.addPluginToMenu(u"&Geoserver QGIS Bridge", self.actionUploadDialog) def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&Geoserver QGIS Bridge", self.actionDownloadDialog) self.iface.removePluginMenu(u"&Geoserver QGIS Bridge", self.actionUploadDialog) self.iface.removeToolBarIcon(self.actionDownloadDialog) self.iface.removeToolBarIcon(self.actionUploadDialog) def showDownloadDialog(self): self.download_dialog = DownloadDialog(self.iface) # show the dialog self.download_dialog.show() def showUploadDialog(self): self.upload_dialog = UploadDialog(self.iface) # show the dialog self.upload_dialog.show()
class ZonalStatistics: """QGIS Plugin Implementation.""" 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', 'ZonalStatistics_{}.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 = ZonalStatisticsDialog(self.iface.mainWindow()) self.graph = zonal_stat_graph.Graph() self.table = zonal_stat_table.Table() self.newCol = zonal_stat_new_column.NewColumn() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Location Intelligence') ## Add to LI tooblar or create if doesn't exist toolbarName = u'Location Intelligence' self.toolbar = self.iface.mainWindow().findChild(QToolBar,toolbarName) print self.toolbar if self.toolbar is None: self.toolbar = self.iface.addToolBar(toolbarName) self.toolbar.setObjectName(toolbarName) ## Functions call on init self.statistics() self.availableLayers() self.dlg.comboBox_3.currentIndexChanged.connect(self.fieldsToAnalyse) self.dlg.pushButton.clicked.connect(self.spatialQuery_group) self.table.pushButton_5.clicked.connect(self.showGraph) self.dlg.pushButton_2.clicked.connect(self.addToAttrTable_group) self.table.pushButton_6.clicked.connect(self.spatialQuery) # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('ZonalStatistics', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/ZonalStatistics/icon.png' self.add_action( icon_path, text=self.tr(u'Open Zonal Statistics'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&Zonal Statistics'), action) self.iface.removeToolBarIcon(action) # remove the toolbar if len(self.toolbar.actions())==0: del self.toolbar def availableLayers(self): """ Adds layers to comboboxes """ self.dlg.comboBox.clear() self.dlg.comboBox_3.clear() for i in self.iface.legendInterface().layers(): if i.type() == QgsMapLayer.VectorLayer and i.isValid(): if i.wkbType() % 3 == 0 and i.isValid(): ## Region layers self.dlg.comboBox.addItem(i.name()) if i.wkbType() % 3 == 1 and i.isValid(): ## Point layers self.dlg.comboBox_3.addItem(i.name()) ## Run function that fills the combobox below for the first time when plugin starts self.fieldsToAnalyse() def fieldsToAnalyse(self): """ Add fields of numeric type into combobox """ try: chosenLayer = self.dlg.comboBox_3.currentText() layer = QgsMapLayerRegistry.instance().mapLayersByName(chosenLayer)[0] self.dlg.comboBox_2.clear() for field in layer.pendingFields(): if field.typeName() in ("Real", "real", "Integer", "integer","Integer64", "integer64", "Double", "double") and field.name() not in ("id", "ID", "Id", "iD"): self.dlg.comboBox_2.addItem(field.name()) except IndexError: self.dlg.comboBox_2.clear() def statistics(self): """ Available statistics """ stats = [u'Suma', u'Średnia', u'Liczba obiektów'] for st in stats: self.dlg.comboBox_4.addItem(st) def spatialQuery(self): """ Creates lists of features within each polygon """ try: PolyName = self.dlg.comboBox.currentText() layerList_Poly = QgsMapLayerRegistry.instance().mapLayersByName(PolyName) self.polygons = [feature for feature in layerList_Poly[0].getFeatures()] polyCRS = int(layerList_Poly[0].crs().authid()[5:]) PointName = self.dlg.comboBox_3.currentText() layerList_Point = QgsMapLayerRegistry.instance().mapLayersByName(PointName) self.points = [feature for feature in layerList_Point[0].getFeatures()] pointCRS = int(layerList_Point[0].crs().authid()[5:]) self.groups = [] self.values = [] count = -1 maximum = len(self.polygons) currentField = self.dlg.comboBox_2.currentText() for fPoly in self.polygons: self.values.append([]) poly_geom = fPoly.geometry() ## Progress bar part status = count+2 progress = int(round(status/float(maximum)*100)) self.increaseProgressBar(progress) ## Change CRS if different if polyCRS != pointCRS: crsSrc = QgsCoordinateReferenceSystem(polyCRS) crsDest = QgsCoordinateReferenceSystem(pointCRS) xform = QgsCoordinateTransform(crsSrc, crsDest) poly_geom.transform(xform) try: self.groups.append(fPoly[1]) except KeyError: self.iface.messageBar().pushMessage("Error", u"Druga kolumna warstwy regionów musi zawierać ich nazwy", level=QgsMessageBar.WARNING, duration=4) return count += 1 for fPoint in self.points: pt_geom = fPoint.geometry() if poly_geom.contains(pt_geom): self.values[count].append(fPoint[currentField]) ## Change back if it was different if polyCRS != pointCRS: xform = QgsCoordinateTransform(crsDest, crsSrc) poly_geom.transform(xform) self.x = list(enumerate(self.groups)) self.prepareGraph() self.prepareTable() except IndexError: # self.iface.messageBar().pushMessage("Error", u"Brak dostępnych warstw wektorowych lub warstwa usunięta", level=QgsMessageBar.CRITICAL, duration=4) pass def prepareGraph(self): """ Prepare data to use """ self.y = [] # try: # self.x = list(enumerate(self.groups)) # self.y = [] # selectedColumns = [] # ## If no or only 'Region' column loaded # if self.dlg.tableWidget.columnCount() in (0,1): # return # else: # ## Check which columns are selected and get the first one if many # for index in self.dlg.tableWidget.selectedIndexes(): # if index.column() != 0: # selectedColumns.append(index.column()) # ## In case none or Region column checked and the button was pressed # try: # columnToGraph = min(selectedColumns)-1 # except ValueError, NameError: # columnToGraph = 0 self.graphTitle = self.dlg.comboBox_3.currentText()+': '+self.dlg.comboBox_2.currentText() ## Select data for valGroup in range(len(self.values)): try: if self.dlg.comboBox_4.currentIndex() == 0: self.y.append(round(sum(self.values[valGroup]),2)) elif self.dlg.comboBox_4.currentIndex() == 1: try: self.y.append(round(sum(self.values[valGroup])/len(self.values[valGroup]),2)) except ZeroDivisionError: self.y.append(0) else: self.y.append(len(self.values[valGroup])) except TypeError: self.iface.messageBar().pushMessage("Error", u"Pusta kolumna z danymi ("+self.dlg.comboBox_2.currentText()+")", level=QgsMessageBar.WARNING, duration=4) self.buildGraph() def buildGraph(self): """ Add data to the graph """ dataColor = (102,178,255) dataBorderColor = (180,220,255) barGraph = self.graph.plotWidget barGraph.clear() barGraph.addItem(pyqtgraph.BarGraphItem(x=range(len(self.x)), height=self.y, width=0.5, brush=dataColor, pen=dataBorderColor)) barGraph.addItem(pyqtgraph.GridItem()) barGraph.getAxis('bottom').setTicks([self.x]) barGraph.setTitle(title=self.graphTitle) def showGraph(self): """ Just show the graph on click """ self.graph.show() def prepareTable(self): """ Create table to view the data """ qTable = self.table.tableWidget labels = ['Region', unicode(self.dlg.comboBox_2.currentText())] qTable.setSortingEnabled(False) qTable.setRowCount(len(self.groups)) qTable.setColumnCount(len(labels)) # Insert data try: for row in range(len(self.groups)): ## Add group name field group = QTableWidgetItem(unicode(self.groups[row])) qTable.setItem(row,0,group) ## Calculate sum or average if self.dlg.comboBox_4.currentIndex() == 0: item = QCustomTableWidgetItem(str(round(self.y[row],2))) elif self.dlg.comboBox_4.currentIndex() == 1: try: item = QCustomTableWidgetItem(str(round(self.y[row]/len(self.values[row]),2))) except ZeroDivisionError: item = QCustomTableWidgetItem(str(0)) else: item = QTableWidgetItem(str(len(self.values[row]))) ## Set item qTable.setItem(row,1,item) except TypeError: self.iface.messageBar().pushMessage("Error", u"Wybrane pole zawiera puste komórki ("+self.dlg.comboBox_2.currentText()+")", level=QgsMessageBar.WARNING, duration=4) qTable.setSortingEnabled(True) qTable.setHorizontalHeaderLabels(labels) qTable.resizeColumnsToContents() def showTable(self): """ Just show the table on click""" self.table.show() def rowSelection(self): """ Highlights selected groups on map """ PointName = self.dlg.comboBox_3.currentText() layerList_Point = QgsMapLayerRegistry.instance().mapLayersByName(PointName) selectedFeatures = [] layerList_Point[0].setSelectedFeatures([]) qTable = self.table.tableWidget indexes = qTable.selectionModel().selectedRows() ## Get selected group name for index in sorted(indexes): selectedGroup = qTable.item(index.row(),0).text() ## Select features for fPoly in self.polygons: if fPoly[1] == selectedGroup: poly_geom = fPoly.geometry() for fPoint in self.points: point_geom = fPoint.geometry() if poly_geom.contains(point_geom): selectedFeatures.append(fPoint) ## Set selection to chosen IDs ids = [i.id() for i in selectedFeatures] layerList_Point[0].setSelectedFeatures(ids) def showNewCol(self): """ Show a dialog box to input new column name """ self.newCol.show() result = self.newCol.exec_() if result: newName = self.newCol.lineEdit.text() if newName == '': self.iface.messageBar().pushMessage("Error", u"Wpisz nazwę nowej kolumny (do 10 znaków)", level=QgsMessageBar.WARNING, duration=4) return else: self.addToAttrTable(newName) def addToAttrTable(self, newName): """ Add statistics to the attribute table of regions layer """ try: PolyName = self.dlg.comboBox.currentText() layerPoly = QgsMapLayerRegistry.instance().mapLayersByName(PolyName)[0] features = layerPoly.getFeatures() layerPoly.dataProvider().addAttributes([QgsField(newName, QVariant.Double, "double", 10, 2)]) layerPoly.updateFields() columnid = layerPoly.fieldNameIndex(newName) count = 0 ## Progress bar part maximum = 0 for feature in features: maximum += 1 layerPoly.startEditing() ## Get features again as they were 'used' to get 'maximum' features = layerPoly.getFeatures() for feature in features: fid = feature.id() ## Prepare data if self.dlg.comboBox_4.currentIndex() == 0: item = round(self.y[count],2) elif self.dlg.comboBox_4.currentIndex() == 1: try: item = round((self.y[count])/len(self.values[count]),2) except ZeroDivisionError: item = 0 else: item = len(self.values[count]) ## Progress bar part progress = int(round((count+1)/float(maximum)*100)) self.increaseProgressBar(progress) ## Update attribute table layerPoly.changeAttributeValue(fid, columnid, item, True) count += 1 layerPoly.commitChanges() except: try: ## Delete unsuccessful column layerPoly.rollBack() layerPoly.dataProvider().deleteAttributes([layerPoly.fieldNameIndex(newName)]) layerPoly.updateFields() self.iface.messageBar().pushMessage("Error", u"Najpierw wczytaj dane", level=QgsMessageBar.CRITICAL, duration=4) except UnboundLocalError: self.iface.messageBar().pushMessage("Error", u"Błąd w dostępie do wybranej warstwy", level=QgsMessageBar.CRITICAL, duration=4) def addToAttrTable_group(self): """ Run spatial query and prepare data to input to attr table """ self.spatialQuery() if self.dlg.comboBox_2.count() > 0: self.showNewCol() def spatialQuery_group(self): """ Run spatial query and view table """ self.spatialQuery() if self.dlg.comboBox_2.count() > 0: self.showTable() def increaseProgressBar(self, value): self.dlg.progressBar.setValue(value) def run(self): """Run method that performs all the real work""" ## Reset progress bar self.dlg.progressBar.setValue(0) ## Update available layers self.availableLayers() ## Update available fields # self.fieldsToAnalyse() ## Listen to features selection on row click self.table.tableWidget.verticalHeader().sectionClicked.connect(self.rowSelection) # show the dialog self.dlg.show()
class MetadataDbLinker(object): """QGIS Plugin Implementation.""" 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__) self.plugin_metadata = plugin_metadata() # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, '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) self.settings = MetadataDbLinkerSettings() # Create the dialog (after translation) and keep reference self.dlg = MetadataDialog() self.settings_dlg = SettingsDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&{}'.format(self.plugin_metadata['name'])) # Initialize the fixes to DlgCreateTable class if not getattr(DlgCreateTable, 'original_createTable', None): DlgCreateTable.original_createTable = DlgCreateTable.createTable QgsMessageLog.logMessage("Adding the createTable patch.") DlgCreateTable.createTable = patched_createTable if not getattr(connector.PostGisDBConnector, 'accept_original', None): DlgImportVector.accept_original = DlgImportVector.accept DlgImportVector.accept = new_accept # menu DBTree.fireMetadataDlg = fireMetadataDlg DBTree.contextMenuEvent = newContextMenuEvent self.septimasearchprovider = MySeptimaSearchProvider(iface) # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('MetadataDbLinker', message) def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" self.editmetadata_action = QAction( QIcon(':/plugins/MetadataDbLinker/resources/metadata.png'), self.tr(u'Enter or edit metadata'), self.iface.mainWindow()) self.editmetadata_action.triggered.connect(self.run) self.editmetadata_action.setEnabled(True) self.iface.addPluginToMenu(self.menu, self.editmetadata_action) self.iface.addToolBarIcon(self.editmetadata_action) self.actions.append(self.editmetadata_action) self.settings_action = QAction( QIcon(':/plugins/MetadataDbLinker/resources/settings.png'), self.tr(u'Settings'), self.iface.mainWindow()) self.settings_action.triggered.connect(self.settings_run) self.settings_action.setEnabled(True) self.iface.addPluginToMenu(self.menu, self.settings_action) self.actions.append(self.settings_action) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&{}'.format(self.plugin_metadata['name'])), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" errors = self.settings.verify_settings_set() if errors: QMessageBox.critical(None, u'Missing settings.', u'{}'.format(errors)) return None # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass def settings_run(self): """Run method that performs all the real work""" # show the dialog self.settings_dlg.show() # Run the dialog event loop result = self.settings_dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class ComplexGmlInfo: """QGIS Plugin Implementation.""" 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', 'ComplexGmlInfo_{}.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 = ComplexGmlInfoDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Complex GML Info') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'ComplexGmlInfo') self.toolbar.setObjectName(u'ComplexGmlInfo') logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logfile = util.getTempfile('gmlinfo.log') logging.basicConfig(filename=logfile, level=logging.ERROR, format=logformat) self.cache = {} # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('ComplexGmlInfo', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToVectorMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/ComplexGmlInfo/icon.png' self.add_action(icon_path, text=self.tr(u'Complex GML Info'), callback=self.run, parent=self.iface.mainWindow()) self.add_action(None, text='About', callback=self.about, add_to_toolbar=None, parent=None) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginVectorMenu(self.tr(u'&Complex GML Info'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def about(self): infoString = "<table><tr><td colspan=\"2\"><b>Complex GML Info 0.4</b></td></tr><tr><td colspan=\"2\"></td></tr><tr><td>Author:</td><td>Jürgen Weichand</td></tr><tr><td>Mail:</td><td><a href=\"mailto:[email protected]\">[email protected]</a></td></tr><tr><td>Website:</td><td><a href=\"http://www.weichand.de\">http://www.weichand.de</a></td></tr></table>" QMessageBox.information(self.iface.mainWindow(), "About Complex GML Info", infoString) def run(self): self.dlg.treeWidget.setHeaderHidden(True) self.displayFeatureInfo() QObject.connect(self.dlg.lineEdit, SIGNAL("textChanged(QString)"), self.resetTimer) self.q = self.dlg.lineEdit.text() self.timer = QTimer() self.timer.setInterval(500) self.timer.start() self.timer.timeout.connect(self.checkUpdateFeatureInfo) def resetTimer(self): self.timer.stop() self.timer.start() def checkUpdateFeatureInfo(self): if not self.q == self.dlg.lineEdit.text(): self.q = self.dlg.lineEdit.text() self.updateFeatureInfo() self.timer.stop() self.timer.start() def displayFeatureInfo(self): layer = self.iface.activeLayer() # layer must be activated if not layer: QMessageBox.critical(self.dlg, 'Error', u'Please activate GML layer!') return # layer must be GML if layer.storageType() != 'GML': QMessageBox.critical(self.dlg, 'Error', u'Please activate GML layer!') return filename = layer.dataProvider().dataSourceUri().split('|')[0] if not filename in self.cache: logging.debug('%s not cached yet!' % filename) try: self.cache[filename] = pygml.Dataset(filename) except pygml.GmlException as e: QMessageBox.critical(self.dlg, 'Error', e.message) return gml = self.cache[filename] # >= 1 feature must be selected if not layer.selectedFeatures(): QMessageBox.critical( self.dlg, 'Error', u'Please select one or more feature(s) first!') return else: self.dlg.show() features = OrderedDict() i = 0 for feature in layer.selectedFeatures(): if feature.attribute('gml_id'): i += 1 gml_id = feature.attribute('gml_id') features['Selected feature [' + str(i) + ']'] = gml.getFeature(gml_id) self.fill_widget(self.dlg.treeWidget, features) # based on http://stackoverflow.com/questions/21805047/qtreewidget-to-mirror-python-dictionary def fill_item(self, item, value): item.setExpanded(True) if type(value) is OrderedDict: for key, val in sorted(value.items()): if type(val) is unicode: if '@xmlns' not in key: # hack child = QTreeWidgetItem() text = unicode(key + " '" + val + "'") child.setTextColor(0, self.getQColor(text)) child.setText(0, text) item.addChild(child) else: child = QTreeWidgetItem() text = unicode(key) #child.setTextColor(0, self.getQColor(text)) child.setText(0, text) item.addChild(child) self.fill_item(child, val) elif type(value) is list: for val in value: child = QTreeWidgetItem() item.addChild(child) if type(val) is OrderedDict: child.setText(0, '[' + str(value.index(val)) + ']') self.fill_item(child, val) elif type(val) is list: child.setText(0, '[' + str(value.index(val)) + ']') self.fill_item(child, val) else: child.setText(0, unicode(val)) child.setExpanded(True) else: child = QTreeWidgetItem() child.setText(0, str(value)) item.addChild(child) def fill_widget(self, widget, value): widget.clear() self.fill_item(widget.invisibleRootItem(), value) # colorize attributes def getQColor(self, text): for indicator in ['nil']: if indicator in text.lower(): return QColor('lightgrey') for indicator in [ 'gml:id', 'localid', 'identifier', 'xlink:href', 'xlink:type', 'namespace', 'codespace' ]: if indicator in text.lower(): return QColor('darkslategray') return QColor('red') # search inside QTreeWidget def updateFeatureInfo(self): self.displayFeatureInfo() query = unicode(self.dlg.lineEdit.text()) if query and len(query) >= 3: root_item = self.dlg.treeWidget.invisibleRootItem() self.removeChildren(root_item, query) def removeChildren(self, item, query): if item: child_count = item.childCount() if child_count > 0: for i in range(child_count): self.removeChildren(item.child(i), query) else: path = self.buildPath(item) if not query.lower() in self.buildPath(item).lower(): parent = item.parent() if parent: parent.removeChild(item) self.removeChildren(parent, query) def buildPath(self, item): text = item.text(0) if item.parent(): text += ' > ' + self.buildPath(item.parent()) return text
class PediaLayer: """QGIS Plugin Implementation.""" 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', 'PediaLayer_{}.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 = PediaLayerDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Pedia Layer') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'PediaLayer') self.toolbar.setObjectName(u'PediaLayer') # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('PediaLayer', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToWebMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/PediaLayer/icon.png' self.add_action(icon_path, text=self.tr(u'Create a layer from DBpedia'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginWebMenu(self.tr(u'&Pedia Layer'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # PREPARE COMBO BOX self.dlg.comboBox.clear() layers = self.iface.legendInterface().layers() layer_list = [] for layer in layers: if isinstance(layer, QgsVectorLayer) or \ isinstance(layer, QgsRasterLayer): layer_list.append(layer.name()) self.dlg.comboBox.addItems(layer_list) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # ADD LAYER FROM DBPEDIA # calculate coordinates if self.dlg.radioButton_l.isChecked() == True: index = self.dlg.comboBox.currentIndex() if index == -1: return layer = layers[index] extent = layer.extent() srcCrs = layer.crs() elif self.dlg.radioButton_m.isChecked() == True: canvas = self.iface.mapCanvas() layers = self.iface.legendInterface().layers() if len(layers) == 0: return extent = canvas.extent() srcCrs = canvas.mapSettings().destinationCrs() else: return destCrs = QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem.EpsgCrsId) transform = QgsCoordinateTransform(srcCrs, destCrs) wgsExtent = transform.transform(extent) xMax = wgsExtent.xMaximum() xMin = wgsExtent.xMinimum() yMax = wgsExtent.yMaximum() yMin = wgsExtent.yMinimum() # prepare query sparql = "SELECT distinct ?name ?abstract ?lat ?lon ?url\n" \ + "WHERE {\n" \ + "?s rdfs:label ?name ;\n" \ + "dbpedia-owl:abstract ?abstract ;\n" \ + "foaf:isPrimaryTopicOf ?url ;\n" \ + "geo:lat ?lat ;\n" \ + "geo:long ?lon .\n" \ + "FILTER ( " \ + "?lon > \"" + str(xMin) + "\"^^xsd:float && ?lon < \"" + str(xMax) + "\"^^xsd:float && " \ + "?lat > \"" + str(yMin) + "\"^^xsd:float && ?lat < \"" + str(yMax) + "\"^^xsd:float)\n" \ + "FILTER (LANG(?name)='ja' && LANG(?abstract)='ja')" \ + "\n} LIMIT " + str(self.dlg.spinBox.value()) server = "http://ja.dbpedia.org/sparql" param = { "query": sparql, "format": "application/sparql-results+json" } # exec query request = urllib2.Request(server, urllib.urlencode(param)) response = urllib2.urlopen(request) data = json.loads(response.read()) list = data["results"]["bindings"] # add layer newLayer = QgsVectorLayer("Point?crs=epsg:4326", "pedialayer", "memory") newLayer.setProviderEncoding("UTF-8") QgsMapLayerRegistry.instance().addMapLayer(newLayer) newLayer.startEditing() newLayer.addAttribute(QgsField("name", QVariant.String)) newLayer.addAttribute(QgsField("url", QVariant.String)) newLayer.addAttribute(QgsField("abstract", QVariant.String)) # label setting newLayer.setCustomProperty("labeling", "pal") newLayer.setCustomProperty("labeling/enabled", "true") newLayer.setCustomProperty("labeling/fieldName", "name") newLayer.setCustomProperty("labeling/fontSize", "10") # add features for item in list: feature = QgsFeature(newLayer.pendingFields()) feature.setGeometry( QgsGeometry.fromPoint( QgsPoint(float(item["lon"]["value"]), float(item["lat"]["value"])))) feature.setAttribute("name", unicode(item["name"]["value"])) feature.setAttribute("url", unicode(item["url"]["value"])) feature.setAttribute("abstract", unicode(item["abstract"]["value"])) newLayer.addFeature(feature) newLayer.commitChanges() newLayer.updateExtents()
class MetaSearchPlugin(object): """base plugin""" def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.dialog = None self.web_menu = '&MetaSearch' LOGGER.debug('Setting up i18n') # TODO: does this work for locales like: pt_BR ? locale_name = QSettings().value("locale/userLocale")[0:2] # this one below does not pick up when you load QGIS with --lang param # locale_name = str(QLocale.system().name()).split('_')[0] LOGGER.debug('Locale name: %s', locale_name) # load if exists tr_file = os.path.join(self.context.ppath, 'locale', locale_name, 'LC_MESSAGES', 'ui.qm') if os.path.exists(tr_file): self.translator = QTranslator() result = self.translator.load(tr_file) if not result: msg = 'Failed to load translation: %s' % tr_file LOGGER.error(msg) raise RuntimeError(msg) QCoreApplication.installTranslator(self.translator) LOGGER.debug( QCoreApplication.translate('MetaSearch', 'Translation loaded: %s' % tr_file)) 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 Catalogues')) self.action_run.triggered.connect(self.run) self.iface.addToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png')) 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) def unload(self): """teardown""" # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_run) self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.iface.removeToolBarIcon(self.action_run) self.iface.removeToolBarIcon(self.action_help) def run(self): """open MetaSearch""" self.dialog.exec_() def help(self): """open help in user's default web browser""" open_url(self.context.metadata.get('general', 'homepage'))
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if not settings.IS_WINDOWS: app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as fileaccess: qss = fileaccess.read() else: with open(resources.NINJA_THEME_CLASSIC) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) #Showing GUI ninjaide.show() #OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #First check if we need to load last session files if qsettings.value('preferences/general/loadFiles', True, type=bool): #Files in Main Tab files = data_qsettings.value('lastSession/openedFiles', []) tempFiles = [] if files: for file_ in files: fileData = tuple(file_) if fileData: tempFiles.append(fileData) files = tempFiles # Recent Files recent_files = data_qsettings.value('lastSession/recentFiles', []) #Current File current_file = data_qsettings.value('lastSession/currentFile', '', type='QString') #Projects projects = data_qsettings.value('lastSession/projects', []) else: files = [] recent_files = [] current_file = '' projects = [] #Include files received from console args file_with_nro = list([(f[0], f[1] - 1, 0) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0, 0) for f in filenames[len(linenos):]]) files += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path #FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT ninjaide.load_session_files_projects(files, projects, current_file, recent_files) #Load external plugins #if extra_plugins: #ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()
class QuickMapServices(object): """QGIS Plugin Implementation.""" 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__).decode( sys.getfilesystemencoding()) # initialize locale self.translator = QTranslator() self.locale = Locale.get_locale() locale_path = os.path.join( self.plugin_dir, 'i18n', 'QuickMapServices_{}.qm'.format(self.locale)) if os.path.exists(locale_path): self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.custom_translator = CustomTranslator() QCoreApplication.installTranslator(self.custom_translator) # Create the dialog (after translation) and keep reference self.info_dlg = AboutDialog() # Check Contrib and User dirs try: ExtraSources.check_extra_dirs() except: error_message = self.tr( 'Extra dirs for %s can\'t be created: %s %s') % ( PluginSettings.product_name(), sys.exc_type, sys.exc_value) self.iface.messageBar().pushMessage(self.tr('Error'), error_message, level=QgsMessageBar.CRITICAL) # Declare instance attributes self.service_actions = [] self.service_layers = [] # TODO: id and smart remove self._scales_list = None # noinspection PyMethodMayBeStatic def tr(self, message): # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('QuickMapServices', message) def initGui(self): #import pydevd #pydevd.settrace('localhost', port=9921, stdoutToServer=True, stderrToServer=True, suspend=False) # Register plugin layer type self.tileLayerType = TileLayerType(self) QgsPluginLayerRegistry.instance().addPluginLayerType( self.tileLayerType) # Create menu icon_path = self.plugin_dir + '/icons/mActionAddLayer.svg' self.menu = QMenu(self.tr(u'QuickMapServices')) self.menu.setIcon(QIcon(icon_path)) self.init_server_panel() self.build_menu_tree() # add to QGIS menu/toolbars self.append_menu_buttons() def _load_scales_list(self): scales_filename = os.path.join(self.plugin_dir, 'scales.xml') scales_list = [] # TODO: remake when fix: http://hub.qgis.org/issues/11915 # QgsScaleUtils.loadScaleList(scales_filename, scales_list, importer_message) xml_root = ET.parse(scales_filename).getroot() for scale_el in xml_root.findall('scale'): scales_list.append(scale_el.get('value')) return scales_list @property def scales_list(self): if not self._scales_list: self._scales_list = self._load_scales_list() return self._scales_list def set_nearest_scale(self): #get current scale curr_scale = self.iface.mapCanvas().scale() #find nearest nearest_scale = sys.maxsize for scale_str in self.scales_list: scale = scale_str.split(':')[1] scale_int = int(scale) if abs(scale_int - curr_scale) < abs(nearest_scale - curr_scale): nearest_scale = scale_int #set new scale if nearest_scale != sys.maxsize: self.iface.mapCanvas().zoomScale(nearest_scale) def set_tms_scales(self): res = QMessageBox.question( self.iface.mainWindow(), self.tr('QuickMapServices'), self. tr('Set SlippyMap scales for current project? \nThe previous settings will be overwritten!' ), QMessageBox.Yes | QMessageBox.No) if res == QMessageBox.Yes: # set scales QgsProject.instance().writeEntry('Scales', '/ScalesList', self.scales_list) # activate QgsProject.instance().writeEntry('Scales', '/useProjectScales', True) # update in main window # ???? no way to update: http://hub.qgis.org/issues/11917 def insert_layer(self): action = self.menu.sender() ds = action.data() add_layer_to_map(ds) def unload(self): # remove menu/panels self.remove_menu_buttons() self.remove_server_panel() # clean vars self.menu = None self.toolbutton = None self.service_actions = None self.ds_list = None self.groups_list = None self.service_layers = None # Unregister plugin layer type QgsPluginLayerRegistry.instance().removePluginLayerType( TileLayer.LAYER_TYPE) def build_menu_tree(self): # Main Menu self.menu.clear() self.groups_list = GroupsList() self.ds_list = DataSourcesList() data_sources = self.ds_list.data_sources.values() data_sources.sort(key=lambda x: x.alias or x.id) ds_hide_list = PluginSettings.get_hide_ds_id_list() for ds in data_sources: if ds.id in ds_hide_list: continue ds.action.triggered.connect(self.insert_layer) gr_menu = self.groups_list.get_group_menu(ds.group) gr_menu.addAction(ds.action) if gr_menu not in self.menu.children(): self.menu.addMenu(gr_menu) # QMS web service self.menu.addSeparator() self.service_actions.append(self.qms_search_action) self.menu.addAction(self.qms_search_action) icon_create_service_path = self.plugin_dir + '/icons/mActionCreate.svg' qms_create_service_action = QAction(self.tr('Add to Search'), self.iface.mainWindow()) qms_create_service_action.setIcon(QIcon(icon_create_service_path)) qms_create_service_action.triggered.connect(self.openURL) self.menu.addAction(qms_create_service_action) # Scales, Settings and About actions self.menu.addSeparator() icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.svg' # TODO change icon set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path), self.tr('Set proper scale'), self.iface.mainWindow()) set_nearest_scale_act.triggered.connect(self.set_nearest_scale) self.menu.addAction(set_nearest_scale_act) # TODO: uncomment after fix self.service_actions.append(set_nearest_scale_act) icon_scales_path = self.plugin_dir + '/icons/mActionSettings.svg' # TODO change icon scales_act = QAction(QIcon(icon_scales_path), self.tr('Set SlippyMap scales'), self.iface.mainWindow()) scales_act.triggered.connect(self.set_tms_scales) #self.menu.addAction(scales_act) # TODO: uncomment after fix self.service_actions.append(scales_act) icon_settings_path = self.plugin_dir + '/icons/mActionSettings.svg' settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'), self.iface.mainWindow()) self.service_actions.append(settings_act) settings_act.triggered.connect(self.show_settings_dialog) self.menu.addAction(settings_act) icon_about_path = self.plugin_dir + '/icons/mActionAbout.svg' info_act = QAction(QIcon(icon_about_path), self.tr('About'), self.iface.mainWindow()) self.service_actions.append(info_act) info_act.triggered.connect(self.info_dlg.show) self.menu.addAction(info_act) def remove_menu_buttons(self): """ Remove menus/buttons from all toolbars and main submenu :return: None """ # remove menu if self.menu: self.iface.webMenu().removeAction(self.menu.menuAction()) self.iface.addLayerMenu().removeAction(self.menu.menuAction()) # remove toolbar button if self.tb_action: self.iface.webToolBar().removeAction(self.tb_action) self.iface.layerToolBar().removeAction(self.tb_action) if self.qms_search_action: self.iface.webToolBar().removeAction(self.qms_search_action) self.iface.layerToolBar().removeAction(self.qms_search_action) def append_menu_buttons(self): """ Append menus and buttons to appropriate toolbar :return: """ # add to QGIS menu if PluginSettings.move_to_layers_menu(): self.iface.addLayerMenu().addMenu(self.menu) else: # need workaround for WebMenu _temp_act = QAction('temp', self.iface.mainWindow()) self.iface.addPluginToWebMenu("_tmp", _temp_act) self.iface.webMenu().addMenu(self.menu) self.iface.removePluginWebMenu("_tmp", _temp_act) # add to QGIS toolbar toolbutton = QToolButton() toolbutton.setPopupMode(QToolButton.InstantPopup) toolbutton.setMenu(self.menu) toolbutton.setIcon(self.menu.icon()) toolbutton.setText(self.menu.title()) toolbutton.setToolTip(self.menu.title()) # self.tb_action = toolbutton.defaultAction() # print "self.tb_action: ", self.tb_action if PluginSettings.move_to_layers_menu(): self.tb_action = self.iface.layerToolBar().addWidget(toolbutton) self.iface.layerToolBar().addAction(self.qms_search_action) else: self.tb_action = self.iface.webToolBar().addWidget(toolbutton) self.iface.webToolBar().addAction(self.qms_search_action) def show_settings_dialog(self): settings_dlg = SettingsDialog() settings_dlg.exec_() # apply settings # self.remove_menu_buttons() self.build_menu_tree() # self.append_menu_buttons() def init_server_panel(self): self.server_toolbox = QmsServiceToolbox(self.iface) self.iface.addDockWidget(PluginSettings.server_dock_area(), self.server_toolbox) self.server_toolbox.setWindowIcon( QIcon(self.plugin_dir + '/icons/mActionSearch.svg')) self.server_toolbox.setVisible(PluginSettings.server_dock_visibility()) # self.server_toolbox.setFloating(PluginSettings.dock_floating()) # self.server_toolbox.resize(PluginSettings.dock_size()) # self.server_toolbox.move(PluginSettings.dock_pos()) # self.server_toolbox.setWindowIcon(QIcon(path.join(_current_path, 'edit-find-project.png'))) # QMS search action icon_settings_path = self.plugin_dir + '/icons/mActionSearch.svg' self.qms_search_action = self.server_toolbox.toggleViewAction() self.qms_search_action.setIcon(QIcon(icon_settings_path)) self.qms_search_action.setText(self.tr('Search QMS')) def remove_server_panel(self): mw = self.iface.mainWindow() PluginSettings.set_server_dock_area( mw.dockWidgetArea(self.server_toolbox)) PluginSettings.set_server_dock_visibility( self.server_toolbox.isVisible()) # PluginSettings.set_dock_floating(self.__quick_tlb.isFloating()) # PluginSettings.set_dock_pos(self.__quick_tlb.pos()) # PluginSettings.set_dock_size(self.__quick_tlb.size()) # PluginSettings.set_dock_geocoder_name(self.__quick_tlb.get_active_geocoder_name()) self.iface.removeDockWidget(self.server_toolbox) del self.server_toolbox def openURL(self): QDesktopServices.openUrl(QUrl("https://qms.nextgis.com/create"))
# -*- coding: utf-8 -*- import sys from sky.ui.ui import Main from PyQt4.QtCore import QTranslator from PyQt4.QtGui import QApplication if __name__ == '__main__': app = QApplication(sys.argv) trans = QTranslator() trans.load("zh_CN") # 没有后缀.qm app.installTranslator(trans) ui = Main() ui.show() sys.exit(app.exec_())