def saveAsScriptFile(self, index=None): tabWidget = self.tabEditorWidget.currentWidget() if not index: index = self.tabEditorWidget.currentIndex() if not tabWidget.path: fileName = self.tabEditorWidget.tabText(index) + '.py' folder = self.settings.value("pythonConsole/lastDirPath", QDir.home()) pathFileName = os.path.join(folder, fileName) fileNone = True else: pathFileName = tabWidget.path fileNone = False saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As") filename = QFileDialog.getSaveFileName(self, saveAsFileTr, pathFileName, "Script file (*.py)") if filename: try: tabWidget.save(filename) except (IOError, OSError) as error: msgText = QCoreApplication.translate('PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) if fileNone: tabWidget.path = None else: tabWidget.path = pathFileName return if not fileNone: self.updateTabListScript(pathFileName, action='remove')
def load(self): self.initTranslations() cfg = SimuVis4.Globals.config cfgsec = self.name.lower() if not cfg.has_section(cfgsec): cfg.add_section(cfgsec) cfg.set_def(cfgsec, 'set_default_backend', 'yes') cfg.set_def(cfgsec, 'zoom_step_factor', '0.189207115002721') cfg.set_def(cfgsec, 'mouse_wheel_step', '15') glb = SimuVis4.Globals import matplotlib if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion: SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \ (mplMinVersion, mplMaxVersion, matplotlib.__version__)) return False self.matplotlib = matplotlib if cfg.getboolean(cfgsec, 'set_default_backend'): try: sys.path.append(os.path.split(__file__)[0]) matplotlib.use('module://backend_sv4agg') except: pass import backend_sv4agg self.backend_sv4agg = backend_sv4agg dpath = matplotlib.rcParams['datapath'] tmp = os.path.join(dpath, 'images') if os.path.isdir(tmp): dpath = tmp winIcon = QIcon(os.path.join(dpath, 'matplotlib.png')) testAction = QAction(winIcon, QCoreApplication.translate('MatPlot', '&MatPlot/PyLab Test'), SimuVis4.Globals.mainWin) testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib/pylab test window')) QWidget.connect(testAction, SIGNAL("triggered()"), self.test) SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction) return True
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', 'segreg_{}.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 = segregDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Segreg') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'segreg') self.toolbar.setObjectName(u'segreg')
def mousePressEvent(self, event): anchor_item = self.scene.item_at(event.scenePos(), items.NodeAnchorItem, buttons=Qt.LeftButton) if anchor_item and event.button() == Qt.LeftButton: # Start a new link starting at item self.from_item = anchor_item.parentNodeItem() if isinstance(anchor_item, items.SourceAnchorItem): self.direction = NewLinkAction.FROM_SOURCE self.source_item = self.from_item else: self.direction = NewLinkAction.FROM_SINK self.sink_item = self.from_item event.accept() helpevent = QuickHelpTipEvent( self.tr("Create a new link"), self.tr('<h3>Create new link</h3>' '<p>Drag a link to an existing node or release on ' 'an empty spot to create a new node.</p>' # '<a href="help://orange-canvas/create-new-links">' # 'More ...</a>' ) ) QCoreApplication.postEvent(self.document, helpevent) return True else: # Whoever put us in charge did not know what he was doing. self.cancel(self.ErrorReason) return False
def end(self): self.cleanup() # Remove the help tip set in mousePressEvent self.macro = None helpevent = QuickHelpTipEvent("", "") QCoreApplication.postEvent(self.document, helpevent) UserInteraction.end(self)
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 startPlugin(packageName): """ initialize the plugin """ global plugins, active_plugins, iface if packageName in active_plugins: return False package = sys.modules[packageName] errMsg = QCoreApplication.translate("Python", "Couldn't load plugin %1" ).arg(packageName) # create an instance of the plugin try: plugins[packageName] = package.classFactory(iface) except: _unloadPluginModules(packageName) msg = QCoreApplication.translate("Python", "%1 due an error when calling its classFactory() method").arg(errMsg) showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg) return False # initGui try: plugins[packageName].initGui() except: del plugins[packageName] _unloadPluginModules(packageName) msg = QCoreApplication.translate("Python", "%1 due an error when calling its initGui() method" ).arg( errMsg ) showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg) return False # add to active plugins active_plugins.append(packageName) return True
def defineCharacteristicsFromFile(self): lines = open(self.descriptionFile) line = lines.readline().strip('\n').strip() self.name = line if '|' in self.name: tokens = self.name.split('|') self.name = tokens[0] self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name)) self.cmdname = tokens[1] else: self.cmdname = self.name self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name)) self.name = self.name[0].upper() + self.name[1:].lower() line = lines.readline().strip('\n').strip() self.undecoratedGroup = line self.group = SagaGroupNameDecorator.getDecoratedName(self.undecoratedGroup) self.i18n_group = QCoreApplication.translate("SAGAAlgorithm", self.group) line = lines.readline().strip('\n').strip() while line != '': if line.startswith('Hardcoded'): self.hardcodedStrings.append(line[len('Harcoded|') + 1:]) elif line.startswith('Parameter'): self.addParameter(getParameterFromString(line)) elif line.startswith('AllowUnmatching'): self.allowUnmatchingGridExtents = True elif line.startswith('Extent'): # An extent parameter that wraps 4 SAGA numerical parameters self.extentParamNames = line[6:].strip().split(' ') self.addParameter(ParameterExtent(self.OUTPUT_EXTENT, 'Output extent', '0,1,0,1')) else: self.addOutput(getOutputFromString(line)) line = lines.readline().strip('\n').strip() lines.close()
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', '{}_{}.qm'.format(DelimitationToolbox.__modname__, 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.dock = None
def removeDir(path): result = "" if not QFile(path).exists(): result = QCoreApplication.translate("QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path elif QFile(path).remove(): # if it is only link, just remove it without resolving. pass else: fltr = QDir.Dirs | QDir.Files | QDir.Hidden iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories) while iterator.hasNext(): item = iterator.next() if QFile(item).remove(): pass fltr = QDir.Dirs | QDir.Hidden iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories) while iterator.hasNext(): item = iterator.next() if QDir().rmpath(item): pass if QFile(path).exists(): result = QCoreApplication.translate("QgsPluginInstaller", "Failed to remove the directory:") + "\n" + path + "\n" + QCoreApplication.translate("QgsPluginInstaller", "Check permissions or remove it manually") # restore plugin directory if removed by QDir().rmpath() pluginDir = qgis.utils.home_plugin_path if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) return result
def switchToolMode( self ): self.setCommandViewerEnabled( not self.batchCheck.isChecked() ) self.progressBar.setVisible( self.batchCheck.isChecked() ) self.inSelector.setType( self.inSelector.FILE if self.batchCheck.isChecked() else self.inSelector.FILE_LAYER ) self.outSelector.clear() if self.batchCheck.isChecked(): self.inFileLabel = self.label.text() self.outFileLabel = self.label_2.text() self.label.setText( QCoreApplication.translate( "GdalTools", "&Input directory" ) ) self.label_2.setText( QCoreApplication.translate( "GdalTools", "&Output directory" ) ) QObject.disconnect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile ) QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit ) QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir ) QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir ) else: self.label.setText( self.inFileLabel ) self.label_2.setText( self.outFileLabel ) QObject.disconnect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir ) QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir ) QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile ) QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit )
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 = '%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) # menu && toolbars self.menu_name = self.tr(u'&RuGeocoder') self.toolbar = self.iface.addToolBar(self.menu_name) self.toolbar.setObjectName(u'RuGeocoderToolbar') # instances self.__converter_dlg = ConverterDialog() self.__geocoder_dlg = BatchGeocodingDialog() # Dock tree panel self.__quick_tlb = QuickGeocodingToolbox(self.iface) self.iface.addDockWidget(PluginSettings.dock_area(), self.__quick_tlb) self.__quick_tlb.setFloating(PluginSettings.dock_floating()) self.__quick_tlb.resize(PluginSettings.dock_size()) self.__quick_tlb.move(PluginSettings.dock_pos()) self.__quick_tlb.setVisible(PluginSettings.dock_visibility()) self.__quick_tlb.set_active_geocoder(PluginSettings.dock_geocoder_name()) self.__quick_tlb.setWindowIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))
def initGui(self): # Actions self.action_convert = QAction(QIcon(path.join(_current_path, '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(path.join(_current_path, 'icon.png')), QCoreApplication.translate('RuGeocoder', 'Batch geocoding'), self.iface.mainWindow()) QObject.connect(self.action_batch_geocoding, SIGNAL('triggered()'), self.run_batch) self.action_quick_geocoding = self.__quick_tlb.toggleViewAction() self.action_quick_geocoding.setIcon(QIcon(path.join(_current_path, 'edit-find-project.png'))) self.action_quick_geocoding.setText(QCoreApplication.translate('RuGeocoder', '&Quick geocoding toolbox')) # Add toolbar button and menu item self.toolbar.addAction(self.action_convert) self.iface.addPluginToWebMenu(self.menu_name, self.action_convert) self.toolbar.addAction(self.action_batch_geocoding) self.iface.addPluginToWebMenu(self.menu_name, self.action_batch_geocoding) self.toolbar.addSeparator() self.toolbar.addAction(self.action_quick_geocoding) self.iface.addPluginToWebMenu(self.menu_name, self.action_quick_geocoding)
def __init__(self): """ Constructor """ QDialog.__init__(self) self.setWindowTitle(QCoreApplication.translate("VDLTools", "Display Attributes Confirmation")) self.resize(300, 100) self.__layout = QGridLayout() self.__confirmLabel = QLabel( QCoreApplication.translate("VDLTools", "Do you want to display the attributes tables for the selected features ?")) self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 2) self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "Yes")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "No")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 1, 0) self.__layout.addWidget(self.__cancelButton, 1, 1) self.setLayout(self.__layout)
def __init__(self, layers): """ Constructor """ QDialog.__init__(self) self.__layers = layers self.setWindowTitle(QCoreApplication.translate("VDLTools", "Edition Confirmation")) self.__layout = QGridLayout() titleLabel = QLabel(QCoreApplication.translate("VDLTools", "Do you really want to edit these layers ?")) self.__layout.addWidget(titleLabel, 0, 0, 1, 2) pos = 1 for layer in self.__layers: label = QLabel(" - " + layer.name()) self.__layout.addWidget(label, pos, 0, 1, 2) pos += 1 self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) pos = len(self.__layers) + 1 self.__layout.addWidget(self.__cancelButton, pos, 0) self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, pos, 1) self.setLayout(self.__layout)
def __init__(self, parent): QDialog.__init__(self, parent) self.setWindowTitle(QCoreApplication.translate("SettingsDialogPythonConsole", "Settings Python Console")) self.parent = parent self.setupUi(self) self.listPath = [] self.lineEdit.setReadOnly(True) self.restoreSettings() self.initialCheck() self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.png")) self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path")) self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.png")) self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path")) self.preloadAPI.stateChanged.connect(self.initialCheck) self.addAPIpath.clicked.connect(self.loadAPIFile) self.removeAPIpath.clicked.connect(self.removeAPI) self.compileAPIs.clicked.connect(self._prepareAPI) self.resetFontColor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png")) self.resetFontColor.setIconSize(QSize(18, 18)) self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png")) self.resetFontColorEditor.setIconSize(QSize(18, 18)) self.resetFontColor.clicked.connect(self._resetFontColor) self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor)
def test_methodinvoke(self): executor = ThreadExecutor() state = [None, None] class StateSetter(QObject): @Slot(object) def set_state(self, value): state[0] = value state[1] = QThread.currentThread() def func(callback): callback(QThread.currentThread()) obj = StateSetter() f1 = executor.submit(func, methodinvoke(obj, "set_state", (object,))) f1.result() # So invoked method can be called QCoreApplication.processEvents() self.assertIs(state[1], QThread.currentThread(), "set_state was called from the wrong thread") self.assertIsNot(state[0], QThread.currentThread(), "set_state was invoked in the main thread") executor.shutdown(wait=True)
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 change_i18n(self, new_locale): """Change internationalisation for the plugin. Override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. :param new_locale: The new locale i.e. 'id', 'af', etc. :type new_locale: str :raises: TranslationLoadException """ os.environ['INASAFE_LANG'] = str(new_locale) LOGGER.debug('%s %s %s' % ( new_locale, QLocale.system().name(), os.environ['INASAFE_LANG'])) root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) translation_path = os.path.join( root, 'safe_qgis', 'i18n', 'inasafe_' + str(new_locale) + '.qm') if os.path.exists(translation_path): self.translator = QTranslator() result = self.translator.load(translation_path) if not result: message = 'Failed to load translation for %s' % new_locale raise TranslationLoadError(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(self.translator) LOGGER.debug('%s %s' % ( translation_path, os.path.exists(translation_path)))
def itemAction(self, mi,): # FIXME: use a MIME-Handler here i = self.model.itemFromIndex(mi) t, nc = i.ncItem QMessageBox.information(self, QCoreApplication.translate('NetCDF3', 'netCDF3: Item clicked'), QCoreApplication.translate('NetCDF3', 'You clicked an item in the netCDF3-browser'))
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 slotSave(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """改变当前的分辨率""" screenName = self.resolutionCombox.itemData(0, Qt.UserRole + 1).toString() if not screenName.isEmpty() and not screenName.isNull(): self.curResolutionValue = self.getCurrentScreenResolution(str(screenName)) if self.curResolutionValue: reScreen = self.resolutionCombox.currentText() if reScreen == "800x600": pass else: pass #弹出提示框,默认为取消 rb = MessageBox(self.tr("making sure set the resolution to current"), self).exec_() if rb == QDialog.Accepted: self.jytcapi.jysetdispconf(str(reScreen)) elif rb == QDialog.Rejected: pass
def _do_read(self): # Read messages from the socket and put them into the incoming queue # until nothing more can be read. while True: try: buf = self._socket.recv(4096) except socket.error as e: if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK): break self._log.error("recv() error {0}".format(e.errno)) self.close() break if buf == b"": self._log.error("peer closed connection") self.close() break # XXX: should not be using protocol private attributes # Expose .error and .get_message() ? nbytes = self._protocol.data_received(buf) if self._protocol._error: self._log.error("parse error {0!s}", self._protocol._error) self.close() break while self._protocol._queue.qsize(): message = self._protocol._queue.get(block=False) self._incoming.append(message) # Schedule a dispatch if there are incoming messages if self._incoming: QCoreApplication.instance().postEvent(self, _Dispatch())
def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.web_menu = '&MetaSearch' LOGGER.debug('Setting up i18n') 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(translate('Translation loaded: %s' % tr_file))
def slotShowRestartNetworkInfo(self, status): """显示重启网络的状态信息""" language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) if status == "Start": #InfoHintDialog(self.tr("restarting network, please wait ...")).exec_() self.waitingDlg.setHintInfo(self.tr("restarting network, please wait ...")) elif status == "Success": #InfoHintDialog(self.tr("network setting success")).exec_() self.waitingDlg.setHintInfo(self.tr("network setting success")) elif status == "Failed": #InfoHintDialog(self.tr("network restart failed")).exec_() self.waitingDlg.setHintInfo(self.tr("network restart failed")) else: return if self.waitingDlg.isHidden(): desktop = QApplication.desktop() self.waitingDlg.move((desktop.width() - self.waitingDlg.width())/2, (desktop.height() - self.waitingDlg.height())/2) self.waitingDlg.exec_()
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", "AttributeSplit_{}.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 = AttributeSplitDialog(iface) # Declare instance attributes self.actions = [] self.menu = self.tr(u"&Attribute Split") self.toolbar = self.iface.addToolBar(u"AttributeSplit") self.toolbar.setObjectName(u"AttributeSplit")
def scrollPage(self, degrees=180, afterScroll=None): # do 180 degree scroll down event = QWheelEvent(QCursor.pos(), -1 * (degrees / 15) * 120, Qt.MouseButtons(), Qt.KeyboardModifiers(), Qt.Vertical) QCoreApplication.postEvent(self, event) if afterScroll: afterScroll(self)
def main(): signal.signal(signal.SIGINT, sigint_handler) app = QCoreApplication(sys.argv) ex = GUIServer() sys.exit(app.exec_())
def restart(self, num_processors=None, wait=False): if num_processors is not None: assert sum(num_processors) <= MAX_NUMBER_PROCESSORS, \ 'total number of additional processors must be %d or less' % MAX_NUMBER_PROCESSORS # stop new items from being processed self.shutdown_processors() # attempt to stop current processors if self._local_file_thread is not None: self._local_file_thread.worker.stop() if self._local_folder_thread is not None: self._local_folder_thread.worker.stop() if self._remote_file_thread is not None: self._remote_file_thread.worker.stop() if self._remote_folder_thread is not None: self._remote_folder_thread.worker.stop() for p in self._processors_pool: p.worker.stop() if wait: while self.is_active(): QCoreApplication.processEvents() sleep(0.1) self.set_max_processors(num_processors) # re-enable new items to trigger processing self.init_processors() # launch processors for new items in the queue, if any self.launch_processors()
def popUp(self): """Popup from the tray""" # Reposition the window r = QDesktopWidget().availableGeometry() s = self.size() pos = getConfig(u"pos") if pos == u"Top right": x = r.left() + r.width()-s.width() y = r.top() elif pos == u"Top left": x = r.left() y = r.top() elif pos == u"Bottom right": x = r.left() + r.width()-s.width() y = r.top() + r.height()-s.height() elif pos == u"Bottom left": x = r.left() y = r.top() + r.height()-s.height() else: x = r.left() + r.width()/2 - s.width()/2 y = r.top() + r.height()/2 - s.height()/2 self.move(x, y) # Show it self.show() QCoreApplication.processEvents() self.raise_() self.activateWindow() # Focus the search box self.ui.lineEditQuery.selectAll() self.ui.lineEditQuery.setFocus()
def __onOk(self): """ When the Ok button in Import Jobs Dialog is pushed """ self.__jobsDlg.accept() codes = [] query = self.__db.exec_("""SELECT DISTINCT code FROM %s.%s""" % (self.__schemaDb, self.__configTable)) if query.lastError().isValid(): self.__iface.messageBar().pushMessage(query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) self.__cancel() else: while next(query): codes.append(query.value(0)) if self.__jobsDlg.jobsRadio().isChecked(): self.__jobs = self.__jobsDlg.jobs() # select geodata for insertion jobs = "" i = 0 for job in self.__jobs: if i == 0: i += 1 else: jobs += "," jobs += "'" + job + "'" condition = """usr_session_name IN (""" + jobs + """)""" else: ids = "" i = 0 for selected in self.__selectedFeatures: if i == 0: i += 1 else: ids += "," ids += "'" + str(selected) + "'" condition = """id IN (""" + ids + """)""" query = self.__db.exec_( """SELECT code,usr_fk_table,geometry,id,usr_session_name FROM %s WHERE %s AND usr_valid = FALSE""" % (self.__sourceTable, condition)) if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: self.__data = [] while next(query): code = int(query.value(0)) if code in codes: data = { 'code': code, 'id_table': query.value(1), 'geom': query.value(2), 'id_survey': query.value(3), 'job': query.value(4) } # select schema and id for insertion table query2 = self.__db.exec_( """SELECT schema, name FROM qwat_sys.doctables WHERE id = %s""" % str(data['id_table'])) if query2.lastError().isValid(): self.__iface.messageBar().pushMessage( query2.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: next(query2) data['schema_table'] = query2.value(0) data['name_table'] = query2.value(1) self.__data.append(data) else: self.__iface.messageBar( ).pushMessage(QCoreApplication.translate( "VDLTools", "Code not in config table, measure not processed"), level=QgsMessageBar.CRITICAL, duration=0) self.__checkIfExist()
def flush(self): QCoreApplication.flush()
def delay_method_call(self, *args, **kwargs): event = QueuedCallEvent(method.__get__(self), args, kwargs) QCoreApplication.postEvent(self, event)
class TestQgsNetworkContentFetcher(TestCase): @classmethod def setUpClass(cls): # Bring up a simple HTTP server os.chdir(unitTestDataPath() + '') handler = SimpleHTTPServer.SimpleHTTPRequestHandler cls.httpd = SocketServer.TCPServer(('localhost', PORT), handler) cls.httpd_thread = threading.Thread(target=cls.httpd.serve_forever) cls.httpd_thread.setDaemon(True) cls.httpd_thread.start() def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) self.loaded = False self.app = QCoreApplication([]) def contentLoaded(self): self.loaded = True def testFetchEmptyUrl(self): fetcher = QgsNetworkContentFetcher() self.loaded = False fetcher.fetchContent(QUrl()) fetcher.finished.connect(self.contentLoaded) while not self.loaded: self.app.processEvents() r = fetcher.reply() assert r.error() != QNetworkReply.NoError def testFetchBadUrl(self): fetcher = QgsNetworkContentFetcher() self.loaded = False fetcher.fetchContent(QUrl('http://x')) fetcher.finished.connect(self.contentLoaded) while not self.loaded: self.app.processEvents() r = fetcher.reply() assert r.error() != QNetworkReply.NoError def testFetchUrlContent(self): fetcher = QgsNetworkContentFetcher() self.loaded = False fetcher.fetchContent( QUrl('http://localhost:' + str(PORT) + '/qgis_local_server/index.html')) fetcher.finished.connect(self.contentLoaded) while not self.loaded: self.app.processEvents() r = fetcher.reply() assert r.error() == QNetworkReply.NoError, r.error() html = fetcher.contentAsString() assert 'QGIS' in html def testDoubleFetch(self): fetcher = QgsNetworkContentFetcher() self.loaded = False fetcher.fetchContent(QUrl('http://www.qgis.org/')) # double fetch - this should happen before previous request finishes fetcher.fetchContent( QUrl('http://localhost:' + str(PORT) + '/qgis_local_server/index.html')) fetcher.finished.connect(self.contentLoaded) while not self.loaded: self.app.processEvents() r = fetcher.reply() assert r.error() == QNetworkReply.NoError, r.error() html = fetcher.contentAsString() assert 'QGIS' in html def testFetchEncodedContent(self): fetcher = QgsNetworkContentFetcher() self.loaded = False fetcher.fetchContent( QUrl('http://localhost:' + str(PORT) + '/encoded_html.html')) fetcher.finished.connect(self.contentLoaded) while not self.loaded: self.app.processEvents() r = fetcher.reply() assert r.error() == QNetworkReply.NoError, r.error() html = fetcher.contentAsString() assert unichr(6040) in html
def tr(self, message): return QCoreApplication.translate('QgisODK', message)
def tr(self, message): return QCoreApplication.translate('AGCloacas', message)
def start(self): """ To start the importation """ if self.ownSettings is None: self.__iface.messageBar().pushMessage(QCoreApplication.translate( "VDLTools", "No settings given !!"), level=QgsMessageBar.CRITICAL, duration=0) return if self.ownSettings.uriDb is None: self.__iface.messageBar().pushMessage(QCoreApplication.translate( "VDLTools", "No import db given !!"), level=QgsMessageBar.CRITICAL, duration=0) return if self.ownSettings.schemaDb is None: self.__iface.messageBar().pushMessage(QCoreApplication.translate( "VDLTools", "No db schema given !!"), level=QgsMessageBar.CRITICAL, duration=0) return if self.ownSettings.configTable is None: self.__iface.messageBar().pushMessage(QCoreApplication.translate( "VDLTools", "No config table given !!"), level=QgsMessageBar.CRITICAL, duration=0) return self.__configTable = self.ownSettings.configTable self.__schemaDb = self.ownSettings.schemaDb self.__connector = DBConnector(self.ownSettings.uriDb, self.__iface) self.__db = self.__connector.setConnection() if self.__db is not None: query = self.__db.exec_( """SELECT DISTINCT sourcelayer_name FROM %s.%s WHERE sourcelayer_name IS NOT NULL""" % (self.__schemaDb, self.__configTable)) if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) self.__cancel() else: while next(query): if self.__sourceTable == "": self.__sourceTable = query.value(0) elif self.__sourceTable != query.value(0): self.__iface.messageBar().pushMessage( QCoreApplication.translate( "VDLTools", "different sources in config table ?!?"), level=QgsMessageBar.WARNING) for layer in self.__iface.mapCanvas().layers(): if layer is not None and layer.type() == QgsMapLayer.VectorLayer and \ layer.providerType() == "postgres": uri = QgsDataSourceURI(layer.source()) if self.__sourceTable == uri.schema( ) + "." + uri.table(): self.__selectedFeatures = [] for f in layer.selectedFeatures(): self.__selectedFeatures.append( f.attribute("ID")) break # select jobs query = self.__db.exec_( ("""SELECT DISTINCT usr_session_name FROM %s WHERE """ % self.__sourceTable) + """usr_valid = FALSE AND usr_session_name IS NOT NULL""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) self.__cancel() else: jobs = [] while next(query): jobs.append(query.value(0)) if len(jobs) == 0 and (self.__selectedFeatures is None or len(self.__selectedFeatures) == 0): self.__cancel() else: selected = True if self.__selectedFeatures is None or len( self.__selectedFeatures) == 0: selected = False self.__jobsDlg = ImportJobsDialog(jobs, selected) self.__jobsDlg.jobsRadio().clicked.connect( self.__onJobsRadio) if self.__jobsDlg.pointsRadio() is not None: self.__jobsDlg.pointsRadio().clicked.connect( self.__onPointsRadio) self.__jobsDlg.rejected.connect(self.__cancel) self.__jobsDlg.okButton().clicked.connect(self.__onOk) self.__jobsDlg.cancelButton().clicked.connect( self.__onCancel) self.__jobsDlg.show()
def __insert(self): """ To insert the data into the tables """ not_added = [] for data in self.__data: if data['add']: destLayer = "" request = """INSERT INTO %s.%s""" % (data['schema_table'], data['name_table']) columns = "(id,geometry3d" values = """(nextval('%s.%s_id_seq'::regclass),'%s'""" \ % (data['schema_table'], data['name_table'], data['geom']) # select import data for insertion query = self.__db.exec_( """SELECT destinationlayer_name,destinationcolumn_name,static_value FROM """ + """"%s.%s WHERE code = '%s' AND static_value IS NOT NULL""" % (self.__schemaDb, self.__configTable, str(data['code']))) if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): if destLayer == "": destLayer = query.value(0) elif destLayer != query.value(0): self.__iface.messageBar( ).pushMessage(QCoreApplication.translate( "VDLTools", "different destination layer in config table ?!?" ), level=QgsMessageBar.WARNING) columns += "," + query.value(1) values += "," + query.value(2) columns += ")" values += ")" request += """ %s VALUES %s RETURNING id""" % (columns, values) # insert data query2 = self.__db.exec_(request) if query2.lastError().isValid(): self.__iface.messageBar().pushMessage( query2.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: self.__num += 1 query2.first() id_object = query2.value(0) # update source table query3 = self.__db.exec_(( """UPDATE %s SET usr_valid_date = '%s', usr_valid = TRUE, usr_fk_network_element = %s,""" % (self.__sourceTable, str(datetime.date(datetime.now())), str(id_object)) ) + ( """ usr_fk_table = %s, usr_import_user = '******' WHERE id = %s""" % (str(data['id_table']), self.__db.userName(), str(data['id_survey'])))) if query3.lastError().isValid(): self.__iface.messageBar().pushMessage( query3.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: not_added.append(data) if len(not_added) > 0: self.__measDlg = ImportMeasuresDialog(not_added) self.__measDlg.rejected.connect(self.__validAndNext) self.__measDlg.accepted.connect(self.__deleteAndNext) self.__measDlg.okButton().clicked.connect(self.__onDeleteOk) self.__measDlg.cancelButton().clicked.connect( self.__onDeleteCancel) self.__measDlg.show() else: self.__conclude()
def tr(self, message): return QCoreApplication.translate('Catchments', message)
def __init__(self, situations, differences, names, points): """ Constructor :param situations: situations, when point and vertex elevations are different :param differences: when lines vertex elevations are different on position connection :param names: layers names :param points: vertices positions """ QDialog.__init__(self) self.__situations = situations self.__differences = differences self.__names = names num_lines = len(points[0]['z']) - len(names) + 1 self.__points = points self.setWindowTitle(QCoreApplication.translate("VDLTools","Elevations situations")) self.resize(300, 100) self.__layout = QGridLayout() self.__msgLabels = [] self.__msgChecks = [] self.__difLabels = [] for i in xrange(len(self.__situations)): line = self.__situations[i] ptz = self.__points[line['point']]['z'] msg = "- point " + str(line['point']) + QCoreApplication.translate("VDLTools"," in layer '") + \ self.__names[line['layer']] + "' (point: " + str(ptz[line['layer']+num_lines-1]) + "m |" + \ QCoreApplication.translate("VDLTools","line vertex: ") + str(line['vertex']) + "m) \n" msgLabel = QLabel(msg) self.__msgLabels.append(msgLabel) self.__layout.addWidget(self.__msgLabels[i], i+1, 0, 1, 2) msgCheck = QCheckBox() msgCheck.setChecked(True) self.__msgChecks.append(msgCheck) self.__layout.addWidget(self.__msgChecks[i], i+1, 2) for i in xrange(len(self.__differences)): line = self.__differences[i] msg = "- point " + str(line['point']) + \ QCoreApplication.translate("VDLTools"," in layer : different elevations on same position ") + "(" +\ str(line['v1']) + "m and" + str(line['v2']) + "m) \n" difLabel = QLabel(msg) self.__difLabels.append(difLabel) self.__layout.addWidget(self.__difLabels[i], len(self.__situations) + (i+1), 0, 1, 2) self.__passButton = QPushButton(QCoreApplication.translate("VDLTools","Pass")) self.__passButton.setMinimumHeight(20) self.__passButton.setMinimumWidth(100) pos = len(self.__situations) + len(self.__differences) + 1 self.__layout.addWidget(self.__passButton, pos, 0) self.__onPointsButton = QPushButton(QCoreApplication.translate("VDLTools", "Apply line elevations to points")) self.__onPointsButton.setMinimumHeight(20) self.__onPointsButton.setMinimumWidth(200) self.__onLineButton = QPushButton(QCoreApplication.translate("VDLTools", "Apply points elevations to line")) self.__onLineButton.setMinimumHeight(20) self.__onLineButton.setMinimumWidth(200) if len(self.__situations) > 0: self.__layout.addWidget(self.__onLineButton, pos, 1) self.__layout.addWidget(self.__onPointsButton, pos, 2) self.setLayout(self.__layout)
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('AL\'EXA-IDE') QCoreApplication.setOrganizationDomain('AL\'EXA-IDE') QCoreApplication.setApplicationName('AL\'EXA-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() qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) 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: lineno = fileData[1] tempFiles.append((fileData[0], lineno)) 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_) lineno = fileData[1] tempFiles.append((fileData[0], lineno)) 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() ide.show_python_detection() sys.exit(app.exec_())
def tr(string, context=''): if context == '': context = 'RUtils' return QCoreApplication.translate(context, string)
def tr(self, string, context=''): if context == '': context = self.__class__.__name__ return QCoreApplication.translate(context, string)
def toolName(self): """ To get the tool name :return: tool name """ return QCoreApplication.translate("VDLTools", "Duplicate")
def started(self, title): self.dialog = QProgressDialog(title, "Stop", 0, 0, self.parent) self.dialog.setCancelButton(None) self.dialog.show() QCoreApplication.processEvents(QEventLoop.AllEvents)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOut) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open file") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCutEditorConsole.png")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Settings") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon( QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Import Processing class loadProcessingBt = QCoreApplication.translate( "PythonConsole", "Import Processing class") self.loadProcessingButton = QAction(self) self.loadProcessingButton.setCheckable(False) self.loadProcessingButton.setEnabled(True) self.loadProcessingButton.setIcon( QgsApplication.getThemeIcon("console/iconProcessingConsole.png")) self.loadProcessingButton.setMenuRole(QAction.PreferencesRole) self.loadProcessingButton.setIconVisibleInMenu(True) self.loadProcessingButton.setToolTip(loadProcessingBt) self.loadProcessingButton.setText(loadProcessingBt) ## Import QtCore class loadQtCoreBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore class") self.loadQtCoreButton = QAction(self) self.loadQtCoreButton.setCheckable(False) self.loadQtCoreButton.setEnabled(True) self.loadQtCoreButton.setIcon( QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")) self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole) self.loadQtCoreButton.setIconVisibleInMenu(True) self.loadQtCoreButton.setToolTip(loadQtCoreBt) self.loadQtCoreButton.setText(loadQtCoreBt) ## Import QtGui class loadQtGuiBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui class") self.loadQtGuiButton = QAction(self) self.loadQtGuiButton.setCheckable(False) self.loadQtGuiButton.setEnabled(True) self.loadQtGuiButton.setIcon( QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")) self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole) self.loadQtGuiButton.setIconVisibleInMenu(True) self.loadQtGuiButton.setToolTip(loadQtGuiBt) self.loadQtGuiButton.setText(loadQtGuiBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(24, 24)) self.toolBar.setOrientation(Qt.Vertical) self.toolBar.setMovable(True) self.toolBar.setFloatable(True) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() # self.toolBarEditor.setStyleSheet('QToolBar{background-color: rgb(%s, %s, %s' % tuple(bkgrcolor) + ');\ # border-right: 1px solid rgb(%s, %s, %s' % tuple(bordercl) + ');}') self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(18, 18)) self.toolBarEditor.setOrientation(Qt.Vertical) self.toolBarEditor.setMovable(True) self.toolBarEditor.setFloatable(True) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) ## Menu Import Class self.classMenu = QMenu() self.classMenu.addAction(self.loadProcessingButton) self.classMenu.addAction(self.loadQtCoreButton) self.classMenu.addAction(self.loadQtGuiButton) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.widgetButtonEditor, 0, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 1, 1, 1, 1) self.toolBarLayout = QGridLayout(self.widgetButton) self.toolBarLayout.setMargin(0) self.toolBarLayout.setSpacing(0) self.toolBarLayout.addWidget(self.toolBar) self.toolBarEditorLayout = QGridLayout(self.widgetButtonEditor) self.toolBarEditorLayout.setMargin(0) self.toolBarEditorLayout.setSpacing(0) self.toolBarEditorLayout.addWidget(self.toolBarEditor) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") if pyqtconfig.Configuration().qt_version >= 0x40700: self.lineEditFind.setPlaceholderText(placeHolderTxt) else: self.lineEditFind.setToolTip(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.toggled.connect(self.findTextEditor) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.loadProcessingButton.triggered.connect(self.processing) self.loadQtCoreButton.triggered.connect(self.qtCore) self.loadQtGuiButton.triggered.connect(self.qtGui) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.connect(self.listClassMethod, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findText) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged)
class ParametersPanel(BASE, WIDGET): NOT_SELECTED = QCoreApplication.translate('ParametersPanel', '[Not selected]') def __init__(self, parent, alg): super(ParametersPanel, self).__init__(None) self.setupUi(self) self.grpAdvanced.hide() self.layoutMain = self.scrollAreaWidgetContents.layout() self.layoutAdvanced = self.grpAdvanced.layout() self.parent = parent self.alg = alg self.valueItems = {} self.labels = {} self.widgets = {} self.checkBoxes = {} self.dependentItems = {} self.iterateButtons = {} self.initWidgets() def layerAdded(self, layer): if layer.type() == QgsMapLayer.VectorLayer: for param in self.alg.parameters: if param.hidden: continue if isinstance(param, ParameterVector): if dataobjects.canUseVectorLayer(layer, param.shapetype): widget = self.valueItems[param.name] if isinstance(widget, InputLayerSelectorPanel): widget = widget.cmbText widget.addItem(self.getExtendedLayerName(layer), layer) elif layer.type( ) == QgsMapLayer.RasterLayer and dataobjects.canUseRasterLayer(layer): for param in self.alg.parameters: if param.hidden: continue if isinstance(param, ParameterRaster): widget = self.valueItems[param.name].cmbText widget.addItem(self.getExtendedLayerName(layer), layer) self.updateMultipleInputs() def layersWillBeRemoved(self, layers): for layer in layers: self.layerRemoved(layer) def layerRemoved(self, layer): layer = QgsMapLayerRegistry.instance().mapLayer(layer) widget = None if layer.type() == QgsMapLayer.VectorLayer: for param in self.alg.parameters: if param.hidden: continue if isinstance(param, ParameterVector): widget = self.valueItems[param.name] if isinstance(widget, InputLayerSelectorPanel): widget = widget.cmbText elif layer.type() == QgsMapLayer.RasterLayer: for param in self.alg.parameters: if param.hidden: continue if isinstance(param, ParameterRaster): widget = self.valueItems[param.name].cmbText if widget is not None: idx = widget.findData(layer) if idx != -1: widget.removeItem(idx) self.updateMultipleInputs() def updateMultipleInputs(self): for param in self.alg.parameters: if isinstance( param, ParameterMultipleInput ) and param.datatype != ParameterMultipleInput.TYPE_FILE: if param.datatype == ParameterMultipleInput.TYPE_RASTER: options = dataobjects.getRasterLayers(sorting=False) elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = dataobjects.getVectorLayers(sorting=False) else: options = dataobjects.getVectorLayers([param.datatype], sorting=False) opts = [self.getExtendedLayerName(opt) for opt in options] widget = self.valueItems[param.name] widget.updateForOptions(opts) def initWidgets(self): #tooltips = self.alg.getParameterDescriptions() # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameters: if param.isAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts for param in self.alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') try: if param.optional: desc += self.tr(' [optional]') except: pass widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if isinstance(param, ParameterVector) and \ not self.alg.allowOnlyOpenedLayers: layout = QHBoxLayout() layout.setSpacing(2) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setToolTip(self.tr('Iterate over this layer')) button.setCheckable(True) layout.addWidget(button) self.iterateButtons[param.name] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) #~ if param.name in tooltips.keys(): #~ tooltip = tooltips[param.name] #~ else: #~ tooltip = param.description #~ widget.setToolTip(tooltip) if isinstance(param, ParameterBoolean): widget.setText(desc) if param.isAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget(self.layoutMain.count() - 2, widget) else: label = QLabel(desc) #label.setToolTip(tooltip) self.labels[param.name] = label if param.isAdvanced: self.layoutAdvanced.addWidget(label) self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget(self.layoutMain.count() - 2, label) self.layoutMain.insertWidget(self.layoutMain.count() - 2, widget) self.widgets[param.name] = widget for output in self.alg.outputs: if output.hidden: continue label = QLabel(output.description) widget = OutputSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (OutputRaster, OutputVector, OutputTable)): check = QCheckBox() check.setText( self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.valueItems[output.name] = widget def buttonToggled(self, value): if value: sender = self.sender() for button in self.iterateButtons.values(): if button is not sender: button.setChecked(False) def getExtendedLayerName(self, layer): authid = layer.crs().authid() if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \ and authid is not None: return u'{} [{}]'.format(layer.name(), authid) else: return layer.name() def getWidgetFromParameter(self, param): # TODO Create Parameter widget class that holds the logic # for creating a widget that belongs to the parameter. if isinstance(param, ParameterRaster): layers = dataobjects.getRasterLayers() items = [] if param.optional: items.append((self.NOT_SELECTED, None)) for layer in layers: items.append((self.getExtendedLayerName(layer), layer)) item = InputLayerSelectorPanel(items, param) elif isinstance(param, ParameterVector): if self.somethingDependsOnThisParameter( param) or self.alg.allowOnlyOpenedLayers: item = QComboBox() layers = dataobjects.getVectorLayers(param.shapetype) layers.sort(key=lambda lay: lay.name()) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.getExtendedLayerName(layer), layer) item.currentIndexChanged.connect(self.updateDependentFields) item.name = param.name else: layers = dataobjects.getVectorLayers(param.shapetype) items = [] if param.optional: items.append((self.NOT_SELECTED, None)) for layer in layers: items.append((self.getExtendedLayerName(layer), layer)) # if already set, put first in list for i, (name, layer) in enumerate(items): if layer and layer.source() == param.value: items.insert(0, items.pop(i)) item = InputLayerSelectorPanel(items, param) elif isinstance(param, ParameterTable): if self.somethingDependsOnThisParameter(param): item = QComboBox() layers = dataobjects.getTables() if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(layer.name(), layer) item.currentIndexChanged.connect(self.updateDependentFields) item.name = param.name else: layers = dataobjects.getTables() items = [] if param.optional: items.append((self.NOT_SELECTED, None)) for layer in layers: items.append((layer.name(), layer)) # if already set, put first in list for i, (name, layer) in enumerate(items): if layer and layer.source() == param.value: items.insert(0, items.pop(i)) item = InputLayerSelectorPanel(items, param) elif isinstance(param, ParameterBoolean): item = QCheckBox() if param.default: item.setChecked(True) else: item.setChecked(False) elif isinstance(param, ParameterTableField): item = QComboBox() if param.parent in self.dependentItems: items = self.dependentItems[param.parent] else: items = [] self.dependentItems[param.parent] = items items.append(param.name) parent = self.alg.getParameterFromName(param.parent) if isinstance(parent, ParameterVector): layers = dataobjects.getVectorLayers(parent.shapetype) else: layers = dataobjects.getTables() if len(layers) > 0: if param.optional: item.addItem(self.tr('[not set]')) item.addItems(self.getFields(layers[0], param.datatype)) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) if param.default: item.setCurrentIndex(param.default) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterFile): item = FileSelectionPanel(param.isFolder, param.ext) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_FILE: item = MultipleInputPanel( datatype=ParameterMultipleInput.TYPE_FILE) else: if param.datatype == ParameterMultipleInput.TYPE_RASTER: options = dataobjects.getRasterLayers(sorting=False) elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = dataobjects.getVectorLayers(sorting=False) else: options = dataobjects.getVectorLayers([param.datatype], sorting=False) opts = [self.getExtendedLayerName(opt) for opt in options] item = MultipleInputPanel(opts) elif isinstance(param, ParameterNumber): item = NumberInputPanel(param.default, param.min, param.max, param.isInteger) elif isinstance(param, ParameterExtent): item = ExtentSelectionPanel(self.parent, self.alg, param.default) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterString): if param.multiline: verticalLayout = QVBoxLayout() verticalLayout.setSizeConstraint(QLayout.SetDefaultConstraint) textEdit = QPlainTextEdit() if param.default: textEdit.setPlainText(param.default) verticalLayout.addWidget(textEdit) item = textEdit else: item = QLineEdit() if param.default: item.setText(unicode(param.default)) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) if param.left: widget = self.valueItems[param.left] if isinstance(widget, InputLayerSelectorPanel): widget = widget.cmbText widget.currentIndexChanged.connect(item.onLeftLayerChange) item.leftLayer = widget.itemData(widget.currentIndex()) if param.right: widget = self.valueItems[param.right] if isinstance(widget, InputLayerSelectorPanel): widget = widget.cmbText widget.currentIndexChanged.connect(item.onRightLayerChange) item.rightLayer = widget.itemData(widget.currentIndex()) item.updatePredicates() if param.default: item.setValue(param.default) else: item = QLineEdit() if param.default: item.setText(unicode(param.default)) return item def updateDependentFields(self): sender = self.sender() if not isinstance(sender, QComboBox): return if sender.name not in self.dependentItems: return layer = sender.itemData(sender.currentIndex()) children = self.dependentItems[sender.name] for child in children: widget = self.valueItems[child] widget.clear() if self.alg.getParameterFromName(child).optional: widget.addItem(self.tr('[not set]')) widget.addItems( self.getFields(layer, self.alg.getParameterFromName(child).datatype)) def getFields(self, layer, datatype): fieldTypes = [] if datatype == ParameterTableField.DATA_TYPE_STRING: fieldTypes = [QVariant.String] elif datatype == ParameterTableField.DATA_TYPE_NUMBER: fieldTypes = [ QVariant.Int, QVariant.Double, QVariant.ULongLong, QVariant.UInt ] fieldNames = set() for field in layer.pendingFields(): if not fieldTypes or field.type() in fieldTypes: fieldNames.add(unicode(field.name())) return sorted(list(fieldNames), cmp=locale.strcoll) def somethingDependsOnThisParameter(self, parent): for param in self.alg.parameters: if isinstance(param, ParameterTableField): if param.parent == parent.name: return True return False
def progress(self, msg, percent): self.dialog.setLabelText(msg) # otherwise KProgressDialog automatically closes itself, sigh if percent < 100: self.dialog.setValue(percent) QCoreApplication.processEvents(QEventLoop.AllEvents)
def tr(self, message): return QCoreApplication.translate('SUEWSAnalyzer', message)
def initGui(self): if int(self.QgisVersion) < 1: QMessageBox.warning( self.iface.getMainWindow(), "fTools", QCoreApplication.translate("fTools", "QGIS version detected: ") + unicode(self.QgisVersion) + ".xx\n" + QCoreApplication.translate( "fTools", "This version of fTools requires at least QGIS version 1.0.0\nPlugin will not be enabled." )) return None QObject.connect(self.iface, SIGNAL("currentThemeChanged (QString)"), self.updateThemeIcons) self.analysisMenu = QMenu( QCoreApplication.translate("fTools", "&Analysis Tools")) self.analysisMenu.setObjectName("analysisMenu") self.distMatrix = QAction( QCoreApplication.translate("fTools", "Distance Matrix..."), self.iface.mainWindow()) self.distMatrix.setObjectName("distMatrix") self.sumLines = QAction( QCoreApplication.translate("fTools", "Sum Line Lengths..."), self.iface.mainWindow()) self.sumLines.setObjectName("sumLines") self.pointsPoly = QAction( QCoreApplication.translate("fTools", "Points in Polygon..."), self.iface.mainWindow()) self.pointsPoly.setObjectName("pointsPoly") self.compStats = QAction( QCoreApplication.translate("fTools", "Basic Statistics..."), self.iface.mainWindow()) self.compStats.setObjectName("compStats") self.listUnique = QAction( QCoreApplication.translate("fTools", "List Unique Values..."), self.iface.mainWindow()) self.listUnique.setObjectName("listUnique") self.nearestNeigh = QAction( QCoreApplication.translate("fTools", "Nearest Neighbour Analysis..."), self.iface.mainWindow()) self.nearestNeigh.setObjectName("nearestNeigh") self.meanCoords = QAction( QCoreApplication.translate("fTools", "Mean Coordinate(s)..."), self.iface.mainWindow()) self.meanCoords.setObjectName("meanCoords") self.intLines = QAction( QCoreApplication.translate("fTools", "Line Intersections..."), self.iface.mainWindow()) self.intLines.setObjectName("intLines") self.analysisMenu.addActions([ self.distMatrix, self.sumLines, self.pointsPoly, self.listUnique, self.compStats, self.nearestNeigh, self.meanCoords, self.intLines ]) self.researchMenu = QMenu( QCoreApplication.translate("fTools", "&Research Tools")) self.researchMenu.setObjectName("researchMenu") self.randSel = QAction( QCoreApplication.translate("fTools", "Random Selection..."), self.iface.mainWindow()) self.randSel.setObjectName("randSel") self.randSub = QAction( QCoreApplication.translate("fTools", "Random Selection Within Subsets..."), self.iface.mainWindow()) self.randSub.setObjectName("randSub") self.randPoints = QAction( QCoreApplication.translate("fTools", "Random Points..."), self.iface.mainWindow()) self.randPoints.setObjectName("randPoints") self.regPoints = QAction( QCoreApplication.translate("fTools", "Regular Points..."), self.iface.mainWindow()) self.regPoints.setObjectName("regPoints") self.vectGrid = QAction( QCoreApplication.translate("fTools", "Vector Grid..."), self.iface.mainWindow()) self.vectGrid.setObjectName("vectGrid") self.selectLocation = QAction( QCoreApplication.translate("fTools", "Select by Location..."), self.iface.mainWindow()) self.selectLocation.setObjectName("selectLocation") self.layerExtent = QAction( QCoreApplication.translate("fTools", "Polygon from Layer Extent..."), self.iface.mainWindow()) self.layerExtent.setObjectName("layerExtent") self.researchMenu.addActions([ self.randSel, self.randSub, self.randPoints, self.regPoints, self.vectGrid, self.selectLocation, self.layerExtent ]) self.geoMenu = QMenu( QCoreApplication.translate("fTools", "&Geoprocessing Tools")) self.geoMenu.setObjectName("geoMenu") self.minConvex = QAction( QCoreApplication.translate("fTools", "Convex Hull(s)..."), self.iface.mainWindow()) self.minConvex.setObjectName("minConvex") self.dynaBuffer = QAction( QCoreApplication.translate("fTools", "Buffer(s)..."), self.iface.mainWindow()) self.dynaBuffer.setObjectName("dynaBuffer") self.intersect = QAction( QCoreApplication.translate("fTools", "Intersect..."), self.iface.mainWindow()) self.intersect.setObjectName("intersect") self.union = QAction(QCoreApplication.translate("fTools", "Union..."), self.iface.mainWindow()) self.union.setObjectName("union") self.symDifference = QAction( QCoreApplication.translate("fTools", "Symmetrical Difference..."), self.iface.mainWindow()) self.symDifference.setObjectName("symDifference") self.clip = QAction(QCoreApplication.translate("fTools", "Clip..."), self.iface.mainWindow()) self.clip.setObjectName("clip") self.dissolve = QAction( QCoreApplication.translate("fTools", "Dissolve..."), self.iface.mainWindow()) self.dissolve.setObjectName("dissolve") self.erase = QAction( QCoreApplication.translate("fTools", "Difference..."), self.iface.mainWindow()) self.erase.setObjectName("erase") self.eliminate = QAction( QCoreApplication.translate("fTools", "Eliminate Sliver Polygons..."), self.iface.mainWindow()) self.eliminate.setObjectName("eliminate") self.geoMenu.addActions([ self.minConvex, self.dynaBuffer, self.intersect, self.union, self.symDifference, self.clip, self.erase, self.dissolve, self.eliminate ]) self.conversionMenu = QMenu( QCoreApplication.translate("fTools", "G&eometry Tools")) self.conversionMenu.setObjectName("conversionMenu") self.compGeo = QAction( QCoreApplication.translate("fTools", "Export/Add Geometry Columns..."), self.iface.mainWindow()) self.compGeo.setObjectName("compGeo") self.checkGeom = QAction( QCoreApplication.translate("fTools", "Check Geometry Validity..."), self.iface.mainWindow()) self.checkGeom.setObjectName("checkGeom") self.centroids = QAction( QCoreApplication.translate("fTools", "Polygon Centroids..."), self.iface.mainWindow()) self.centroids.setObjectName("centroids") self.delaunay = QAction( QCoreApplication.translate("fTools", "Delaunay Triangulation..."), self.iface.mainWindow()) self.delaunay.setObjectName("delaunay") self.voronoi = QAction( QCoreApplication.translate("fTools", "Voronoi Polygons..."), self.iface.mainWindow()) self.voronoi.setObjectName("voronoi") self.extNodes = QAction( QCoreApplication.translate("fTools", "Extract Nodes..."), self.iface.mainWindow()) self.extNodes.setObjectName("extNodes") self.simplify = QAction( QCoreApplication.translate("fTools", "Simplify Geometries..."), self.iface.mainWindow()) self.simplify.setObjectName("simplify") self.densify = QAction( QCoreApplication.translate("fTools", "Densify Geometries..."), self.iface.mainWindow()) self.densify.setObjectName("densify") self.multiToSingle = QAction( QCoreApplication.translate("fTools", "Multipart to Singleparts..."), self.iface.mainWindow()) self.multiToSingle.setObjectName("multiToSingle") self.singleToMulti = QAction( QCoreApplication.translate("fTools", "Singleparts to Multipart..."), self.iface.mainWindow()) self.singleToMulti.setObjectName("singleToMulti") self.polysToLines = QAction( QCoreApplication.translate("fTools", "Polygons to Lines..."), self.iface.mainWindow()) self.polysToLines.setObjectName("polysToLines") self.linesToPolys = QAction( QCoreApplication.translate("fTools", "Lines to Polygons..."), self.iface.mainWindow()) self.linesToPolys.setObjectName("linesToPolys") self.conversionMenu.addActions([ self.checkGeom, self.compGeo, self.centroids, self.delaunay, self.voronoi, self.simplify, self.densify, self.multiToSingle, self.singleToMulti, self.polysToLines, self.linesToPolys, self.extNodes ]) self.dataManageMenu = QMenu( QCoreApplication.translate("fTools", "&Data Management Tools")) self.dataManageMenu.setObjectName("dataManageMenu") self.define = QAction( QCoreApplication.translate("fTools", "Define Current Projection..."), self.iface.mainWindow()) self.define.setObjectName("define") self.spatJoin = QAction( QCoreApplication.translate("fTools", "Join Attributes by Location..."), self.iface.mainWindow()) self.spatJoin.setObjectName("spatJoin") self.splitVect = QAction( QCoreApplication.translate("fTools", "Split Vector Layer..."), self.iface.mainWindow()) self.splitVect.setObjectName("splitVect") self.mergeShapes = QAction( QCoreApplication.translate("fTools", "Merge Shapefiles to One..."), self.iface.mainWindow()) self.mergeShapes.setObjectName("mergeShapes") self.spatialIndex = QAction( QCoreApplication.translate("fTools", "Create Spatial Index..."), self.iface.mainWindow()) self.spatialIndex.setObjectName("spatialIndex") self.dataManageMenu.addActions([ self.define, self.spatJoin, self.splitVect, self.mergeShapes, self.spatialIndex ]) self.updateThemeIcons("theme") self.menu = self.iface.vectorMenu() self.menu.addMenu(self.analysisMenu) self.menu.addMenu(self.researchMenu) self.menu.addMenu(self.geoMenu) self.menu.addMenu(self.conversionMenu) self.menu.addMenu(self.dataManageMenu) QObject.connect(self.distMatrix, SIGNAL("triggered()"), self.dodistMatrix) QObject.connect(self.sumLines, SIGNAL("triggered()"), self.dosumLines) QObject.connect(self.pointsPoly, SIGNAL("triggered()"), self.dopointsPoly) QObject.connect(self.compStats, SIGNAL("triggered()"), self.docompStats) QObject.connect(self.listUnique, SIGNAL("triggered()"), self.dolistUnique) QObject.connect(self.nearestNeigh, SIGNAL("triggered()"), self.donearestNeigh) QObject.connect(self.meanCoords, SIGNAL("triggered()"), self.domeanCoords) QObject.connect(self.intLines, SIGNAL("triggered()"), self.dointLines) QObject.connect(self.randSel, SIGNAL("triggered()"), self.dorandSel) QObject.connect(self.randSub, SIGNAL("triggered()"), self.dorandSub) QObject.connect(self.randPoints, SIGNAL("triggered()"), self.dorandPoints) QObject.connect(self.regPoints, SIGNAL("triggered()"), self.doregPoints) QObject.connect(self.vectGrid, SIGNAL("triggered()"), self.dovectGrid) QObject.connect(self.selectLocation, SIGNAL("triggered()"), self.doselectLocation) QObject.connect(self.layerExtent, SIGNAL("triggered()"), self.doextent) QObject.connect(self.minConvex, SIGNAL("triggered()"), self.dominConvex) QObject.connect(self.intersect, SIGNAL("triggered()"), self.dointersect) QObject.connect(self.dissolve, SIGNAL("triggered()"), self.dodissolve) QObject.connect(self.symDifference, SIGNAL("triggered()"), self.dosymdifference) QObject.connect(self.erase, SIGNAL("triggered()"), self.doerase) QObject.connect(self.union, SIGNAL("triggered()"), self.dounion) QObject.connect(self.clip, SIGNAL("triggered()"), self.doclip) QObject.connect(self.dynaBuffer, SIGNAL("triggered()"), self.dodynaBuffer) QObject.connect(self.eliminate, SIGNAL("triggered()"), self.doEliminate) QObject.connect(self.multiToSingle, SIGNAL("triggered()"), self.domultiToSingle) QObject.connect(self.singleToMulti, SIGNAL("triggered()"), self.dosingleToMulti) QObject.connect(self.checkGeom, SIGNAL("triggered()"), self.docheckGeom) QObject.connect(self.simplify, SIGNAL("triggered()"), self.doSimplify) QObject.connect(self.densify, SIGNAL("triggered()"), self.doDensify) QObject.connect(self.centroids, SIGNAL("triggered()"), self.docentroids) QObject.connect(self.delaunay, SIGNAL("triggered()"), self.dodelaunay) QObject.connect(self.voronoi, SIGNAL("triggered()"), self.dovoronoi) QObject.connect(self.polysToLines, SIGNAL("triggered()"), self.dopolysToLines) QObject.connect(self.linesToPolys, SIGNAL("triggered()"), self.dolinesToPolys) QObject.connect(self.compGeo, SIGNAL("triggered()"), self.docompGeo) QObject.connect(self.extNodes, SIGNAL("triggered()"), self.doextNodes) QObject.connect(self.define, SIGNAL("triggered()"), self.dodefine) QObject.connect(self.spatJoin, SIGNAL("triggered()"), self.dospatJoin) QObject.connect(self.splitVect, SIGNAL("triggered()"), self.dosplitVect) QObject.connect(self.mergeShapes, SIGNAL("triggered()"), self.doMergeShapes) QObject.connect(self.spatialIndex, SIGNAL("triggered()"), self.doSpatIndex)
def __getMnt(self, settings): """ To get the MN data for the profile :param settings: settings containing MN url """ if settings is None or settings.mntUrl is None or settings.mntUrl == "None": url = 'http://map.lausanne.ch/main/wsgi/profile.json' elif settings.mntUrl == "": return else: url = settings.mntUrl names = ['mnt', 'mns', 'toit_rocher'] url += '?layers=' pos = 0 for name in names: if pos > 0: url += ',' pos += 1 url += name url += '&geom={"type":"LineString","coordinates":[' pos = 0 for i in range(len(self.__profiles)): if pos > 0: url += ',' pos += 1 url += '[' + str(self.__profiles[i]['x']) + ',' + str( self.__profiles[i]['y']) + ']' url = url + ']}&nbPoints=' + str( int(self.__profiles[len(self.__profiles) - 1]['l'])) try: response = urlopen(url) j = response.read() j_obj = json.loads(j) profile = j_obj['profile'] self.__mntPoints = [] self.__mntPoints.append(names) mnt_l = [] mnt_z = [] for p in range(len(names)): z = [] mnt_z.append(z) for pt in profile: mnt_l.append(float(pt['dist'])) values = pt['values'] for p in range(len(names)): if names[p] in values: mnt_z[p].append(float(values[names[p]])) else: mnt_z[p].append(None) self.__mntPoints.append(mnt_l) self.__mntPoints.append(mnt_z) except HTTPError as e: self.__iface.messageBar().pushMessage( QCoreApplication.translate("VDLTools", "HTTP Error"), QCoreApplication.translate( "VDLTools", "status error [" + str(e.code) + "] : " + e.reason), level=QgsMessageBar.CRITICAL, duration=0) except URLError as e: self.__iface.messageBar().pushMessage(QCoreApplication.translate( "VDLTools", "URL Error"), e.reason, level=QgsMessageBar.CRITICAL, duration=0)
def tr(self, message): return QCoreApplication.translate('SchoolScout', message)
class QtReactor(posixbase.PosixReactorBase): implements(IReactorFDSet) def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp = QCoreApplication([]) self._ownApp = True else: self.qApp = QCoreApplication.instance() self._ownApp = False self._blockApp = None posixbase.PosixReactorBase.__init__(self) def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type) def addReader(self, reader): """ Add a FileDescriptor for notification of data available to read. """ self._add(reader, self._reads, QSocketNotifier.Read) def addWriter(self, writer): """ Add a FileDescriptor for notification of data available to write. """ self._add(writer, self._writes, QSocketNotifier.Write) def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown() def removeReader(self, reader): """ Remove a Selectable for notification of data available to read. """ self._remove(reader, self._reads) def removeWriter(self, writer): """ Remove a Selectable for notification of data available to write. """ self._remove(writer, self._writes) def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv def getReaders(self): return self._reads.keys() def getWriters(self): return self._writes.keys() def callLater(self, howlong, *args, **kargs): rval = super(QtReactor, self).callLater(howlong, *args, **kargs) self.reactorInvocation() return rval def reactorInvocation(self): self._timer.stop() self._timer.setInterval(0) self._timer.start() def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay, fromqt) iterate = _iterate def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000) if self.timeout() is None: timeout = 0.1 elif self.timeout() == 0: timeout = 0 else: timeout = self.timeout() self._timer.setInterval(timeout * 1000) self._timer.start() def runReturn(self, installSignalHandlers=True): self.startRunning(installSignalHandlers=installSignalHandlers) self.reactorInvocation() def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_()
def __init__(self, iface): """ Constructor :param iface: interface """ QDockWidget.__init__(self) self.setWindowTitle( QCoreApplication.translate("VDLTools", "Profile Tool")) self.resize(1024, 400) self.__iface = iface self.__canvas = self.__iface.mapCanvas() self.__types = ['PDF', 'PNG'] # ], 'SVG', 'PS'] self.__libs = [] if Qwt5_loaded: self.__lib = 'Qwt5' self.__libs.append('Qwt5') if matplotlib_loaded: self.__libs.append('Matplotlib') elif matplotlib_loaded: self.__lib = 'Matplotlib' self.__libs.append('Matplotlib') else: self.__lib = None self.__iface.messageBar().pushMessage(QCoreApplication.translate( "VDLTools", "No graph lib available (qwt5 or matplotlib)"), level=QgsMessageBar.CRITICAL, duration=0) self.__doTracking = False self.__vline = None self.__profiles = None self.__numLines = None self.__mntPoints = None self.__marker = None self.__tabmouseevent = None self.__contentWidget = QWidget() self.setWidget(self.__contentWidget) self.__boxLayout = QHBoxLayout() self.__contentWidget.setLayout(self.__boxLayout) self.__plotFrame = QFrame() self.__frameLayout = QHBoxLayout() self.__plotFrame.setLayout(self.__frameLayout) self.__printLayout = QHBoxLayout() self.__printLayout.addWidget(self.__plotFrame) self.__legendLayout = QVBoxLayout() self.__printLayout.addLayout(self.__legendLayout) self.__printWdg = QWidget() self.__printWdg.setLayout(self.__printLayout) self.__plotWdg = None self.__changePlotWidget() size = QSize(150, 20) self.__boxLayout.addWidget(self.__printWdg) self.__vertLayout = QVBoxLayout() self.__libCombo = QComboBox() self.__libCombo.setFixedSize(size) self.__libCombo.addItems(self.__libs) self.__vertLayout.addWidget(self.__libCombo) self.__libCombo.currentIndexChanged.connect(self.__setLib) self.__maxLabel = QLabel("y max") self.__maxLabel.setFixedSize(size) self.__vertLayout.addWidget(self.__maxLabel) self.__maxSpin = QSpinBox() self.__maxSpin.setFixedSize(size) self.__maxSpin.setRange(-10000, 10000) self.__maxSpin.valueChanged.connect(self.__reScalePlot) self.__vertLayout.addWidget(self.__maxSpin) self.__vertLayout.insertSpacing(10, 20) self.__minLabel = QLabel("y min") self.__minLabel.setFixedSize(size) self.__vertLayout.addWidget(self.__minLabel) self.__minSpin = QSpinBox() self.__minSpin.setFixedSize(size) self.__minSpin.setRange(-10000, 10000) self.__minSpin.valueChanged.connect(self.__reScalePlot) self.__vertLayout.addWidget(self.__minSpin) self.__vertLayout.insertSpacing(10, 40) self.__typeCombo = QComboBox() self.__typeCombo.setFixedSize(size) self.__typeCombo.addItems(self.__types) self.__vertLayout.addWidget(self.__typeCombo) self.__saveButton = QPushButton( QCoreApplication.translate("VDLTools", "Save")) self.__saveButton.setFixedSize(size) self.__saveButton.clicked.connect(self.__save) self.__vertLayout.addWidget(self.__saveButton) self.__boxLayout.addLayout(self.__vertLayout) self.__maxSpin.setEnabled(False) self.__minSpin.setEnabled(False) self.__colors = [] for cn in QColor.colorNames(): qc = QColor(cn) val = qc.red() + qc.green() + qc.blue() if 0 < val < 450: self.__colors.append(cn)
# Qt4 plugins are bundled as data files (see hooks/hook-PyQt4*), # within a "qt4_plugins" directory. # We add a runtime hook to tell Qt4 where to find them. import os import sys d = "qt4_plugins" d = os.path.join(sys._MEIPASS, d) # We remove QT_PLUGIN_PATH variable, beasuse we want Qt4 to load # plugins only from one path. if 'QT_PLUGIN_PATH' in os.environ: del os.environ['QT_PLUGIN_PATH'] # We cannot use QT_PLUGIN_PATH here, because it would not work when # PyQt4 is compiled with a different CRT from Python (eg: it happens # with Riverbank's GPL package). from PyQt4.QtCore import QCoreApplication # We set "qt4_plugins" as only one path for Qt4 plugins QCoreApplication.setLibraryPaths([os.path.abspath(d)])
def __changePlotWidget(self): """ When plot widget is change (qwt <-> matplotlib) """ self.__activateMouseTracking(False) while self.__frameLayout.count(): child = self.__frameLayout.takeAt(0) child.widget().deleteLater() self.__plotWdg = None if self.__lib == 'Qwt5': self.__plotWdg = QwtPlot(self.__plotFrame) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(10) sizePolicy.setVerticalStretch(0) self.__plotWdg.setSizePolicy(sizePolicy) self.__plotWdg.setAutoFillBackground(False) # Decoration self.__plotWdg.setCanvasBackground(Qt.white) self.__plotWdg.plotLayout().setAlignCanvasToScales(False) self.__plotWdg.plotLayout().setSpacing(100) self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.xBottom) self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.yLeft) title = QwtText( QCoreApplication.translate("VDLTools", "Distance [m]")) title.setFont(QFont("Helvetica", 10)) self.__plotWdg.setAxisTitle(QwtPlot.xBottom, title) title.setText( QCoreApplication.translate("VDLTools", "Elevation [m]")) title.setFont(QFont("Helvetica", 10)) self.__plotWdg.setAxisTitle(QwtPlot.yLeft, title) self.__zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft, QwtPicker.DragSelection, QwtPicker.AlwaysOff, self.__plotWdg.canvas()) self.__zoomer.setRubberBandPen(QPen(Qt.blue)) grid = QwtPlotGrid() grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine)) grid.attach(self.__plotWdg) self.__frameLayout.addWidget(self.__plotWdg) elif self.__lib == 'Matplotlib': fig = Figure((1.0, 1.0), linewidth=0.0, subplotpars=SubplotParams(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)) font = {'family': 'arial', 'weight': 'normal', 'size': 12} rc('font', **font) rect = fig.patch rect.set_facecolor((0.9, 0.9, 0.9)) self.__axes = fig.add_axes((0.07, 0.16, 0.92, 0.82)) self.__axes.set_xbound(0, 1000) self.__axes.set_ybound(0, 1000) self.__manageMatplotlibAxe(self.__axes) self.__plotWdg = FigureCanvasQTAgg(fig) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) self.__plotWdg.setSizePolicy(sizePolicy) self.__frameLayout.addWidget(self.__plotWdg)
def delay_method_call(self, *args, **kwargs): event = QueuedCallEvent(method, (self,) + args, kwargs) QCoreApplication.postEvent(self, event) QCoreApplication.sendPostedEvents() return event.result()
def _tr(s): return QCoreApplication.translate('ModelerAlgorithm', s)
def attachCurves(self, names, settings, usedMnts): """ To attach the curves for the layers to the profile :param names: layers names """ if (self.__profiles is None) or (self.__profiles == 0): return self.__getLinearPoints() if usedMnts is not None and (usedMnts[0] or usedMnts[1] or usedMnts[2]): self.__getMnt(settings) c = 0 if self.__mntPoints is not None: for p in range(len(self.__mntPoints[0])): if usedMnts[p]: legend = QLabel("<font color='" + self.__colors[c] + "'>" + self.__mntPoints[0][p] + "</font>") self.__legendLayout.addWidget(legend) if self.__lib == 'Qwt5': xx = [list(g) for k, g in itertools.groupby(self.__mntPoints[1], lambda x: x is None) if not k] yy = [list(g) for k, g in itertools.groupby(self.__mntPoints[2][p], lambda x: x is None) if not k] for j in range(len(xx)): curve = QwtPlotCurve(self.__mntPoints[0][p]) curve.setData(xx[j], yy[j]) curve.setPen(QPen(QColor(self.__colors[c]), 3)) curve.attach(self.__plotWdg) elif self.__lib == 'Matplotlib': qcol = QColor(self.__colors[c]) self.__plotWdg.figure.get_axes()[0].plot(self.__mntPoints[1], self.__mntPoints[2][p], gid=self.__mntPoints[0][p], linewidth=3) tmp = self.__plotWdg.figure.get_axes()[0].get_lines() for t in range(len(tmp)): if self.__mntPoints[0][p] == tmp[t].get_gid(): tmp[c].set_color((old_div(qcol.red(), 255.0), old_div(qcol.green(), 255.0), old_div(qcol.blue(), 255.0), old_div(qcol.alpha(), 255.0))) self.__plotWdg.draw() break c += 1 if 'z' in self.__profiles[0]: for i in range(len(self.__profiles[0]['z'])): if i < self.__numLines: v = 0 else: v = i - self.__numLines + 1 name = names[v] xx = [] yy = [] for prof in self.__profiles: xx.append(prof['l']) yy.append(prof['z'][i]) for j in range(len(yy)): if yy[j] is None: xx[j] = None if i == 0 or i > (self.__numLines-1): legend = QLabel("<font color='" + self.__colors[c] + "'>" + name + "</font>") self.__legendLayout.addWidget(legend) if self.__lib == 'Qwt5': # Split xx and yy into single lines at None values xx = [list(g) for k, g in itertools.groupby(xx, lambda x: x is None) if not k] yy = [list(g) for k, g in itertools.groupby(yy, lambda x: x is None) if not k] # Create & attach one QwtPlotCurve per one single line for j in range(len(xx)): curve = QwtPlotCurve(name) curve.setData(xx[j], yy[j]) curve.setPen(QPen(QColor(self.__colors[c]), 3)) if i > (self.__numLines-1): curve.setStyle(QwtPlotCurve.Dots) pen = QPen(QColor(self.__colors[c]), 8) pen.setCapStyle(Qt.RoundCap) curve.setPen(pen) curve.attach(self.__plotWdg) elif self.__lib == 'Matplotlib': qcol = QColor(self.__colors[c]) if i < self.__numLines: self.__plotWdg.figure.get_axes()[0].plot(xx, yy, gid=name, linewidth=3) else: self.__plotWdg.figure.get_axes()[0].plot(xx, yy, gid=name, linewidth=5, marker='o', linestyle='None') tmp = self.__plotWdg.figure.get_axes()[0].get_lines() for t in range(len(tmp)): if name == tmp[t].get_gid(): tmp[c].set_color((old_div(qcol.red(), 255.0), old_div(qcol.green(), 255.0), old_div(qcol.blue(), 255.0), old_div(qcol.alpha(), 255.0))) self.__plotWdg.draw() break c += 1 # scaling this try: self.__reScalePlot(None, True) except: self.__iface.messageBar().pushMessage( QCoreApplication.translate("VDLTools", "Rescale problem... (trace printed)"), level=QgsMessageBar.CRITICAL, duration=0) print( QCoreApplication.translate("VDLTools", "rescale problem : "), sys.exc_info()[0], traceback.format_exc()) if self.__lib == 'Qwt5': self.__plotWdg.replot() elif self.__lib == 'Matplotlib': self.__plotWdg.figure.get_axes()[0].redraw_in_frame() self.__plotWdg.draw() self.__activateMouseTracking(True) self.__marker.show()
def write_strat_data(self, strat_data, _strat_columns, table_header, strat_sql_columns_list, decimal_separator): if table_header: rpt = ur"""<P><U><B><font size=3>%s</font></B></U></P>""" % table_header else: rpt = ur'' strat_columns = [x.split(u';')[0] for x in _strat_columns] col_widths = [ x.split(u';')[1] if len(x.split(u';')) == 2 else u'1*' for x in _strat_columns ] rpt += ur"""<TABLE style="font-family:'Ubuntu'; font-size:8pt; font-weight:400; font-style:normal;" WIDTH=100% BORDER=0 CELLPADDING=0 class="no-spacing" CELLSPACING=0>""" for col_width in col_widths: rpt += ur"""<COL WIDTH={}>""".format(col_width) rpt += ur"""<p style="font-family:'Ubuntu'; font-size:8pt; font-weight:400; font-style:normal;">""" headers_txt = OrderedDict([ (u'stratid', ru( QCoreApplication.translate(u'Drillreport2_strat', u'Layer number'))), (u'depth', ru( QCoreApplication.translate(u'Drillreport2_strat', u'level (m b gs)'))), (u'depthtop', ru( QCoreApplication.translate(u'Drillreport2_strat', u'top of layer (m b gs)'))), (u'depthbot', ru( QCoreApplication.translate(u'Drillreport2_strat', u'bottom of layer (m b gs)'))), (u'geology', ru( QCoreApplication.translate(u'Drillreport2_strat', u'geology, full text'))), (u'geoshort', ru( QCoreApplication.translate(u'Drillreport2_strat', u'geology, short'))), (u'capacity', ru(QCoreApplication.translate(u'Drillreport2_strat', u'capacity'))), (u'development', ru( QCoreApplication.translate(u'Drillreport2_strat', u'development'))), (u'comment', ru(QCoreApplication.translate(u'Drillreport2_strat', u'comment'))) ]) if len(strat_data) > 0: rpt += ur"""<TR VALIGN=TOP>""" for header in strat_columns: rpt += ur"""<TD><P><font size=2><u>{}</font></P></u></TD>""".format( headers_txt[header]) rpt += ur"""</TR>""" for rownr, row in enumerate(strat_data): rpt += ur"""<TR VALIGN=TOP>""" for col in strat_columns: if col == u'depth': try: depthtop_idx = strat_sql_columns_list.index( u'depthtop') depthbot_idx = strat_sql_columns_list.index( u'depthbot') except ValueError: utils.MessagebarAndLog.critical(bar_msg=ru( QCoreApplication.translate( u'Drillreport2', u'Programming error, depthtop and depthbot columns was supposed to exist' ))) rpt += ur"""<TD><P><font size=1> </font></P></TD>""".format( value) else: depthtop = u'' if row[ depthtop_idx] == 'NULL' else row[ depthtop_idx].replace( u'.', decimal_separator) depthbot = u'' if row[ depthbot_idx] == 'NULL' else row[ depthbot_idx].replace( u'.', decimal_separator) rpt += ur"""<TD><P><font size=1>{}</font></P></TD>""".format( u' - '.join([depthtop, depthbot])) else: value_idx = strat_sql_columns_list.index(col) value = u'' if row[value_idx] == 'NULL' else row[ value_idx] if col in (u'depthtop', u'depthbot') and decimal_separator != u'.': value = value.replace(u'.', decimal_separator) rpt += ur"""<TD><P><font size=1>{}</font></P></TD>""".format( value) rpt += ur"""</TR>""" rpt += ur"""</p>""" rpt += ur"""</TABLE>""" return rpt