Esempio n. 1
0
 def __layerChanged(self):
     if type(self.layer) == QgsVectorLayer:
         QObject.disconnect(self.layer, SIGNAL("attributeAdded(int)"),   self.__layerChanged)
         QObject.disconnect(self.layer, SIGNAL("attributeDeleted(int)"), self.__layerChanged)
     if hasattr(self.initField, '__call__'):
         initField = self.initField()
     else:
         initField = self.initField
     self.widget.clear()
     self.widget.addItem("")
     self.layer = self.layerCombo.getLayer()
     if self.layer is None:
         return
     QObject.connect(self.layer, SIGNAL("attributeAdded(int)"),   self.__layerChanged)
     QObject.connect(self.layer, SIGNAL("attributeDeleted(int)"), self.__layerChanged)
     i = 0
     for idx, field in enumerate(self.layer.pendingFields()):
         i += 1
         fieldAlias = self.layer.attributeDisplayName(idx)
         fieldName = field.name()
         self.widget.addItem(fieldAlias, fieldName)
         if not self.__isFieldValid(idx):
             j = self.widget.model().index(i, 0)
             self.widget.model().setData(j, 0, Qt.UserRole-1)
             continue
         if fieldName == initField:
             self.widget.setCurrentIndex(i)
Esempio n. 2
0
    def runFinishedFromThread(self, output):
        self.testThread.stop()
        QApplication.restoreOverrideCursor()
        self.buttonOk.setEnabled(True)
        result = output[0]
        numRows = len(result)
        self.tblUnique.setRowCount(numRows)
        if self.myFunction in (1, 2):
            self.tblUnique.setColumnCount(1)
            for rec in range(numRows):
                item = QTableWidgetItem(result[rec])
                self.tblUnique.setItem(rec, 0, item)
        else:
            self.tblUnique.setColumnCount(2)
            for rec in range(numRows):
                if ":" not in result[rec]:
                	tmp = result[rec].split(u"\uff1a")
                else:
                	tmp = result[rec].split(":")
                item = QTableWidgetItem(tmp[0])
                self.tblUnique.setItem(rec, 0, item)
                item = QTableWidgetItem(tmp[1])
                self.tblUnique.setItem(rec, 1, item)
            self.tblUnique.setHorizontalHeaderLabels([self.tr("Parameter"), self.tr("Value")])
            self.tblUnique.horizontalHeader().setResizeMode(1, QHeaderView.ResizeToContents)
            self.tblUnique.horizontalHeader().show()
        self.tblUnique.horizontalHeader().setResizeMode(0, QHeaderView.Stretch)
        self.tblUnique.resizeRowsToContents()

        self.lstCount.insert(unicode(output[1]))
        self.cancel_close.setText("Close")
        QObject.disconnect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread)
        return True
Esempio n. 3
0
    def accept(self):
        inShape = self.inShape.currentText()
        outDir = self.outShape.text()
        if inShape == "":
            QMessageBox.information(self, self.tr("Vector Split"),
                                    self.tr("No input shapefile specified"))
            return
        elif outDir == "":
            QMessageBox.information(self, self.tr("Vector Split"),
                                    self.tr("Please specify output shapefile"))
            return

        self.btnOk.setEnabled( False )

        vLayer = ftools_utils.getVectorLayerByName(unicode(self.inShape.currentText()))
        self.workThread = SplitThread(vLayer, self.inField.currentText(), self.encoding, outDir)

        QObject.connect(self.workThread, SIGNAL("rangeCalculated(PyQt_PyObject)"), self.setProgressRange)
        QObject.connect(self.workThread, SIGNAL("valueProcessed()"), self.valueProcessed)
        QObject.connect(self.workThread, SIGNAL("processFinished(PyQt_PyObject)"), self.processFinished)
        QObject.connect(self.workThread, SIGNAL("processInterrupted()"), self.processInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox_2, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.workThread.start()
Esempio n. 4
0
 def _slot_clicked ( self, handler, connect ):
     from facets.extra.helper.debug import log_if
     log_if( 2, 'clicked!' )
     if connect:
         QObject.connect( self.control, SIGNAL( 'clicked()' ), handler )
     else:
         QObject.disconnect( self.control, SIGNAL( 'clicked()' ), handler )
Esempio n. 5
0
    def accept(self):
        self.inFiles = None
        if self.batchCheck.isChecked():
            self.inFiles = Utils.getRasterFiles(self.inSelector.filename(),
                                                self.recurseCheck.isChecked())
        else:
            self.inFiles = [self.inSelector.filename()]

        self.progressBar.setRange(0, len(self.inFiles))

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.okButton.setEnabled(False)

        self.extractor = ExtractThread(self.inFiles, self.prjCheck.isChecked())
        QObject.connect(self.extractor, SIGNAL("fileProcessed()"),
                        self.updateProgress)
        QObject.connect(self.extractor, SIGNAL("processFinished()"),
                        self.processingFinished)
        QObject.connect(self.extractor, SIGNAL("processInterrupted()"),
                        self.processingInterrupted)

        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.buttonBox, SIGNAL("rejected()"),
                        self.stopProcessing)

        self.extractor.start()
Esempio n. 6
0
    def accept(self):
        if self.inputFiles is None:
            workDir = QDir(self.leInputDir.text())
            workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot)
            nameFilter = ["*.shp", "*.SHP"]
            workDir.setNameFilters(nameFilter)
            self.inputFiles = workDir.entryList()
            if len(self.inputFiles) == 0:
                QMessageBox.warning(
                    self, self.tr("No shapefiles found"),
                    self.tr("There are no shapefiles in this directory. Please select another one."))
                self.inputFiles = None
                return

        if self.outFileName is None:
            QMessageBox.warning(
                self, self.tr("No output file"),
                self.tr("Please specify output file."))
            return

        if self.chkListMode.isChecked():
            files = self.leInputDir.text().split(";")
            baseDir = QFileInfo(files[0]).absolutePath()
        else:
            baseDir = self.leInputDir.text()
            # look for shapes with specified geometry type
            self.inputFiles = ftools_utils.getShapesByGeometryType(baseDir, self.inputFiles, self.cmbGeometry.currentIndex())
            if self.inputFiles is None:
                QMessageBox.warning(
                    self, self.tr("No shapefiles found"),
                    self.tr("There are no shapefiles with the given geometry type. Please select an available geometry type."))
                return
            self.progressFiles.setRange(0, len(self.inputFiles))

        outFile = QFile(self.outFileName)
        if outFile.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.outFileName):
                QMessageBox.warning(self, self.tr("Delete error"), self.tr("Can't delete file %s") % (self.outFileName))
                return

        if self.inEncoding is None:
            self.inEncoding = "System"

        self.btnOk.setEnabled(False)

        self.mergeThread = ShapeMergeThread(baseDir, self.inputFiles, self.inEncoding, self.outFileName, self.encoding)
        QObject.connect(self.mergeThread, SIGNAL("rangeChanged( PyQt_PyObject )"), self.setFeatureProgressRange)
        QObject.connect(self.mergeThread, SIGNAL("checkStarted()"), self.setFeatureProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("checkFinished()"), self.resetFeatureProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("fileNameChanged( PyQt_PyObject )"), self.setShapeProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("featureProcessed()"), self.featureProcessed)
        QObject.connect(self.mergeThread, SIGNAL("shapeProcessed()"), self.shapeProcessed)
        QObject.connect(self.mergeThread, SIGNAL("processingFinished()"), self.processingFinished)
        QObject.connect(self.mergeThread, SIGNAL("processingInterrupted()"), self.processingInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.mergeThread.start()
Esempio n. 7
0
    def unload(self):
        """Gui breakdown procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(self.tr("InaSAFE"), self.actionDock)
        self.iface.removeToolBarIcon(self.actionDock)
        self.iface.removePluginMenu(self.tr("InaSAFE"), self.actionKeywordsDialog)
        self.iface.removeToolBarIcon(self.actionKeywordsDialog)
        self.iface.removePluginMenu(self.tr("InaSAFE"), self.actionResetDock)
        self.iface.removeToolBarIcon(self.actionResetDock)
        self.iface.removePluginMenu(self.tr("InaSAFE"), self.actionOptions)
        self.iface.removeToolBarIcon(self.actionOptions)
        self.iface.removePluginMenu(self.tr("InaSAFE"), self.actionImpactFunctionsDoc)
        self.iface.removeToolBarIcon(self.actionImpactFunctionsDoc)
        self.iface.mainWindow().removeDockWidget(self.dockWidget)
        self.dockWidget.setVisible(False)
        self.dockWidget.destroy()
        QObject.disconnect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.layerChanged)
Esempio n. 8
0
    def unload(self):
        """Gui breakdown procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionDock)
        self.iface.removeToolBarIcon(self.actionDock)
        self.iface.removePluginMenu(self.tr('InaSAFE'),
                                    self.actionKeywordsDialog)
        self.iface.removeToolBarIcon(self.actionKeywordsDialog)
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionResetDock)
        self.iface.removeToolBarIcon(self.actionResetDock)
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionOptions)
        self.iface.removeToolBarIcon(self.actionOptions)
        self.iface.mainWindow().removeDockWidget(self.dockWidget)
        self.dockWidget.setVisible(False)
        self.dockWidget.destroy()
        QObject.disconnect(self.iface,
                           SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                           self.layerChanged)
Esempio n. 9
0
    def unload(self):
        """Gui breakdown procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Remove the plugin menu item and icon
        for myAction in self.actions:
            self.iface.removePluginMenu(self.tr('InaSAFE'), myAction)
            self.iface.removeToolBarIcon(myAction)
        self.iface.mainWindow().removeDockWidget(self.dockWidget)
        self.iface.mainWindow().removeToolBar(self.toolbar)
        self.dockWidget.setVisible(False)
        self.dockWidget.destroy()
        QObject.disconnect(
            self.iface,
            SIGNAL("currentLayerChanged(QgsMapLayer*)"),
            self.layerChanged)

        self.clearModules()
Esempio n. 10
0
  def threadFinished(self):
    '''
    run when calculation ends
    ask to load created shapefile
    '''
    self.t2 = time()

    if self.ui.cbOutput.isChecked():
      msg = QMessageBox.question(self, 'Polygonizer', 'Polygonization finished in %03.2f seconds. \n %d polygons were crested. \n Load created layer?' % ((self.t2 - self.t1), polyCount), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
      if msg == QMessageBox.Yes:
        new_path = self.ui.eOutput.text()
        if new_path.contains("\\"):
          out_name = new_path.right((new_path.length() - new_path.lastIndexOf("\\")) - 1)
        else:
          out_name = new_path.right((new_path.length() - new_path.lastIndexOf("/")) - 1)
        if out_name.endsWith(".shp"):
          out_name = out_name.left(out_name.length() - 4)

        self.iface.addVectorLayer(self.ui.eOutput.text(), out_name, "ogr")
    else:
      QgsMapLayerRegistry().instance().addMapLayer(self.mLayer)
      QMessageBox.information(self, 'Polygonizer', 'Polygonization finished in %03.2f seconds. \n %d polygons were crested.' % ((self.t2 - self.t1), polyCount))

    QObject.disconnect(self.layer,SIGNAL("editingStarted()"), self.startEditing)
    QObject.disconnect(self.polygonizeThread, SIGNAL("progress"), self.setProgress)
    self.close()
Esempio n. 11
0
 def __layerChanged(self):
     if type(self.layer) == QgsVectorLayer:
         QObject.disconnect(self.layer, SIGNAL("attributeAdded(int)"),
                            self.__layerChanged)
         QObject.disconnect(self.layer, SIGNAL("attributeDeleted(int)"),
                            self.__layerChanged)
     if hasattr(self.initField, '__call__'):
         initField = self.initField()
     else:
         initField = self.initField
     self.widget.clear()
     self.widget.addItem("")
     self.layer = self.layerCombo.getLayer()
     if self.layer is None:
         return
     QObject.connect(self.layer, SIGNAL("attributeAdded(int)"),
                     self.__layerChanged)
     QObject.connect(self.layer, SIGNAL("attributeDeleted(int)"),
                     self.__layerChanged)
     i = 0
     for idx, field in enumerate(self.layer.pendingFields()):
         i += 1
         fieldAlias = self.layer.attributeDisplayName(idx)
         fieldName = field.name()
         self.widget.addItem(fieldAlias, fieldName)
         if not self.__isFieldValid(idx):
             j = self.widget.model().index(i, 0)
             self.widget.model().setData(j, 0, Qt.UserRole - 1)
             continue
         if fieldName == initField:
             self.widget.setCurrentIndex(i)
Esempio n. 12
0
    def accept(self):
        if not self.cmbInputLayer.currentText():
            QMessageBox.warning(self, self.tr("Warning"),
                                self.tr("Please specify an input layer"))
            return
        vLayer = ftools_utils.getVectorLayerByName(
            self.cmbInputLayer.currentText())

        self.btnOk.setEnabled(False)

        if self.chkWriteShapefile.isChecked():
            outFileName = self.edOutputFile.text()
            outFile = QFile(outFileName)
            if outFile.exists():
                if not QgsVectorFileWriter.deleteShapeFile(outFileName):
                    QMessageBox.warning(
                        self, self.tr("Delete error"),
                        self.tr("Can't delete file %s") % (outFileName))
                    self.btnOk.setEnabled(False)
                    return

            self.workThread = GeomThread(self.myFunction, vLayer,
                                         self.chkUseSelection.isChecked(),
                                         self.spnTolerance.value(), True,
                                         outFileName, self.encoding)
        else:
            res = QMessageBox.warning(
                self, self.tr("Warning"),
                self.
                tr("Currently QGIS doesn't allow simultaneous access from "
                   "different threads to the same datasource. Make sure your layer's "
                   "attribute tables are closed. Continue?"),
                QMessageBox.Yes | QMessageBox.No)
            if res == QMessageBox.No:
                self.btnOk.setEnabled(False)
                return

            self.workThread = GeomThread(self.myFunction, vLayer,
                                         self.chkUseSelection.isChecked(),
                                         self.spnTolerance.value(), False,
                                         None, None)

        QObject.connect(self.workThread,
                        SIGNAL("rangeCalculated( PyQt_PyObject )"),
                        self.setProgressRange)
        QObject.connect(self.workThread, SIGNAL("featureProcessed()"),
                        self.featureProcessed)
        QObject.connect(self.workThread,
                        SIGNAL("processingFinished( PyQt_PyObject )"),
                        self.processFinished)
        QObject.connect(self.workThread, SIGNAL("processingInterrupted()"),
                        self.processInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"),
                        self.stopProcessing)

        self.workThread.start()
 def unload(self):
     # Remove the plugin menu item and icon
     self.iface.removePluginMenu(self.tr('&FieldPyculator'), self.action)
     self.iface.removeToolBarIcon(self.action)
     # Remove layer changing tracking
     QObject.disconnect(self.iface,
                        SIGNAL('currentLayerChanged( QgsMapLayer* )'),
                        self.layer_changed)
Esempio n. 14
0
 def stop(self):
     print('Thread::[{}] successfully stopped.'.format(self.objectName()))
     if hasattr(self,'procHostapd'):
         QObject.disconnect(self.procHostapd,
         SIGNAL('readyReadStandardOutput()'), self, SLOT('read_OutputCommand()'))
         self.procHostapd.terminate()
         self.procHostapd.waitForFinished()
         self.procHostapd.kill()
Esempio n. 15
0
    def _disconnectsim(self, sim):
        #ui signals -> logs
        QObject.disconnect(sim, _LOOPMSGSIGNAL, self.simlog)

        #signals to set box values
        for index in xrange(api.ARDUINO_DIGITAL_PIN_NB):
            box = self.getboxbynum(index)
            QObject.disconnect(sim.pins[index], _PINSIGNAL, box.setChecked)
Esempio n. 16
0
    def getSource(self, url):
        qurl = QUrl(url)
        QObject.disconnect(self.web_view, SIGNAL('loadFinished(bool)'), self._load_finished)
        QObject.connect(self.web_view, SIGNAL('loadFinished(bool)'), self._load_get_source)

        current_frame = self.web_page.currentFrame()
        current_frame.load(qurl)
        self.app_exec()
Esempio n. 17
0
    def orientation(self):

        # Disconnect previous snapping
        QObject.disconnect(
            self.emit_point,
            SIGNAL("canvasClicked(const QgsPoint &, Qt::MouseButton)"),
            self.click_button_snapping)
        self.emit_point.canvasClicked.connect(self.click_button_orientation)
Esempio n. 18
0
 def delete(self):
     if self.part:
         QObject.disconnect(self.part, SIGNAL('selected(QWidget *)'),
                            self, SIGNAL('selected(QWidget *)'))
         self.part.setParent(None)
         part = self.part
         self.part = None
         return part
Esempio n. 19
0
 def stop(self):
     print 'Thread::[{}] successfully stopped.'.format(self.objectName())
     if hasattr(self,'procHostapd'):
         QObject.disconnect(self.procHostapd,
         SIGNAL('readyReadStandardOutput()'), self, SLOT('read_OutputCommand()'))
         self.procHostapd.terminate()
         self.procHostapd.waitForFinished()
         self.procHostapd.kill()
Esempio n. 20
0
    def restoreGui(self):
        self.progressBar.setRange(0, 1)
        self.progressBar.setValue(0)
        self.outShape.clear()

        QObject.disconnect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)
        QObject.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.btnClose.setText(self.tr("Close"))
        self.btnOk.setEnabled(True)
Esempio n. 21
0
    def restoreGui(self):
        self.progressBar.setRange(0, 1)
        self.progressBar.setValue(0)
        self.outShape.clear()

        QObject.disconnect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)
        QObject.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.btnClose.setText(self.tr("Close"))
        self.btnOk.setEnabled(True)
Esempio n. 22
0
 def _slot_choose ( self, handler, connect ):
     from facets.extra.helper.debug import log_if
     log_if( 2, 'choose!' )
     if connect:
         QObject.connect( self.control, SIGNAL( 'activated(QString)' ),
                          handler )
     else:
         QObject.disconnect( self.control, SIGNAL( 'activated(QString)' ),
                             handler )
Esempio n. 23
0
 def clear_cards_tables(self):
     table = self.cards_table
     count = table.count()
     while count > 0:
         item = table.itemAt(count-1)
         wid = item.widget()
         QObject.disconnect(wid,0,0,0)
         wid.deleteLater()
         count -= 1
Esempio n. 24
0
    def accept(self):
        if self.inPolygon.currentText() == "":
            QMessageBox.information(
                self, self.tr("Count Points In Polygon"),
                self.tr("Please specify input polygon vector layer"))
        elif self.inPoint.currentText() == "":
            QMessageBox.information(
                self, self.tr("Count Points In Polygon"),
                self.tr("Please specify input point vector layer"))
        elif self.lnField.text() == "":
            QMessageBox.information(
                self, self.tr("Count Points In Polygon"),
                self.tr("Please specify output count field"))
        elif self.outShape.text() == "":
            QMessageBox.information(self, self.tr("Count Points In Polygon"),
                                    self.tr("Please specify output shapefile"))
        else:
            inPoly = ftools_utils.getVectorLayerByName(
                self.inPolygon.currentText())
            inPnts = ftools_utils.getVectorLayerByName(
                self.inPoint.currentText())

            polyProvider = inPoly.dataProvider()
            pointProvider = inPnts.dataProvider()
            if polyProvider.crs() != pointProvider.crs():
                QMessageBox.warning(
                    self, self.tr("CRS warning!"),
                    self.
                    tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results."
                       ))

            self.btnOk.setEnabled(False)

            self.workThread = PointsInPolygonThread(inPoly, inPnts,
                                                    self.lnField.text(),
                                                    self.outShape.text(),
                                                    self.encoding,
                                                    self.attributeList,
                                                    self.statisticSelector)

            QObject.connect(self.workThread, SIGNAL("rangeChanged(int)"),
                            self.setProgressRange)
            QObject.connect(self.workThread, SIGNAL("updateProgress()"),
                            self.updateProgress)
            QObject.connect(self.workThread, SIGNAL("processingFinished()"),
                            self.processFinished)
            QObject.connect(self.workThread, SIGNAL("processingInterrupted()"),
                            self.processInterrupted)

            self.btnClose.setText(self.tr("Cancel"))
            QObject.disconnect(self.buttonBox, SIGNAL("rejected()"),
                               self.reject)
            QObject.connect(self.btnClose, SIGNAL("clicked()"),
                            self.stopProcessing)

            self.workThread.start()
Esempio n. 25
0
  def restoreGui( self ):
    self.progressBar.setRange( 0, 100 )
    self.progressBar.setValue( 0 )

    QApplication.restoreOverrideCursor()

    QObject.disconnect( self.buttonBox, SIGNAL( "rejected()" ), self.stopProcessing )
    QObject.connect( self.buttonBox, SIGNAL( "rejected()" ), self.reject )

    self.okButton.setEnabled( True )
Esempio n. 26
0
    def getSource(self, url):
        qurl = QUrl(url)
        QObject.disconnect(self.web_view, SIGNAL('loadFinished(bool)'),
                           self._load_finished)
        QObject.connect(self.web_view, SIGNAL('loadFinished(bool)'),
                        self._load_get_source)

        current_frame = self.web_page.currentFrame()
        current_frame.load(qurl)
        self.app_exec()
Esempio n. 27
0
 def unload(self):
     """Removes the plugin menu item and icon from QGIS GUI."""
     for action in self.actions:
         self.iface.removePluginMenu(
             self.tr(u'&ESDM Constraint Checker'),
             action)
         self.iface.removeToolBarIcon(action)
     QObject.disconnect(self.freeHandTool, SIGNAL("geometryReady(PyQt_PyObject)"), self.receiveFeature)
     # remove the toolbar
     del self.toolbar
Esempio n. 28
0
    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',
            'TopologicGeometryEdit_{}.qm'.format(locale))

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

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


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Topologic Geometry Add')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'TopologicGeometryAdd')
        self.toolbar.setObjectName(u'TopologicGeometryAdd')
        # declare slot variables
        self.selectedLayer = None
        self.nodeLayer = None
        self.edgeLayer = None        
        
        # set db connector for topology tests
        self.topologyConnector = TopologyConnector()
                
        # set variables as typ array
        self.qgisLayerInformation = []
        self.postgresLayerInformation = []
        self.deletedQgisLayerInformation = []        
                
        currentLayer = self.iface.mapCanvas().currentLayer()
        if currentLayer:
            self.listenLayerChanged(currentLayer)                 
                
        # set signal for listenLayerChangged
        QObject.disconnect(self.iface.mapCanvas(), SIGNAL("currentLayerChanged(QgsMapLayer *)"), self.listenLayerChanged)
        QObject.connect(self.iface.mapCanvas(), SIGNAL("currentLayerChanged(QgsMapLayer *)"), self.listenLayerChanged)
Esempio n. 29
0
    def restoreGui(self):
        self.progressBar.setRange(0, 100)
        self.progressBar.setValue(0)

        QApplication.restoreOverrideCursor()

        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"),
                           self.stopProcessing)
        QObject.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)

        self.okButton.setEnabled(True)
Esempio n. 30
0
    def stop_logging (self):
        if self._logger is not None and self._log_handler is not None:
            self._logger.debug('---------------------------------------------------------')
            self._logger.removeHandler(self._log_handler)
            logging.shutdown()

            # disconnessione al segnale logged emesso ad ogni log
            QObject.disconnect(self._log_handler, SIGNAL('logged(QString)'),self.message_logged)

            self.logging_enabled = False
            self._logger = None
            self._log_handler = None
Esempio n. 31
0
    def initGuiButtons(self):
        """Init the GUI to follow export processes."""

        self.dlg.printBar.setValue(0)
        self.dlg.printBar.setMaximum(len(rowsChecked))
        self.dlg.exportButton.setEnabled(False)

        # Activate the Cancel button to stop export process, and hide the Close button
        QObject.disconnect(self.dlg.buttonBox, SIGNAL("rejected()"),
                           self.dlg.reject)
        self.dlg.btnClose.hide()
        self.dlg.btnCancel.show()
        self.dlg.buttonBox.rejected.connect(self.stopProcessing)
Esempio n. 32
0
    def snapping(self):

        # Set active layer and set signals
        self.iface.setActiveLayer(self.layer_node)
        QObject.disconnect(
            self.emit_point,
            SIGNAL("canvasClicked(const QgsPoint &, Qt::MouseButton)"),
            self.click_button_orientation)
        self.canvas.xyCoordinates.connect(self.mouse_move)
        QObject.connect(
            self.emit_point,
            SIGNAL("canvasClicked(const QgsPoint &, Qt::MouseButton)"),
            self.click_button_snapping)
Esempio n. 33
0
    def _slot_text_enter ( self, handler, connect ):
        from facets.extra.helper.debug import log_if
        log_if( 2, 'text enter!' )

        control = self.control
        if isinstance( control, QComboBox ):
            control = control.lineEdit()

        if connect:
            QObject.connect( control, SIGNAL( 'editingFinished()' ), handler )
        else:
            QObject.disconnect( control, SIGNAL( 'editingFinished()' ),
                                handler )
Esempio n. 34
0
 def changeMode(self):
     if self.chkListMode.isChecked():
         self.label.setText(self.tr("Input files"))
         QObject.disconnect(self.btnSelectDir, SIGNAL("clicked()"), self.inputDir)
         QObject.connect(self.btnSelectDir, SIGNAL("clicked()"), self.inputFile)
         self.lblGeometry.setEnabled(False)
         self.cmbGeometry.setEnabled(False)
     else:
         self.label.setText(self.tr("Input directory"))
         QObject.disconnect(self.btnSelectDir, SIGNAL("clicked()"), self.inputFile)
         QObject.connect(self.btnSelectDir, SIGNAL("clicked()"), self.inputDir)
         self.lblGeometry.setEnabled(True)
         self.cmbGeometry.setEnabled(True)
Esempio n. 35
0
    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',
            'TopologicGeometryEdit_{}.qm'.format(locale))

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

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


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Topologic Geometry Edit')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'TopologicGeometryEdit')
        self.toolbar.setObjectName(u'TopologicGeometryEdit')
        # declare slot variables
        self.selectedLayer = None
        self.selectedFeature = None
        self.insideTopoEdit = False # dynamic handling of geometry change listener
        self.rollBackStarted = False # prevent geometry change triggered by rollback action
        self.nodeLayer = None
        self.edgeLayer = None
        self.layerInfo = None # holds information of current selected layer
        
        # set db connector for topology tests
        self.topologyConnector = TopologyConnector()
        # check if already a layer is selected on Plugin Load (probably only during testing) 
        currentLayer = self.iface.mapCanvas().currentLayer()
        if currentLayer:
            self.listen_layerChanged(currentLayer)
        # connect to geometry changes (test)
        QObject.disconnect(self.iface.mapCanvas(), SIGNAL("currentLayerChanged(QgsMapLayer *)"), self.listen_layerChanged)
        QObject.connect(self.iface.mapCanvas(), SIGNAL("currentLayerChanged(QgsMapLayer *)"), self.listen_layerChanged)
Esempio n. 36
0
  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 )
Esempio n. 37
0
 def disconnect(self, obj=None, event='', callback=None):
     '''
     Disconnects all callbacks from object
     
     @param obj: Name of the object
     @param event: Name of the event
     @param callback: Function to call on event
     '''
     obj = 'self.ui.' + str(obj)
     try:
         obj = eval(obj)
         QObject.disconnect(obj, SIGNAL(str(event)), callback)
     except:
         print "ERROR: Could not disconnect signals from object " + str(obj)
Esempio n. 38
0
 def disconnect(self, obj=None, event='', callback=None):
     '''
     Disconnects all callbacks from object
     
     @param obj: Name of the object
     @param event: Name of the event
     @param callback: Function to call on event
     '''
     obj = 'self.ui.' + str(obj)
     try:
         obj = eval(obj)
         QObject.disconnect(obj, SIGNAL(str(event)), callback)
     except:
         print "ERROR: Could not disconnect signals from object " + str(obj)
Esempio n. 39
0
  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 )
Esempio n. 40
0
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     QApplication.restoreOverrideCursor()
     self.buttonOk.setEnabled(True)
     if success == "writeShape":
         extra = ""
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(
                 unicode(self.shapefileName))
             if not addCanvasCheck:
                 QMessageBox.warning(
                     self, self.tr("Geometry"),
                     self.tr("Error loading output shapefile:\n%s") %
                     (unicode(self.shapefileName)))
         else:
             QMessageBox.information(
                 self, self.tr("Geometry"),
                 self.tr("Created output shapefile:\n%s\n%s") %
                 (unicode(self.shapefileName), extra))
     else:
         self.tblUnique.setColumnCount(2)
         count = 0
         for rec in success:
             if len(rec[1]) < 1:
                 continue
             for err in rec[1]:  # for each error we find
                 self.tblUnique.insertRow(count)
                 fidItem = QTableWidgetItem(unicode(rec[0]))
                 self.tblUnique.setItem(count, 0, fidItem)
                 message = err.what()
                 errItem = QTableWidgetItem(message)
                 if err.hasWhere(
                 ):  # if there is a location associated with the error
                     errItem.setData(Qt.UserRole, err.where())
                 self.tblUnique.setItem(count, 1, errItem)
                 count += 1
         self.tblUnique.setHorizontalHeaderLabels(
             [self.tr("Feature"), self.tr("Error(s)")])
         self.tblUnique.horizontalHeader().setResizeMode(
             0, QHeaderView.ResizeToContents)
         self.tblUnique.horizontalHeader().show()
         self.tblUnique.horizontalHeader().setResizeMode(
             1, QHeaderView.Stretch)
         self.tblUnique.resizeRowsToContents()
         self.lstCount.insert(unicode(count))
     self.cancel_close.setText("Close")
     QObject.disconnect(self.cancel_close, SIGNAL("clicked()"),
                        self.cancelThread)
     return True
Esempio n. 41
0
  def union(self):
    '''new method using Union function'''
    global polyCount
    inFeat = QgsFeature()

    progress = 0.

    self.emit(SIGNAL('progress'), 0)

    self.parent.layer = getMapLayerByName(self.ui.cmbLayer.currentText())
    provider = self.parent.layer.dataProvider()
    #user can't toggle edit mode of line layer while polygonizing, plugin automatically turn it off 
    QObject.connect(self.parent.layer,SIGNAL("editingStarted()"), self.parent.startEditing)
    allAttrs = provider.attributeIndexes()
    provider.select(allAttrs)

    provider.select()

    step = 45. / self.parent.layer.featureCount()
    allLinesList = []
    allLinesListExtend = allLinesList.extend
    allLinesListAppend = allLinesList.append

    while provider.nextFeature(inFeat):
      geom = inFeat.geometry()
      if geom.isMultipart():
        allLinesListExtend(geom.asMultiPolyline() )
      else:
        allLinesListAppend(geom.asPolyline())

      progress += step
      self.emit(SIGNAL('progress'), progress)

    allLines = MultiLineString(allLinesList)
    allLines = allLines.union(Point(0,0))

    polygons = list(polygonize([allLines]))

    polyCount = len(polygons)
    #if no polygons where created then exit from thread
    if polyCount == 0:
      QObject.disconnect(self.parent.polygonizeThread,SIGNAL("finished()"), self.parent.threadFinished)
      self.emit(SIGNAL('noPolygons'))
      return
    else:
      if self.ui.cbOutput.isChecked():
        self.saveAsFile(polygons, progress)
      else:
        self.saveInMemory(polygons, progress)
Esempio n. 42
0
    def switchToolMode(self):
        self.recurseCheck.setVisible(self.inputDirCheck.isChecked())
        self.inSelector.clear()

        if self.inputDirCheck.isChecked():
            self.inFileLabel = self.label.text()
            self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory"))

            QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit)
            QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir)
        else:
            self.label.setText(self.inFileLabel)

            QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit)
            QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir)
Esempio n. 43
0
    def switchToolMode(self):
        self.recurseCheck.setVisible(self.inputDirCheck.isChecked())
        self.inSelector.clear()

        if self.inputDirCheck.isChecked():
            self.inFileLabel = self.label.text()
            self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory"))

            QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit)
            QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir)
        else:
            self.label.setText(self.inFileLabel)

            QObject.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit)
            QObject.disconnect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputDir)
Esempio n. 44
0
  def closeForm(self):
    ''' Stop polygonization process or close window '''
    if self.ui.btnCancel.text() == 'Cancel':
      msg = QMessageBox.question(self, 'Polygonizer', 'Stop process?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
      if msg == QMessageBox.No:
        return

      QObject.disconnect(self.polygonizeThread,SIGNAL("finished()"), self.threadFinished)
      QObject.disconnect(self.layer,SIGNAL("editingStarted()"), self.startEditing)

      self.polygonizeThread.terminate()
      self.SetWidgetsEnabled(True)
      self.ui.pbProgress.setValue(0)
    else:
      self.close()
Esempio n. 45
0
    def accept(self):
        self.btnOk.setEnabled(False)

        self.workThread = SpatialIdxThread(self.layers, self.chkExternalFiles.isChecked())
        self.progressBar.setRange(0, len(self.layers))

        QObject.connect(self.workThread, SIGNAL("layerProcessed()"), self.layerProcessed)
        QObject.connect(self.workThread, SIGNAL("processFinished( PyQt_PyObject )"), self.processFinished)
        QObject.connect(self.workThread, SIGNAL("processInterrupted()"), self.processInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.workThread.start()
 def deactivate(self):  #enable clean exit of the plugin
     self.cleaning()
     QObject.disconnect(self.tool, SIGNAL("moved"), self.moved)
     QObject.disconnect(self.tool, SIGNAL("leftClicked"), self.leftClicked)
     QObject.disconnect(self.tool, SIGNAL("rightClicked"),
                        self.rightClicked)
     QObject.disconnect(self.tool, SIGNAL("doubleClicked"),
                        self.doubleClicked)
Esempio n. 47
0
  def accept( self ):
    self.btnOk.setEnabled( False )

    self.workThread = SpatialIdxThread( self.layers, self.chkExternalFiles.isChecked() )
    self.progressBar.setRange( 0, len( self.layers ) )

    QObject.connect( self.workThread, SIGNAL( "layerProcessed()" ), self.layerProcessed )
    QObject.connect( self.workThread, SIGNAL( "processFinished( PyQt_PyObject )" ), self.processFinished )
    QObject.connect( self.workThread, SIGNAL( "processInterrupted()" ), self.processInterrupted )

    self.btnClose.setText( self.tr( "Cancel" ) )
    QObject.disconnect( self.buttonBox, SIGNAL( "rejected()" ), self.reject )
    QObject.connect( self.btnClose, SIGNAL( "clicked()" ), self.stopProcessing )

    self.workThread.start()
Esempio n. 48
0
    def _slot_text_change ( self, handler, connect ):
        from facets.extra.helper.debug import log_if
        log_if( 2, 'text change!' )

        control = self.control
        if isinstance( control, QComboBox ):
            control = control.lineEdit()

        signal = 'textEdited(QString)'
        if isinstance( control, QTextEdit ):
            signal = 'textChanged()'

        if connect:
            QObject.connect( control, SIGNAL( signal ), handler )
        else:
            QObject.disconnect( control, SIGNAL( signal ), handler )
 def deactivatePointMapTool(self):  #enable clean exit of the plugin
     QObject.disconnect(self.pointTool, SIGNAL("moved"), self.moved)
     QObject.disconnect(self.pointTool, SIGNAL("leftClicked"),
                        self.leftClicked)
     QObject.disconnect(self.pointTool, SIGNAL("rightClicked"),
                        self.rightClicked)
     QObject.disconnect(self.pointTool, SIGNAL("doubleClicked"),
                        self.doubleClicked)
     self.iface.mainWindow().statusBar().showMessage("")
Esempio n. 50
0
    def fetchFiles(self, urls):
        self.logT("TileLayer.fetchFiles() starts")
        # create a QEventLoop object that belongs to the current thread (if ver. > 2.1, it is render thread)
        eventLoop = QEventLoop()
        self.logT("Create event loop: " + str(eventLoop))  # DEBUG
        QObject.connect(self, SIGNAL("allRepliesFinished()"), eventLoop.quit)

        # create a timer to watch whether rendering is stopped
        watchTimer = QTimer()
        watchTimer.timeout.connect(eventLoop.quit)

        # send a fetch request to the main thread
        self.emit(SIGNAL("fetchRequest(QStringList)"), urls)

        # wait for the fetch to finish
        tick = 0
        interval = 500
        timeoutTick = self.plugin.downloadTimeout * 1000 / interval
        watchTimer.start(interval)
        while tick < timeoutTick:
            # run event loop for 0.5 seconds at maximum
            eventLoop.exec_()

            if debug_mode:
                qDebug("watchTimerTick: %d" % tick)
                qDebug("unfinished downloads: %d" %
                       self.downloader.unfinishedCount())

            if self.downloader.unfinishedCount(
            ) == 0 or self.renderContext.renderingStopped():
                break
            tick += 1
        watchTimer.stop()

        if tick == timeoutTick and self.downloader.unfinishedCount() > 0:
            self.log("fetchFiles timeout")
            # self.showBarMessage("fetchFiles timeout", duration=5)   #DEBUG
            self.downloader.abort()
            self.downloader.errorStatus = Downloader.TIMEOUT_ERROR
        files = self.downloader.fetchedFiles

        watchTimer.timeout.disconnect(eventLoop.quit)  #
        QObject.disconnect(self, SIGNAL("allRepliesFinished()"),
                           eventLoop.quit)

        self.logT("TileLayer.fetchFiles() ends")
        return files
    def dataActionMenuFunction(self,action):
        QObject.disconnect(self.menu, SIGNAL("triggered(QAction*)"),self.dataActionMenuFunction)
        if action != self.actRefresh:
            actiontext = str(action.text())
            tool_node = self.dynactions[actiontext]
            filename = self.model.fileName(self.currentIndex)
            filepath = self.model.filePath(self.currentIndex)
            parentfilepath = self.model.filePath(self.currentIndex.parent())

            params = self.getOptionalParams()
            window = ExecuteToolGui(parent_widget = self.treeview,
                                    tool_node = tool_node,
                                    tool_config = None,
                                    tool_library_node = self.tool_library_node, 
                                    params=params)
            window.show()
        return
    def dataActionMenuFunction(self, action):
        QObject.disconnect(self.menu, SIGNAL("triggered(QAction*)"),
                           self.dataActionMenuFunction)
        if action != self.actRefresh:
            actiontext = str(action.text())
            tool_node = self.dynactions[actiontext]
            filename = self.model.fileName(self.currentIndex)
            filepath = self.model.filePath(self.currentIndex)
            parentfilepath = self.model.filePath(self.currentIndex.parent())

            params = self.getOptionalParams()
            window = ExecuteToolGui(parent_widget=self.treeview,
                                    tool_node=tool_node,
                                    tool_config=None,
                                    tool_library_node=self.tool_library_node,
                                    params=params)
            window.show()
        return
Esempio n. 53
0
    def accept(self):
        if not self.cmbInputLayer.currentText():
            QMessageBox.warning(self, self.tr("Warning"), self.tr("Please specify an input layer"))
            return
        vLayer = ftools_utils.getVectorLayerByName(self.cmbInputLayer.currentText())

        self.btnOk.setEnabled(False)

        if self.chkWriteShapefile.isChecked():
            outFileName = self.edOutputFile.text()
            outFile = QFile(outFileName)
            if outFile.exists():
                if not QgsVectorFileWriter.deleteShapeFile(outFileName):
                    QMessageBox.warning(self, self.tr("Delete error"),
                                        self.tr("Can't delete file %s") % (outFileName))
                    self.btnOk.setEnabled(False)
                    return

            self.workThread = GeomThread(self.myFunction, vLayer, self.chkUseSelection.isChecked(),
                                         self.spnTolerance.value(), True, outFileName, self.encoding)
        else:
            res = QMessageBox.warning(self, self.tr("Warning"),
                                      self.tr(
                "Currently QGIS doesn't allow simultaneous access from "
                "different threads to the same datasource. Make sure your layer's "
                "attribute tables are closed. Continue?"),
                QMessageBox.Yes | QMessageBox.No)
            if res == QMessageBox.No:
                self.btnOk.setEnabled(False)
                return

            self.workThread = GeomThread(self.myFunction, vLayer, self.chkUseSelection.isChecked(),
                                         self.spnTolerance.value(), False, None, None)

        QObject.connect(self.workThread, SIGNAL("rangeCalculated( PyQt_PyObject )"), self.setProgressRange)
        QObject.connect(self.workThread, SIGNAL("featureProcessed()"), self.featureProcessed)
        QObject.connect(self.workThread, SIGNAL("processingFinished( PyQt_PyObject )"), self.processFinished)
        QObject.connect(self.workThread, SIGNAL("processingInterrupted()"), self.processInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.workThread.start()
Esempio n. 54
0
    def fetchFiles(self, urls):
        self.logT("TileLayer.fetchFiles() starts")
        # create a QEventLoop object that belongs to the current thread (if ver. > 2.1, it is render thread)
        eventLoop = QEventLoop()
        self.logT("Create event loop: " + str(eventLoop))  # DEBUG
        QObject.connect(self, SIGNAL("allRepliesFinished()"), eventLoop.quit)

        # create a timer to watch whether rendering is stopped
        watchTimer = QTimer()
        watchTimer.timeout.connect(eventLoop.quit)

        # send a fetch request to the main thread
        self.emit(SIGNAL("fetchRequest(QStringList)"), urls)

        # wait for the fetch to finish
        tick = 0
        interval = 500
        timeoutTick = self.downloadTimeout / interval
        watchTimer.start(interval)
        while tick < timeoutTick:
            # run event loop for 0.5 seconds at maximum
            eventLoop.exec_()

            if debug_mode:
                qDebug("watchTimerTick: %d" % tick)
                qDebug("unfinished downloads: %d" % self.downloader.unfinishedCount())

            if self.downloader.unfinishedCount() == 0 or self.renderContext.renderingStopped():
                break
            tick += 1
        watchTimer.stop()

        if tick == timeoutTick and self.downloader.unfinishedCount() > 0:
            self.log("fetchFiles timeout")
            # self.showBarMessage("fetchFiles timeout", duration=5)   #DEBUG
            self.downloader.abort()
            self.downloader.errorStatus = Downloader.TIMEOUT_ERROR
        files = self.downloader.fetchedFiles

        watchTimer.timeout.disconnect(eventLoop.quit)  #
        QObject.disconnect(self, SIGNAL("allRepliesFinished()"), eventLoop.quit)

        self.logT("TileLayer.fetchFiles() ends")
        return files
Esempio n. 55
0
    def unload(self):
        """Unload the plugin"""
        self.getTimeLayerManager().deactivateTimeManagement()
        self.iface.unregisterMainWindowAction(self.actionShowSettings)
        self.guiControl.unload()

        self.iface.projectRead.disconnect(self.readSettings)
        self.iface.newProjectCreated.disconnect(self.restoreDefaults)
        self.iface.newProjectCreated.disconnect(self.disableAnimationExport)
        # QgsProject.instance().writeMapLayer.disconnect(self.writeSettings)
        QObject.disconnect(QgsProject.instance(),
                           SIGNAL("writeProject(QDomDocument &)"),
                           self.writeSettings)

        QgsMapLayerRegistry.instance().layerWillBeRemoved.disconnect(
            self.timeLayerManager.removeTimeLayer)
        QgsMapLayerRegistry.instance().removeAll.disconnect(
            self.timeLayerManager.clearTimeLayerList)
        QgsMapLayerRegistry.instance().removeAll.disconnect(
            self.disableAnimationExport)
Esempio n. 56
0
    def select(self, part):
        if self.current_part:
            self.current_part.set_selected(False)
        if isinstance(self.current_part, parts.SynthPart):
            if self.current_part.stream:
                QObject.disconnect(self.current_part.stream,
                                   SIGNAL('cursor(int)'),
                                   self.patternEditor.grid.set_play_cursor)
            self.patternEditor.grid.set_play_cursor(0)
        elif isinstance(self.current_part, parts.EffectPart):
            pass

        self.current_part = part
        if isinstance(self.current_part, parts.SynthPart):
            if self.current_part.stream:
                QObject.connect(self.current_part.stream, SIGNAL('cursor(int)'),
                                self.patternEditor.grid.set_play_cursor)
            self.current_part.set_selected(True)
        elif isinstance(self.current_part, parts.EffectPart):
            self.current_part.set_selected(True)
Esempio n. 57
0
  def accept( self ):
    self.inFiles = None
    if self.batchCheck.isChecked():
      self.inFiles = Utils.getRasterFiles( self.inSelector.filename(), self.recurseCheck.isChecked() )
    else:
      self.inFiles = [ self.inSelector.filename() ]

    self.progressBar.setRange( 0, len( self.inFiles ) )

    QApplication.setOverrideCursor( QCursor( Qt.WaitCursor ) )
    self.okButton.setEnabled( False )

    self.extractor = ExtractThread( self.inFiles, self.prjCheck.isChecked() )
    QObject.connect( self.extractor, SIGNAL( "fileProcessed()" ), self.updateProgress )
    QObject.connect( self.extractor, SIGNAL( "processFinished()" ), self.processingFinished )
    QObject.connect( self.extractor, SIGNAL( "processInterrupted()" ), self.processingInterrupted )

    QObject.disconnect( self.buttonBox, SIGNAL( "rejected()" ), self.reject )
    QObject.connect( self.buttonBox, SIGNAL( "rejected()" ), self.stopProcessing )

    self.extractor.start()