Пример #1
0
    def _create_map_tips(self):
        """ Create MapTips on the map """

        row = tools_gw.get_config_value('qgis_dim_tooltip')
        if not row or row[0].lower() != 'true':
            return

        tools_gw.disconnect_signal(
            'dimensioning',
            'create_map_tips_timer_map_tips_timeout_show_map_tip')
        self.timer_map_tips = QTimer(self.canvas)
        self.map_tip_node = QgsMapTip()
        self.map_tip_connec = QgsMapTip()

        tools_gw.connect_signal(
            self.canvas.xyCoordinates, self._map_tip_changed, 'dimensioning',
            'create_map_tips_xyCoordinates_map_tip_changed')
        tools_gw.connect_signal(
            self.timer_map_tips.timeout, self._show_map_tip, 'dimensioning',
            'create_map_tips_timer_map_tips_timeout_show_map_tip')

        tools_gw.disconnect_signal(
            'dimensioning',
            'create_map_tips_timer_map_tips_clear_timeout_clear_map_tip')
        self.timer_map_tips_clear = QTimer(self.canvas)
        tools_gw.connect_signal(
            self.timer_map_tips_clear.timeout, self._clear_map_tip,
            'dimensioning',
            'create_map_tips_timer_map_tips_clear_timeout_clear_map_tip')
    def __init__(self, parent, context, webPage, layerType):
        QObject.__init__(self, parent)

        debug("OpenlayersController.__init__", 3)
        self.context = context
        self.layerType = layerType

        self.img = QImage()

        self.page = webPage
        self.page.loadFinished.connect(self.pageLoaded)
        # initial size for map
        self.page.setViewportSize(QSize(1, 1))

        self.timerMapReady = QTimer()
        self.timerMapReady.setSingleShot(True)
        self.timerMapReady.setInterval(20)
        self.timerMapReady.timeout.connect(self.checkMapReady)

        self.timer = QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.checkMapUpdate)

        self.timerMax = QTimer()
        self.timerMax.setSingleShot(True)
        # TODO: different timeouts for map types
        self.timerMax.setInterval(2500)
        self.timerMax.timeout.connect(self.mapTimeout)
    def create_map_tips(self):
        """ Create MapTips on the map """

        row = self.controller.get_config('dim_tooltip')
        if not row or row[0].lower() != 'true':
            return

        self.timer_map_tips = QTimer(self.canvas)
        self.map_tip_node = QgsMapTip()
        self.map_tip_connec = QgsMapTip()

        self.canvas.xyCoordinates.connect(self.map_tip_changed)
        self.timer_map_tips.timeout.connect(self.show_map_tip)
        self.timer_map_tips_clear = QTimer(self.canvas)
        self.timer_map_tips_clear.timeout.connect(self.clear_map_tip)
Пример #4
0
 def __init__(self, iface, parent=None):
     """
     Class constructor.
     """
     self.canvas = iface.mapCanvas()
     super(DsgRasterInfoTool, self).__init__(parent)
     self.setupUi(self)
     self.bandTooltipButton.setToolTip(self.tr("Show raster tooltip"))
     self.dynamicHistogramButton.setToolTip(
         self.tr("Dynamic histogram view"))
     self.valueSetterButton.setToolTip(
         self.
         tr("Set raster value from mouse click\nShift + Left Click + Mouse Drag: Selects a set of points and assigns raster value for each point"
            ))
     self.assignBandValueTool = None
     self.parent = parent
     self.splitter.hide()
     self.iface = iface
     self.timerMapTips = QTimer(self.canvas)
     self.geometryHandler = GeometryHandler(iface)
     self.addShortcuts()
     self.valueSetterButton.setEnabled(False)
     self.iface.mapCanvas().currentLayerChanged.connect(
         self.enableAssignValue)
     self.iface.actionToggleEditing().triggered.connect(
         self.enableAssignValue)
     self.iface.mapCanvas().mapToolSet.connect(self.enableAssignValue)
     self.valueSetterButton.toggled.connect(self.activateValueSetter)
     # self.rasterComboBox.currentIndexChanged.connect(self.enableAssignValue)
     # start currentLayer selection
     self.currentLayer = None
Пример #5
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = os.path.join(self.plugin_dir,'icon.png')
        self.add_action(icon_path,text=self.tr(u'QRealTime Setting'),callback=self.run,parent=self.iface.mainWindow())
        """add sync action"""
        self.sync= self.add_layer_action(icon_path,self.tr(u'sync'),self.download,False)
	# make sync action checkable and default to unchecked
        self.sync.setCheckable(True)
        self.sync.setChecked(False)
        """add import action """
        self.Import=self.add_layer_action(icon_path,self.tr(u'import'),self.importData)
        """add makeonline action """
        self.makeOnline=self.add_layer_action(icon_path,self.tr(u'Make Online'),self.sendForm)
        service=self.dlg.getCurrentService()
        self.service=service
        self.topElement= None
        self.version=''
        try:
            self.time=86400
            self.time=int(service.getValue(self.tr('sync time')))
        except:
            print ('can not read time')
        self.timer=QTimer()
        def timeEvent():
            print ('calling collect data')
            self.service.importData(self.layer,self.formID,False)
        self.timer.timeout.connect(timeEvent)
Пример #6
0
    def __init__(self, layout, timerinterval=10000):
        QObject.__init__(self)
        self.interval = timerinterval

        if isinstance(layout, QVBoxLayout):
            self.layout = layout
            self.layout.setSpacing(2)

            # Set notification type stylesheet
            self.errorStyleSheet = "background-color: #FFBABA;"
            self.error_font_color = 'color: #D8000C;'

            self.successStyleSheet = "background-color: #DFF2BF;"
            self.success_font_color = 'color: #4F8A10;'

            self.informationStyleSheet = "background-color: #BDE5F8;"
            self.information_font_color = 'color: #555;'

            self.warningStyleSheet = "background-color: #FEEFB3;"
            self.warning_font_color = 'color: #9F6000;'
            # Timer settings
            self.timer = QTimer(self.layout)
            self.timer.setInterval(self.interval)
            self.timer.timeout.connect(self.clear)

        else:
            self.layout = None

        self._notifications = {}
Пример #7
0
    def _load_layer(self, loader, conn_info, meta, **kw_start):
        lst_layer = list()
        batch = 100 # kw_start.get("limit",30000)
        for i in range(6):
            timer = QTimer()
            timer.timeout.connect(lambda: self.check_loader(loader,batch))
            if not i:
                loader.start(conn_info, meta, **kw_start)
            else:
                loader.restart(conn_info, meta, **kw_start)

            timer.start(10)
            try:
                self._wait_async()
            except AllErrorsDuringTest as e:
                lst_err = e.args[0]
                self.assertIsInstance(lst_err[0], ManualInterrupt)
            finally:
                timer.stop()
                lst_layer.append(loader.layer)
                
            # with self.assertRaises(AllErrorsDuringTest, msg="stopping loader should emit error") as cm: 
            #     self._wait_async()
            # lst_err = cm.exception.args[0]
            # self.assertIsInstance(lst_err[0], ManualInterrupt)
        
        return lst_layer
Пример #8
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.boundary_change_queue = []
     self.timer = QTimer(self)
     self.timer.timeout.connect(self.process_queue)
     self.set_frequency(QgsSettings().value('redistrict/check_every', '30',
                                            int, QgsSettings.Plugins))
Пример #9
0
    def __init__(self, iface):
        QDockWidget.__init__(self, iface.mainWindow())
        self.setupUi(self)
        self.newsFrame.setVisible(False)

        self.iface = iface
        self.search_threads = None  # []
        self.extent_renderer = RubberBandResultRenderer()

        self.cmbStatusFilter.addItem(self.tr('All'), STATUS_FILTER_ALL)
        self.cmbStatusFilter.addItem(self.tr('Valid'),
                                     STATUS_FILTER_ONLY_WORKS)
        self.cmbStatusFilter.currentIndexChanged.connect(self.start_search)

        if hasattr(self.txtSearch, 'setPlaceholderText'):
            self.txtSearch.setPlaceholderText(self.tr("Search string..."))

        self.delay_timer = QTimer(self)
        self.delay_timer.setSingleShot(True)
        self.delay_timer.setInterval(250)

        self.delay_timer.timeout.connect(self.start_search)
        self.txtSearch.textChanged.connect(self.delay_timer.start)
        self.btnFilterByExtent.toggled.connect(self.toggle_filter_button)
        self.one_process_work = QMutex()

        self.add_last_used_services()

        self.show_news()
Пример #10
0
    def _check_path_exists(self, path, text_box):
        # Validates if the specified folder exists
        dir = QDir()

        if not dir.exists(path):
            msg = self.tr("'{0}' directory does not exist.".format(path))
            self.notif_bar.insertErrorNotification(msg)

            # Highlight textbox control
            text_box.setStyleSheet(INVALIDATESTYLESHEET)

            timer = QTimer(self)
            # Sync interval with that of the notification bar
            timer.setInterval(self.notif_bar.interval)
            timer.setSingleShot(True)

            # Remove previous connected slots (if any)
            receivers = timer.receivers(QTimer.timeout)
            if receivers > 0:
                self._timer.timeout.disconnect()

            timer.start()
            timer.timeout.connect(lambda: self._restore_stylesheet(
                text_box)
                                  )

            return False

        return True
Пример #11
0
 def __init__(self, filename):
     super(FileGPSService, self).__init__()
     self.file = None
     self.timer = QTimer()
     self.timer.setInterval(100)
     self.timer.timeout.connect(self._read_from_file)
     self.filename = filename
    def load(self):
        # initialise UI
        self.dlg = AnalysisDialog(self.iface.mainWindow())

        # initialise axial analysis classes
        self.verificationThread = None

        # connect signal/slots with main program
        self.project.settingsUpdated.connect(self.setDatastore)
        self.editDatastoreSettings.connect(self.project.showDialog)

        # set up GUI signals
        self.dlg.visibilityChanged.connect(self.onShow)
        self.dlg.analysisDataButton.clicked.connect(self.changeDatastore)
        self.dlg.updateDatastore.connect(self.updateDatastore)
        self.dlg.axialVerifyButton.clicked.connect(self.runAxialVerification)
        self.dlg.axialUpdateButton.clicked.connect(self.runAxialUpdate)
        self.dlg.axialVerifyCancelButton.clicked.connect(
            self.cancelAxialVerification)
        self.dlg.axialReportList.itemSelectionChanged.connect(
            self.zoomAxialProblem)
        self.dlg.axialDepthmapCalculateButton.clicked.connect(
            self.run_analysis)
        self.dlg.axialDepthmapCancelButton.clicked.connect(
            self.cancel_analysis)

        # initialise internal globals
        self.isVisible = False
        self.datastore = dict()
        self.running_analysis = ""
        self.start_time = None
        self.end_time = None
        self.analysis_nodes = 0
        self.axial_id = ""
        self.all_ids = []
        self.current_layer = None

        # timer to check for analysis result
        self.timer = QTimer()
        self.timer.timeout.connect(self.check_analysis_progress)

        # define analysis data structures
        self.analysis_layers = {'map': "", 'unlinks': "", 'map_type': 0}
        self.axial_analysis_settings = {
            'type': 0,
            'distance': 0,
            'radius': 0,
            'rvalues': "n",
            'output': "",
            'fullset': 0,
            'betweenness': 1,
            'newnorm': 1,
            'weight': 0,
            'weightBy': "",
            'stubs': 40,
            'id': ""
        }
        self.user_ids = {'map': "", 'unlinks': ""}
        self.analysis_output = ""
        self.getProjectSettings()
Пример #13
0
    def __init__(self,
                 parent=None,
                 notificationbar=None,
                 dbmodel=None,
                 attrname=None):
        '''
        :param parent: Parent widget
        :param notificationbar: instance of stdm.ui.NotificationBar class.
        '''
        QLineEdit.__init__(self, parent)
        self._notifBar = notificationbar
        self._dbmodel = None
        self._attrName = None
        self._timer = QTimer(self)
        self._timer.setInterval(800)
        self._timer.setSingleShot(True)
        self._invalidMsg = ""
        self._filterOperator = "="
        self._defaultStyleSheet = self.styleSheet()
        self._isValid = True
        self._currInvalidMsg = ""

        # Connect signals
        self._timer.timeout.connect(self.validateInput)
        self.textChanged.connect(self.onTextChanged)
    def test_link_feature(self):
        """
        Check if an existing feature can be linked
        """
        wrapper = self.createWrapper(self.vl_a, '"name"=\'Douglas Adams\'')  # NOQA

        f = QgsFeature(self.vl_b.fields())
        f.setAttributes([self.vl_b.dataProvider().defaultValueClause(0), 'The Hitchhiker\'s Guide to the Galaxy'])
        self.vl_b.addFeature(f)

        def choose_linked_feature():
            dlg = QApplication.activeModalWidget()
            dlg.setSelectedFeatures([f.id()])
            dlg.accept()

        btn = self.widget.findChild(QToolButton, 'mLinkFeatureButton')

        timer = QTimer()
        timer.setSingleShot(True)
        timer.setInterval(0)  # will run in the event loop as soon as it's processed when the dialog is opened
        timer.timeout.connect(choose_linked_feature)
        timer.start()

        btn.click()
        # magically the above code selects the feature here...

        link_feature = next(self.vl_link.getFeatures(QgsFeatureRequest().setFilterExpression('"fk_book"={}'.format(f[0]))))
        self.assertIsNotNone(link_feature[0])

        self.assertEqual(self.table_view.model().rowCount(), 1)
Пример #15
0
    def _get_sync(self, qurl: QUrl, timeout: int = 20000) -> Reply:
        '''
        synchronous GET-request
        '''
        request = QNetworkRequest(qurl)
        ## newer versions of QGIS (3.6+) support synchronous requests
        #if hasattr(self._manager, 'blockingGet'):
        #reply = self._manager.blockingGet(request, forceRefresh=True)
        ## use blocking event loop for older versions
        #else:
        loop = QEventLoop()
        timer = QTimer()
        timer.setSingleShot(True)
        # reply or timeout break event loop, whoever comes first
        timer.timeout.connect(loop.quit)
        reply = self._manager.get(request)
        reply.finished.connect(loop.quit)

        timer.start(timeout)

        # start blocking loop
        loop.exec()
        loop.deleteLater()
        if not timer.isActive():
            reply.deleteLater()
            raise ConnectionError('Timeout')

        timer.stop()
        #if reply.error():
        #self.error.emit(reply.errorString())
        #raise ConnectionError(reply.errorString())
        res = Reply(reply)
        self.finished.emit(res)
        return res
    def __init__(self,
                 connector,
                 geogiglayer,
                 fullDetail=False,
                 sm_factor=1.0,
                 sm_type="WithBBOX"):
        self.connector = connector
        self.geogiglayer = geogiglayer

        self.queryThread = QueryThread(self.connector)
        self.queryThread.started.connect(self.datasetStart)
        self.queryThread.finished.connect(self.datasetReceived)
        self.queryThread.progress_occurred.connect(self.featuresRead)

        self.refreshTimer = QTimer()
        self.refreshTimer.setSingleShot(True)
        self.refreshTimer.timeout.connect(self.makeQuery)

        self.lastExtent = None
        self.sm_factor = sm_factor
        self.sm_type = sm_type

        root = QgsProject.instance().layerTreeRoot()
        root.visibilityChanged.connect(
            self.visibilityChanged)  # track all layer visibility changes
        self.fullDetail = fullDetail
Пример #17
0
    def highlight_feature(self, canvas_extent=CanvasExtent.Fixed):
        if self.canvas is None or not self.feature.isValid():
            return

        geom = self.feature.geometry()

        if geom is None:
            return

        if canvas_extent == CanvasExtent.Scale:
            feature_bounding_box = geom.boundingBox()
            feature_bounding_box = self.canvas.mapSettings(
            ).layerToMapCoordinates(self.layer, feature_bounding_box)
            extent = self.canvas.extent()
            if not extent.contains(feature_bounding_box):
                extent.combineExtentWith(feature_bounding_box)
                extent.scale(1.1)
                self.canvas.setExtent(extent)
                self.canvas.refresh()

        elif canvas_extent == CanvasExtent.Pan:
            centroid = geom.centroid()
            center = centroid.asPoint()

            center = self.canvas.mapSettings().layerToMapCoordinates(
                self.layer, center)
            self.canvas.zoomByFactor(1.0,
                                     center)  # refresh is done in this method

        # highlight
        self.delete_highlight()
        self.highlight = QgsHighlight(self.canvas, geom, self.layer)

        settings = QSettings()
        color = QColor(
            settings.value("/Map/highlight/color",
                           Qgis.DEFAULT_HIGHLIGHT_COLOR.name()))
        alpha = int(
            settings.value("/Map/highlight/colorAlpha",
                           Qgis.DEFAULT_HIGHLIGHT_COLOR.alpha()))
        buffer = 2 * float(
            settings.value("/Map/highlight/buffer",
                           Qgis.DEFAULT_HIGHLIGHT_BUFFER_MM))
        min_width = 2 * float(
            settings.value("/Map/highlight/min_width",
                           Qgis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM))

        self.highlight.setColor(color)  # sets also fill with default alpha
        color.setAlpha(alpha)
        self.highlight.setFillColor(color)  # sets fill with alpha
        self.highlight.setBuffer(buffer)
        self.highlight.setMinWidth(min_width)
        self.highlight.setWidth(4.0)
        self.highlight.show()

        self.timer = QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.delete_highlight)
        self.timer.start(3000)
Пример #18
0
 def createScreenshot(self, obj, rect=None):
     if self.capturing and self.timer is None:
         self.timer = QTimer()
         self.timer.setInterval(1000)
         self.timer.setSingleShot(True)
         self.timer.timeout.connect(
             lambda: self._createScreenshot(obj, rect))
         self.timer.start()
    def __init__(self, iface, parent=None, wizard_embedded=False):

        QDialog.__init__(self, parent)
        self.iface = iface
        self._close_editing()

        self.setupUi(self)
        self.buttonBox.accepted.connect(self._accepted)
        self.buttonBox.rejected.connect(self._rejected)

        self.type_combo_box.clear()
        self._lst_panel = dict()
        self.db_simple_factory = DbSimpleFactory()

        for db_id in self.db_simple_factory.get_db_list(False):
            self.type_combo_box.addItem(displayDbIliMode[db_id], db_id)
            db_factory = self.db_simple_factory.create_factory(db_id)
            item_panel = db_factory.get_config_panel(self, DbActionType.EXPORT)
            self._lst_panel[db_id] = item_panel
            self.db_layout.addWidget(item_panel)

        self.type_combo_box.currentIndexChanged.connect(self._type_changed)

        # when opened by the wizard it uses the current db connection settings and should not be changable
        self.db_frame.setHidden(wizard_embedded)

        self.dataset_model = DatasetModel()
        self.dataset_tableview.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.dataset_tableview.horizontalHeader().hide()
        self.dataset_tableview.verticalHeader().hide()
        self.dataset_tableview.setSelectionMode(QTableView.SingleSelection)
        self.dataset_tableview.setModel(self.dataset_model)

        self._restore_configuration()

        # refresh the models on changing values but avoid massive db connects by timer
        self.refreshTimer = QTimer()
        self.refreshTimer.setSingleShot(True)
        self.refreshTimer.timeout.connect(
            lambda: self._refresh_datasets(self._updated_configuration()))

        for key, value in self._lst_panel.items():
            value.notify_fields_modified.connect(
                self._request_for_refresh_datasets)

        self._refresh_datasets(self._updated_configuration())

        self.add_button.clicked.connect(self._add_dataset)
        self.edit_button.clicked.connect(self._edit_dataset)
        self.create_baskets_button.clicked.connect(self._create_baskets)
        self.dataset_tableview.selectionModel().selectionChanged.connect(
            lambda: self._enable_dataset_handling(True))

        self.add_button.setIcon(
            QgsApplication.getThemeIcon("/symbologyAdd.svg"))
        self.edit_button.setIcon(
            QgsApplication.getThemeIcon("/symbologyEdit.svg"))
Пример #20
0
    def __init__(self, iface, model):
        """Initialize the GUI control"""
        QObject.__init__(self)
        self.iface = iface
        self.model = model
        self.optionsDialog = None
        self.path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ui')

        # load the form
        self.dock = uic.loadUi(os.path.join(self.path, DOCK_WIDGET_FILE))
        self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dock)

        self.dock.pushButtonExportVideo.setEnabled(False)  # only enabled if there are managed layers
        self.dock.pushButtonOptions.clicked.connect(self.optionsClicked)
        self.dock.pushButtonExportVideo.clicked.connect(self.exportVideoClicked)
        self.dock.pushButtonToggleTime.clicked.connect(self.toggleTimeClicked)
        self.dock.pushButtonArchaeology.clicked.connect(self.archaeologyClicked)
        self.dock.pushButtonBack.clicked.connect(self.backClicked)
        self.dock.pushButtonForward.clicked.connect(self.forwardClicked)
        self.dock.pushButtonPlay.clicked.connect(self.playClicked)
        self.dock.dateTimeEditCurrentTime.dateTimeChanged.connect(self.currentTimeChangedDateText)
        # self.dock.horizontalTimeSlider.valueChanged.connect(self.currentTimeChangedSlider)

        self.sliderTimer = QTimer(self)
        self.sliderTimer.setInterval(250)
        self.sliderTimer.setSingleShot(True)
        self.sliderTimer.timeout.connect(self.currentTimeChangedSlider)
        self.dock.horizontalTimeSlider.valueChanged.connect(self.startTimer)

        self.dock.comboBoxTimeExtent.currentIndexChanged[str].connect(self.currentTimeFrameTypeChanged)
        self.dock.spinBoxTimeExtent.valueChanged.connect(self.currentTimeFrameSizeChanged)

        # this signal is responsible for rendering the label
        self.iface.mapCanvas().renderComplete.connect(self.renderLabel)

        # create shortcuts
        self.focusSC = QShortcut(QKeySequence("Ctrl+Space"), self.dock)
        self.focusSC.activated.connect(self.dock.horizontalTimeSlider.setFocus)

        # put default values
        self.dock.horizontalTimeSlider.setMinimum(conf.MIN_TIMESLIDER_DEFAULT)
        self.dock.horizontalTimeSlider.setMaximum(conf.MAX_TIMESLIDER_DEFAULT)
        self.dock.dateTimeEditCurrentTime.setMinimumDate(MIN_QDATE)
        self.showLabel = conf.DEFAULT_SHOW_LABEL
        self.exportEmpty = conf.DEFAULT_EXPORT_EMPTY
        self.labelOptions = TimestampLabelConfig(self.model)

        # placeholders for widgets that are added dynamically
        self.bcdateSpinBox = None

        # add to plugins toolbar
        try:
            self.action = QAction(QCoreApplication.translate("TimeManagerGuiControl", "Toggle visibility"), self.iface.mainWindow())
            self.action.triggered.connect(self.toggleDock)
            self.iface.addPluginToMenu(QCoreApplication.translate("TimeManagerGuiControl", "&TimeManager"), self.action)
        except Exception as e:
            pass  # OK for testing
Пример #21
0
    def __init__(self, canvas, ms):  # msはミリ秒
        QgsMapTool.__init__(self, canvas)

        self.canvas = canvas

        self.ms = ms
        # canvasMoveEventで設定した秒数(msで設定)経過したら呼ばれるメソッドを設定
        self.timerMapTips = QTimer(canvas)
        self.timerMapTips.timeout.connect(self.showMapTip)
Пример #22
0
 def resize_timer_set(self):
     """Odpalenie stopera sprawdzającego, czy dockwidget skończył zmieniać swój rozmiar."""
     if self.resize_timer:
         # Timer już działa
         return
     # Odpalenie stopera:
     self.resize_timer = QTimer(self, interval=10)
     self.resize_timer.timeout.connect(self.resize_check)
     self.resize_timer.start()  # Odpalenie stopera
Пример #23
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = os.path.join(self.plugin_dir, 'icon.png')
        self.add_action(icon_path,
                        text=self.tr(u'QRealTime Setting'),
                        callback=self.run,
                        parent=self.iface.mainWindow())
        self.ODKMenu = QMenu('QRealTime')
        icon = QIcon(icon_path)
        self.sync = QAction(self.tr(u'sync'), self.ODKMenu)
        self.sync.setCheckable(True)
        self.sync.setChecked(False)
        self.sync.triggered.connect(self.download)
        self.sync.setChecked(False)
        self.iface.addCustomActionForLayerType(self.sync, 'QRealTime',
                                               QgsMapLayer.VectorLayer, True)

        self.Import = QAction(icon, self.tr(u'import'), self.ODKMenu)
        self.Import.triggered.connect(self.importData)
        self.iface.addCustomActionForLayerType(self.Import, 'QRealTime',
                                               QgsMapLayer.VectorLayer, True)
        self.makeOnline = QAction(icon, self.tr(u'Make Online'), self.ODKMenu)
        self.makeOnline.triggered.connect(self.sendForm)
        self.iface.addCustomActionForLayerType(self.makeOnline, 'QRealTime',
                                               QgsMapLayer.VectorLayer, True)
        service = self.dlg.getCurrentService()
        self.service = service
        self.topElement = None
        self.version = ''
        try:
            self.time = 1
            self.time = int(service.getValue('sync time'))
        except:
            print('can not read time')
        self.timer = QTimer()

        def timeEvent():
            print('calling collect data')
            layer = self.getLayer()
            print(layer)
            if (not self.topElement):
                url = service.getValue(
                    'url') + '//formXml?formId=' + layer.name()
                response = requests.request('GET',
                                            url,
                                            proxies=getProxiesConf(),
                                            auth=service.getAuth(),
                                            verify=False)
                if response.status_code == 200:
                    self.formKey, self.topElement, self.version, self.geoField = self.updateLayer(
                        layer, response.content)
            service.collectData(layer, layer.name(), False, self.topElement,
                                self.version, self.geoField)

        self.timer.timeout.connect(timeEvent)
Пример #24
0
    def __init__(self, iface):
        super().__init__()
        self.iface = iface

        stack = QgsPanelWidgetStack()

        self.main_panel = QgsPanelWidget()
        self.main_panel.setDockMode(True)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setMargin(0)  # pylint: disable=no-value-for-parameter
        self.main_panel.setLayout(layout)
        self.setWindowTitle(self.tr('Project Colors'))
        self.setObjectName('project_colors_dock')

        scheme = [
            s for s in QgsApplication.colorSchemeRegistry().schemes()
            if isinstance(s, QgsProjectColorScheme)
        ]
        self.color_list = QgsColorSchemeList(None, scheme[0])
        layout.addWidget(self.color_list)

        # defer updates for a short timeout -- prevents flooding with signals
        # when doing lots of color changes, improving app responsiveness
        self.timer = QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.setInterval(100)

        self.block_updates = False

        def apply_colors():
            """
            Applies color changes to canvas and project
            """
            self.block_updates = True
            self.color_list.saveColorsToScheme()
            self.block_updates = False
            self.iface.mapCanvas().refreshAllLayers()

        self.timer.timeout.connect(apply_colors)

        def colors_changed():
            """
            Triggers a deferred update of the project colors
            """
            if self.timer.isActive():
                return
            self.timer.start()

        self.color_list.model().dataChanged.connect(colors_changed)
        stack.setMainPanel(self.main_panel)
        self.setWidget(stack)

        QgsProject.instance().projectColorsChanged.connect(
            self.repopulate_list)
Пример #25
0
    def __init__(self, worker: Worker, parent: QObject = None,
                 auto_close: bool = False, auto_run: bool = True,
                 on_success: object = None, on_close: object = None):
        '''
        Parameters
        ----------
        worker : Worker
            Worker object holding the task to do
        parent : QObject, optional
            parent ui element of the dialog, defaults to no parent
        auto_close : bool, optional
            close dialog automatically after task is done, defaults to automatic
            close
        auto_run : bool, optional
            start task automatically when showing the dialog, otherwise the user
            has to start it by pressing the start-button, defaults to automatic
            start
        on_success : object, optional
            function to call on successful run of task, function has to expect
            the result of the task as an argument, defaults to no callback on
            success
        on_close : object, optional
            function to call when closing the dialog, defaults to no callback on
            closing
        '''
        # parent = parent or iface.mainWindow()
        super().__init__(self.ui_file, modal=True, parent=parent)
        self.parent = parent
        self.setupUi()
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.progress_bar.setValue(0)
        self.stop_button.setVisible(False)
        self.close_button.setVisible(False)
        self.auto_close_check.setChecked(auto_close)
        self.auto_run = auto_run
        # ToDo: use signals instead of callbacks
        self.on_success = on_success
        self.on_close = on_close
        self.success = False
        self.error = False

        self.worker = worker
        if self.worker:
            self.worker.finished.connect(self._success)
            self.worker.error.connect(self.on_error)
            self.worker.message.connect(self.show_status)
            self.worker.progress.connect(self.progress)

        self.start_button.clicked.connect(self.run)
        self.stop_button.clicked.connect(self.stop)
        self.close_button.clicked.connect(self.close)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self._update_timer)
Пример #26
0
 def show(self):
     super().show()
     self.timer=QTimer(self)
     self.timer.setSingleShot(True)
     self.timer.timeout.connect(lambda: self.hide())
     self.timer.start(self.temps*1000)
     # self.show()
     if self.parent is not None:
         #Ja que python no té switch-case, ho fem amb una llista
         pos=[(10,10),(self.parent.width()-self.width()-10,10),(10,self.parent.height()-self.height()-10),(self.parent.width()-self.width()-10,self.parent.height()-self.height()-10)][self.pos]
         self.move(*pos)
Пример #27
0
 def update_referecedata_cache_model(self, filter_models, type):
     # updates the model and waits for the end
     loop = QEventLoop()
     self.ilireferencedatacache.model_refreshed.connect(lambda: loop.quit())
     timer = QTimer()
     timer.setSingleShot(True)
     timer.timeout.connect(lambda: loop.quit())
     timer.start(10000)
     self.refresh_referencedata_cache(filter_models, type)
     loop.exec()
     return self.ilireferencedatacache.model
Пример #28
0
    def __init(self):
        self.checkBoxHideCross.setEnabled(False)
        self.__populateTypeMapGUI()
        self.__populateButtonBox()
        self.__registerObjJS()
        self.lbStatusRead.setVisible(False)
        self.__setConnections()

        self.__timerMapReady = QTimer()
        self.__timerMapReady.setSingleShot(True)
        self.__timerMapReady.setInterval(20)
        self.__timerMapReady.timeout.connect(self.__checkMapReady)
 def start_polling(self):
     if not self.is_logged_in:
         try:
             self.login()
         except HANDLED_EXCEPTIONS as exc:
             self._handle_exception(exc)
     if not self.is_logged_in:
         return
     self.refresh_calc_list()
     self.timer = QTimer()
     QObject.connect(
         self.timer, SIGNAL('timeout()'), self.refresh_calc_list)
     self.timer.start(5000)  # refresh calc list time in milliseconds
Пример #30
0
    def loading(self):
        """ Loading progress bar """

        self.dialog = QProgressDialog()
        self.dialog.setWindowTitle("Loading")
        self.dialog.setLabelText("That's your progress")
        self.bar = QProgressBar()
        self.bar.setTextVisible(True)
        self.dialog.setBar(self.bar)
        self.dialog.setMinimumWidth(300)
        self.dialog.show()
        self.timer = QTimer()
        self.timer.timeout.connect(self.saver)
        self.timer.start(1000)