示例#1
0
 def createView(self):
     name, ok = QInputDialog.getText(None, "View name", "View name")
     if ok:
         try:
             self.db.connector.createSpatialView(name, self._getSqlQuery())
         except BaseError as e:
             DlgDbError.showError(e, self)
示例#2
0
    def connect(self, selected, parent=None):
        settings = QSettings()
        settings.beginGroup(u"/%s/connections/%s" % (self.getSettingsKey(), selected))

        if not settings.contains("database"):  # non-existent entry?
            raise DbError('there is no defined database connection "%s".' % selected)

        get_value_str = lambda x: str(settings.value(x) if Utils.isSIPv2() else settings.value(x).toString())
        service, host, port, database, username, password = list(map(get_value_str, ["service", "host", "port", "database", "username", "password"]))

        # qgis1.5 use 'savePassword' instead of 'save' setting
        isSave = settings.value("save") if Utils.isSIPv2() else settings.value("save").toBool()
        isSavePassword = settings.value("savePassword") if Utils.isSIPv2() else settings.value("savePassword").toBool()
        if not (isSave or isSavePassword):
            (password, ok) = QInputDialog.getText(parent, "Enter password", 'Enter password for connection "%s":' % selected, QLineEdit.Password)
            if not ok: return

        settings.endGroup()

        uri = QgsDataSourceUri()
        if service:
            uri.setConnection(service, database, username, password)
        else:
            uri.setConnection(host, port, database, username, password)

        return Connection(uri)
    def saveToGeopackage(self):
        file_filter = self.tr('GeoPackage files (*.gpkg);;All files (*.*)', 'OutputFile')

        settings = QgsSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        filename, filter = QFileDialog.getSaveFileName(self, self.tr("Save to GeoPackage"), path,
                                                       file_filter, options=QFileDialog.DontConfirmOverwrite)

        if not filename:
            return

        layer_name, ok = QInputDialog.getText(self, self.tr('Save to GeoPackage'), self.tr('Layer name'), text=self.parameter.name().lower())
        if ok:
            self.use_temporary = False
            if not filename.lower().endswith('.gpkg'):
                filename += '.gpkg'
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(filename))

            uri = QgsDataSourceUri()
            uri.setDatabase(filename)
            uri.setDataSource('', layer_name,
                              'geom' if isinstance(self.parameter, QgsProcessingParameterFeatureSink) and self.parameter.hasGeometry() else None)
            self.leText.setText("ogr:" + uri.uri())

            self.skipOutputChanged.emit(False)
            self.destinationChanged.emit()
 def showGoogleMapsApiKeyDialog(self):
     apiKey = QSettings().value("Plugin-OpenLayers/googleMapsApiKey")
     newApiKey, ok = QInputDialog.getText(
         self.iface.mainWindow(), "API key",
         "Enter your Google Maps API key", QLineEdit.Normal, apiKey)
     if ok:
         QSettings().setValue("Plugin-OpenLayers/googleMapsApiKey",
                              newApiKey)
 def showThunderforestApiKeyDialog(self):
     apiKey = QSettings().value("Plugin-OpenLayers/thunderforestApiKey")
     newApiKey, ok = QInputDialog.getText(
         self.iface.mainWindow(), "API key",
         "Enter your API key (<a href=\"https://thunderforest.com/pricing/\">https://thunderforest.com</a>)", QLineEdit.Normal, apiKey)
     if ok:
         QSettings().setValue("Plugin-OpenLayers/thunderforestApiKey",
                              newApiKey)
 def layernameValid(self):   
     if not hasattr(self, 'layerName'):
       layerName, accept = QInputDialog.getText(None,
           QCoreApplication.translate("geopunt4Qgis", 'Laag toevoegen'),
           QCoreApplication.translate("geopunt4Qgis", 'Geef een naam voor de laag op:') )
       if accept == False: 
          return False
       else: 
          self.layerName = layerName
     return True
 def saveLineClicked(self):
     if not hasattr(self, 'profileLineLayerTxt'):
        layerName, accept = QInputDialog.getText(None,
           QCoreApplication.translate("geopunt4Qgis", 'Laag toevoegen'),
           QCoreApplication.translate("geopunt4Qgis", 'Geef een naam voor de laag op:') )
        if accept == False: 
           return
        else:  
           self.profileLineLayerTxt = layerName
        
     if self.profile != None and self.Rubberline != None:
        title = self.ax.get_title()
        self.eh.save_profile( self.Rubberline.asGeometry(), self.profile, title,
                           self.profileLineLayerTxt, self.profileLineSavetoFile, sender=self )
 def savePntClicked(self):
     if not hasattr(self, 'sampleLayerTxt'):
        layerName, accept = QInputDialog.getText(None,
           QCoreApplication.translate("geopunt4Qgis", 'Laag toevoegen'),
           QCoreApplication.translate("geopunt4Qgis", 'Geef een naam voor de laag op:') )
        if accept == False: 
           return
        else:  
           self.sampleLayerTxt = layerName
   
     if self.profile != None:
        title = self.ax.get_title()
        self.eh.save_sample_points( self.profile, title, 
                                self.sampleLayerTxt, self.samplesSavetoFile, sender=self )
示例#9
0
文件: plugin.py 项目: wongjimsan/QGIS
    def createSchemaActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, (DBPlugin, Schema, Table)) or item.database() is None:
                parent.infoBar.pushMessage(
                    QApplication.translate("DBManagerPlugin", "No database selected or you are not connected to it."),
                    QgsMessageBar.INFO, parent.iface.messageTimeout())
                return
            (schema, ok) = QInputDialog.getText(parent, QApplication.translate("DBManagerPlugin", "New schema"),
                                                QApplication.translate("DBManagerPlugin", "Enter new schema name"))
            if not ok:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        self.createSchema(schema)
示例#10
0
 def _addReverse(self, adres):
     formattedAddress, locationType = adres["FormattedAddress"] , adres["LocationType"]
     xlam72, ylam72 = adres["Location"]["X_Lambert72"] , adres["Location"]["Y_Lambert72"]
 
     if not hasattr(self, 'layerName_reverse'):
        layerName, accept = QInputDialog.getText(None,
          QCoreApplication.translate("geopunt4Qgis", 'Laag toevoegen'),
          QCoreApplication.translate("geopunt4Qgis", 'Geef een naam voor de laag op:'))
        if accept == False: return
        else:  self.layerName_reverse = layerName
        
     xy = self.gh.prjPtToMapCrs([xlam72, ylam72], 31370)
     self.gh.save_adres_point(xy, formattedAddress, locationType, layername=self.layerName_reverse, 
       startFolder=os.path.join( self.startDir, self.layerName_reverse), saveToFile=self.saveToFile_reverse ,
       sender=self.iface.mainWindow())
     self.iface.messageBar().popWidget()	
     self._clearGraphicLayer()
示例#11
0
	def _askTStablename(self, ps_layer, default_tblname=None):
		# utility function used to ask to the user the name of the table
		# containing time series data
		if default_tblname is None:
			default_tblname = ""

		# ask a tablename to the user
		if ps_layer.id() != self.last_ps_layerid or not self.ts_tablename:
			tblname, ok = QInputDialog.getText( self.iface.mainWindow(),
					"PS Time Series Viewer",
					"Insert the name of the table containing time-series",
					text=default_tblname )
			if not ok:
				return False

			self.ts_tablename = tblname
			self.last_ps_layerid = ps_layer.id()

		return True
 def createRepo(self):
     name, ok = QInputDialog.getText(self, 'Create repository',
                                           'Enter the repository name:')
     if ok:
         group = self.comboEndpoint.currentText()
         url = repository.repoEndpoints[group]
         try:
             repo = execute(lambda: createRepoAtUrl(url, group, name))
         except GeoGigException as e:
             config.iface.messageBar().pushMessage("Error", str(e),
                            level=QgsMessageBar.CRITICAL,
                            duration=5)
             return
         item = RepoItem(self, self.repoTree, repo)
         addRepo(repo)
         self.repoTree.addTopLevelItem(item)
         config.iface.messageBar().pushMessage("Create repository", "Repository correctly created",
                                        level=QgsMessageBar.INFO,
                                        duration=5)
示例#13
0
    def saveToGeopackage(self):
        file_filter = self.tr('GeoPackage files (*.gpkg);;All files (*.*)',
                              'OutputFile')

        settings = QgsSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        filename, filter = QFileDialog.getSaveFileName(
            self,
            self.tr("Save to GeoPackage"),
            path,
            file_filter,
            options=QFileDialog.DontConfirmOverwrite)

        if not filename:
            return

        layer_name, ok = QInputDialog.getText(
            self,
            self.tr('Save to GeoPackage'),
            self.tr('Layer name'),
            text=self.parameter.name().lower())
        if ok:
            self.use_temporary = False
            if not filename.lower().endswith('.gpkg'):
                filename += '.gpkg'
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(filename))

            uri = QgsDataSourceUri()
            uri.setDatabase(filename)
            uri.setDataSource(
                '', layer_name, 'geom' if
                isinstance(self.parameter, QgsProcessingParameterFeatureSink)
                and self.parameter.hasGeometry() else None)
            self.leText.setText("ogr:" + uri.uri())

            self.skipOutputChanged.emit(False)
            self.destinationChanged.emit()
示例#14
0
    def set_nodata(self):
        """Set NoData value(s) for each band of current raster."""
        if not self.raster:
            self.uc.bar_warn('Select a raster layer to define/change NoData value!')
            return
        if self.handler.provider.userNoDataValues(1):
            note = '\nNote: there is a user defined NODATA value.\nCheck the raster properties (Transparency).'
        else:
            note = ''
        dt = self.handler.provider.dataType(1)
        
        # current NODATA value
        if self.handler.provider.sourceHasNoDataValue(1):
            cur_nodata = self.handler.provider.sourceNoDataValue(1)
            if dt < 6:
                cur_nodata = '{0:d}'.format(int(float(cur_nodata)))
        else:
            cur_nodata = ''
        
        label = 'Define/change raster NODATA value.\n\n'
        label += 'Raster src_data type: {}.{}'.format(dtypes[dt]['name'], note)
        nd, ok = QInputDialog.getText(None, "Define NODATA Value", label, QLineEdit.Normal, str(cur_nodata))
        if not ok:
            return
        if not is_number(nd):
            self.uc.show_warn('Wrong NODATA value!')
            return
        new_nodata = int(nd) if dt < 6 else float(nd)
        
        # set the NODATA value for each band
        res = []
        for nr in self.handler.bands_range:
            res.append(self.handler.provider.setNoDataValue(nr, new_nodata))
            self.handler.provider.sourceHasNoDataValue(nr)
        
        if False in res:
            self.uc.show_warn('Setting new NODATA value failed!')
        else:
            self.uc.bar_info('Successful setting new NODATA values!', dur=2)

        self.set_active_raster()
        self.raster.triggerRepaint()
 def setDelim(self, idx):
     txt = self.ui.delimSelect.itemText(idx)
     accept = True
     if txt == 'Puntcomma':
         self.delimiter = ';'
         self.loadTable()
     elif txt == 'Comma':
         self.delimiter = ','
         self.loadTable()
     elif txt ==  'Tab':
         self.delimiter = '\t'
         self.loadTable()
     else:
         delimiter, accept = QInputDialog.getText(self, 
             QCoreApplication.translate("batcGeoCodedialog","Andere separator") , 
             QCoreApplication.translate("batcGeoCodedialog","Stel zelf een separator in: (Maximaal 1 karakter)"))
         if accept:
             self.delimiter = str( delimiter.strip()[0])
             self.ui.delimEdit.setText(self.delimiter)
             self.loadTable()
示例#16
0
def user_input_label(label_req, question):
    label = ''
    qid = QInputDialog()
    #communiceer met de gebruiker voor input, waarbij question de vraag is die wordt gesteld
    if label_req < '2':
        while True:
            label, ok = QInputDialog.getText(
                qid,
                "Label:",
                question,
                QLineEdit.Normal,
            )
            if ok:
                if label != '' or label_req == '0':
                    return label
                    break
            else:
                label = 'Cancel'
                return label
                break
示例#17
0
    def _askTStablename(self, ps_layer, default_tblname=None):
        # utility function used to ask to the user the name of the table
        # containing time series data
        if default_tblname is None:
            default_tblname = ""

        # ask a tablename to the user
        if ps_layer.id() != self.last_ps_layerid or not self.ts_tablename:
            tblname, ok = QInputDialog.getText(
                self.iface.mainWindow(),
                "PS Time Series Viewer",
                "Insert the name of the table containing time-series",
                text=default_tblname)
            if not ok:
                return False

            self.ts_tablename = tblname
            self.last_ps_layerid = ps_layer.id()

        return True
示例#18
0
def authenticate():
    auth_url = ee.oauth.get_authorization_url()
    webbrowser.open_new(auth_url)

    print(
        '\nGoogle Earth Engine Authorization:\n'
        'If the web browser does not start automatically, '
        'start it manually and open the following URL:\n"{}"'.format(auth_url))

    token, ok = QInputDialog.getText(
        None, 'Authorization',
        'Google Earth Engine Python is not detected on this machine.\n'
        'This plugin uses Google Earth Engine Python API and requires users \n'
        'to be authorized, please follow the instructions in the opened web page\n'
        'and paste the resulting auth token here.\n\n'
        'If the web page does not open automatically, visit the followin link manually:\n\n'
        'URL: ' + tiny_url(auth_url))

    if ok and token:
        ee.oauth._obtain_and_write_token(token.strip())
 def createRepo(self):
     name, ok = QInputDialog.getText(self, 'Create repository',
                                     'Enter the repository name:')
     if ok:
         group = self.comboEndpoint.currentText()
         url = repository.repoEndpoints[group]
         try:
             repo = execute(lambda: createRepoAtUrl(url, group, name))
         except GeoGigException as e:
             config.iface.messageBar().pushMessage(
                 "Error", str(e), level=QgsMessageBar.CRITICAL, duration=5)
             return
         item = RepoItem(self, self.repoTree, repo)
         addRepo(repo)
         self.repoTree.addTopLevelItem(item)
         config.iface.messageBar().pushMessage(
             "Create repository",
             "Repository correctly created",
             level=QgsMessageBar.INFO,
             duration=5)
示例#20
0
 def editLayerName(self, index):
     item = index.data(role=Qt.UserRole)
     name, status = QInputDialog.getText(self, self.tr('Change name'),
         self.tr('Enter new layer name for %s') % item.name,
         text = item.name)
     if status and name != item.name:
         result = self.editLayerMetadata(item, {'name':name})
         if result['layer']['name'] == name:
             self.iface.messageBar().pushMessage('DIVI',
                 self.tr('Name of layer %s was changed to %s.') % (item.name, name),
                 duration = 3
             )
             item.name = name
             index.model().dataChanged.emit(index, index)
         else:
             self.iface.messageBar().pushMessage('DIVI',
                 self.tr('Error occured while changing name.'),
                 Qgis.Critical,
                 duration = 3
             )
示例#21
0
 def duplicate_maptheme(self):
     theme = self.dockwidget.PresetComboBox.currentText()
     quest = QInputDialog.getText(None,
                                  self.tr(u'Duplicate theme'),
                                  self.tr(u'Copy theme ')+theme+self.tr(u' to theme '),
                                  0,
                                  theme
                                  )
     root = QgsProject.instance().layerTreeRoot()
     model = iface.layerTreeView().layerTreeModel()
     name, ok = quest
     if ok and name != "":
         rec = QgsProject.instance().mapThemeCollection().createThemeFromCurrentState(root, model)
         QgsProject.instance().mapThemeCollection().insert(name, rec)
         self.set_combo_text(name)
         self.populate()
         self.theme_changed()
         return
     else:
         return
示例#22
0
 def newProject(self):
     """Call QGIS actions to create and name a new project."""
     settings = QSettings()
     if settings.contains('/QSWATPlus/LastInputPath'):
         path = settings.value('/QSWATPlus/LastInputPath')
     else:
         path = ''
     title = 'Select parent directory'
     parentDir = QFileDialog.getExistingDirectory(None, title, path)
     if parentDir is not None and os.path.isdir(parentDir):
         projName, ok = QInputDialog.getText(None, 'Project name', 'Please enter the project name, starting with a letter:')
         if not ok:
             return
         if not projName[0].isalpha():
             QSWATUtils.error('Project name must start with a letter', False)
             return
         projDir = QSWATUtils.join(parentDir, projName)
         if os.path.exists(projDir):
             response = QSWATUtils.question('Project directory {0} already exists.  Do you wish to delete it?'.format(projDir), False, False)
             if response != QMessageBox.Yes:
                 return
             shutil.rmtree(projDir, True)
         try: 
             os.mkdir(projDir)
         except Exception:
             QSWATUtils.exceptionError('Failed to create project directory {0}'.format(projDir), False)
             return
         self._iface.newProject()
         projFile = QSWATUtils.join(projDir, projName + '.qgs')
         proj = QgsProject.instance()
         proj.setFileName(projFile)
         QSWATUtils.loginfo('Project file is {0}'.format(projFile))
         self._iface.actionSaveProject().trigger()
         # allow time for project to be created
         time.sleep(2)
         self.initButtons()
         settings.setValue('/QSWATPlus/LastInputPath', str(projDir))
         self._odlg.raise_()
         self.setupProject(proj, False)
         self._gv.writeProjectConfig(0, 0)
示例#23
0
 def __init__(self, question="YesNo", msg = '', dialogtitle='User input needed', parent=None):
     self.result = ''
     if question == 'YesNo':         #  Yes/No dialog
         reply = QMessageBox.information(parent, dialogtitle, msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
         if reply==QMessageBox.Yes:
             self.result = 1 #1 = "yes"
         else:
             self.result = 0  #0="no"
     elif question == 'AllSelected': # All or Selected Dialog
         btnAll = QPushButton("All")   # = "0"
         btnSelected = QPushButton("Selected")     # = "1"
         #btnAll.clicked.connect(lambda x: self.DoForAll())
         #btnSelected.clicked.connect(lambda x: self.DoForSelected())
         msgBox = QMessageBox(parent)
         msgBox.setText(msg)
         msgBox.setWindowTitle(dialogtitle)
         #msgBox.setWindowModality(Qt.ApplicationModal)
         msgBox.addButton(btnAll, QMessageBox.ActionRole)
         msgBox.addButton(btnSelected, QMessageBox.ActionRole)
         msgBox.addButton(QMessageBox.Cancel)
         reply = msgBox.exec_()
         self.result = reply  # ALL=0, SELECTED=1
     elif question == 'DateShift':
         supported_units = ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks']
         while True:
             answer = str(QInputDialog.getText(None, "User input needed", "Give needed adjustment of date/time for the data.\nSupported format: +- X <resolution>\nEx: 1 hours, -1 hours, -1 days\nSupported units:\n%s"%', '.join(supported_units), QLineEdit.Normal, '0 hours')[0])
             if not answer:
                 self.result = 'cancel'
                 break
             else:
                 adjustment_unit = answer.split()
                 if len(adjustment_unit) == 2:
                     if adjustment_unit[1] in supported_units:
                         self.result = adjustment_unit
                         break
                     else:
                         pop_up_info("Failure:\nOnly support resolutions\n%s"%', '.join(supported_units))
                 else:
                     pop_up_info("Failure:\nMust write time resolution also.\n")
示例#24
0
    def edit_row(self):
        """ Edit the selected row in the table. """
        selection = self.table.selectedIndexes()

        if len(selection) <= 0:
            return

        row = selection[0].row()
        item = self.table.item(row, 0)
        url = item.data(Qt.UserRole)

        server_url, result = QInputDialog.getText(self.parent,
                                                  tr("Update Lizmap Server"),
                                                  tr("URL"),
                                                  QLineEdit.Normal,
                                                  text=url)
        if not result:
            return

        self._edit_row(row, server_url)
        self.save_table()
        self.check_display_warning_no_server()
示例#25
0
    def connect(self, selected, parent=None):
        settings = QSettings()
        settings.beginGroup(u"/%s/connections/%s" %
                            (self.getSettingsKey(), selected))

        if not settings.contains("database"):  # non-existent entry?
            raise DbError('there is no defined database connection "%s".' %
                          selected)

        get_value_str = lambda x: str(
            settings.value(x)
            if Utils.isSIPv2() else settings.value(x).toString())
        service, host, port, database, username, password = list(
            map(get_value_str, [
                "service", "host", "port", "database", "username", "password"
            ]))

        # qgis1.5 use 'savePassword' instead of 'save' setting
        isSave = settings.value("save") if Utils.isSIPv2() else settings.value(
            "save").toBool()
        isSavePassword = settings.value("savePassword") if Utils.isSIPv2(
        ) else settings.value("savePassword").toBool()
        if not (isSave or isSavePassword):
            (password, ok) = QInputDialog.getText(
                parent, "Enter password",
                'Enter password for connection "%s":' % selected,
                QLineEdit.Password)
            if not ok: return

        settings.endGroup()

        uri = QgsDataSourceUri()
        if service:
            uri.setConnection(service, database, username, password)
        else:
            uri.setConnection(host, port, database, username, password)

        return Connection(uri)
示例#26
0
    def createSchemaActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(
                    item,
                (DBPlugin, Schema, Table)) or item.database() is None:
                parent.infoBar.pushMessage(
                    QApplication.translate(
                        "DBManagerPlugin",
                        "No database selected or you are not connected to it."
                    ), Qgis.Info, parent.iface.messageTimeout())
                return
            (schema, ok) = QInputDialog.getText(
                parent, QApplication.translate("DBManagerPlugin",
                                               "New schema"),
                QApplication.translate("DBManagerPlugin",
                                       "Enter new schema name"))
            if not ok:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        self.createSchema(schema)
示例#27
0
    def on_pushButton_export_pressed(self):

        self.delete()
        if platform.system() == "Windows":
            b = QgsApplication.qgisSettingsDirPath().replace("/", "\\")

            cmd = os.path.join(os.sep, b, 'python', 'plugins',
                               'totalopenstationToQgis', 'scripts',
                               'totalopenstation-cli-parser.py')
            cmd2 = ' -i ' + str(
                self.lineEdit_input.text()) + ' ' + '-o ' + str(
                    self.lineEdit_output.text(
                    )) + ' ' + '-f' + ' ' + self.comboBox_format.currentText(
                    ) + ' ' + '-t' + ' ' + self.comboBox_format2.currentText(
                    ) + ' ' + '--overwrite'
            try:  #os.system("start cmd /k" + ' python ' +cmd+' '+cmd2)
                p = subprocess.check_call([
                    'python', cmd, '-i',
                    str(self.lineEdit_input.text()), '-o',
                    str(self.lineEdit_output.text()), '-f',
                    self.comboBox_format.currentText(), '-t',
                    self.comboBox_format2.currentText(), '--overwrite'
                ],
                                          shell=True)

                if self.comboBox_format2.currentIndex() == 0:

                    self.convert_csv()
                    uri = "file:///" + str(
                        self.lineEdit_output.text()
                    ) + "?type=csv&xField=x&yField=y&spatialIndex=yes&subsetIndex=yes&watchFile=no"
                    layer = QgsVectorLayer(
                        uri, "totalopenstation Pyarchinit Quote",
                        "delimitedtext")

                    layer.isValid()

                    QgsProject.instance().addMapLayer(layer)

                    QMessageBox.warning(self, 'Total Open Station',
                                        'data loaded into panel Layer',
                                        QMessageBox.Ok)

                    self.loadCsv(str(self.lineEdit_output.text()))
                    '''copy and past from totalstation to pyarchinit'''
                    sourceLYR = QgsProject.instance().mapLayersByName(
                        'totalopenstation Pyarchinit Quote')[0]
                    destLYR = QgsProject.instance().mapLayersByName(
                        'Quote US disegno')[0]
                    #Dialog Box for input "name sito archeologico" to select it...
                    ID_Sito = QInputDialog.getText(
                        None, 'Sito', 'Input Nome del sito archeologico')
                    Sito = str(ID_Sito[0])
                    ID_M = QInputDialog.getText(
                        None, 'Unità di misura',
                        'Input tipo di unità di misura\n (ex: metri)')
                    Misura = str(ID_M[0])
                    ID_Disegnatore = QInputDialog.getText(
                        None, 'Disegnatore', 'Input Nome del Disegnatore')
                    Disegnatore = str(ID_Disegnatore[0])
                    features = []
                    if self.checkBox_coord.isChecked():
                        # ID_X = QInputDialog.getText(None, 'X', 'Input coord X')
                        # x = float(ID_X[0])
                        # ID_Y = QInputDialog.getText(None, 'Y', 'Input Coord Y')
                        # y = float(ID_Y[0])
                        ID_Z = QInputDialog.getText(None, 'Z',
                                                    'Input Elevation')
                        q = float(ID_Z[0])

                        # expression1 = QgsExpression('x($geometry)+{}'.format(x))
                        # expression2 = QgsExpression('y($geometry)+{}'.format(y))
                        # context = QgsExpressionContext()
                        # scope = QgsExpressionContextScope()
                        # context.appendScope(scope)

                        for feature in sourceLYR.getFeatures():
                            # scope.setFeature(feature)
                            # a = expression1.evaluate(context)
                            # b = expression2.evaluate(context)
                            # if a and b:
                            features.append(feature)
                            feature.setAttribute('sito_q', Sito)
                            feature.setAttribute('unita_misu_q', Misura)
                            feature.setAttribute('x',
                                                 str(date.today().isoformat()))
                            feature.setAttribute('y', Disegnatore)
                            attr_Q = feature.attributes()[5]
                            p = q + float(attr_Q)

                            feature.setAttribute('quota_q', p)

                            # geom = feature.geometry()
                            # geom.get().setX(a)
                            # geom.get().setY(b)

                            # feature.setGeometry(geom)
                            sourceLYR.updateFeature(feature)
                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()
                    else:
                        for feature in sourceLYR.getFeatures():

                            features.append(feature)
                            feature.setAttribute('sito_q', Sito)
                            feature.setAttribute('unita_misu_q', Misura)
                            feature.setAttribute('x',
                                                 str(date.today().isoformat()))
                            feature.setAttribute('y', Disegnatore)

                            sourceLYR.updateFeature(feature)
                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    QgsProject.instance().removeMapLayer(sourceLYR)
                    ###########finish############################################

                elif self.comboBox_format2.currentIndex() == 1:

                    uri = "file:///" + str(
                        self.lineEdit_output.text()
                    ) + "?type=csv&xField=x&yField=y&spatialIndex=yes&subsetIndex=yes&watchFile=no"
                    layer = QgsVectorLayer(
                        uri, "totalopenstation Pyarchinit riferimento",
                        "delimitedtext")

                    layer.isValid()

                    QgsProject.instance().addMapLayer(layer)

                    QMessageBox.warning(self, 'Total Open Station',
                                        'data loaded into panel Layer',
                                        QMessageBox.Ok)

                    self.loadCsv(str(self.lineEdit_output.text()))
                    '''copy and past from totalstation to pyarchinit'''
                    sourceLYR = QgsProject.instance().mapLayersByName(
                        'totalopenstation Pyarchinit riferimento')[0]
                    destLYR = QgsProject.instance().mapLayersByName(
                        'Punti di riferimento')[0]

                    #Dialog Box for input "name sito archeologico" to select it...
                    ID_Sito = QInputDialog.getText(
                        None, 'Sito', 'Input Nome del sito archeologico')
                    Sito = str(ID_Sito[0])
                    features = []
                    if self.checkBox_coord.isChecked():
                        # ID_X = QInputDialog.getText(None, 'X', 'Input coord X')
                        # x = float(ID_X[0])
                        # ID_Y = QInputDialog.getText(None, 'Y', 'Input Coord Y')
                        # y = float(ID_Y[0])
                        ID_Z = QInputDialog.getText(None, 'Z',
                                                    'Input Elevation')
                        q = float(ID_Z[0])

                        # expression1 = QgsExpression('x($geometry)+{}'.format(x))
                        # expression2 = QgsExpression('y($geometry)+{}'.format(y))
                        # context = QgsExpressionContext()
                        # scope = QgsExpressionContextScope()
                        # context.appendScope(scope)

                        for feature in sourceLYR.getFeatures():
                            # scope.setFeature(feature)
                            # a = expression1.evaluate(context)
                            # b = expression2.evaluate(context)
                            # if a and b:
                            features.append(feature)

                            feature.setAttribute('sito', Sito)
                            attr_Q = feature.attributes()[4]
                            p = q + float(attr_Q)

                            feature.setAttribute('quota', p)

                            # geom = feature.geometry()
                            # geom.get().setX(a)
                            # geom.get().setY(b)

                            # feature.setGeometry(geom)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    else:

                        features = []
                        for feature in sourceLYR.getFeatures():
                            features.append(feature)
                            feature.setAttribute('sito', Sito)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    QgsProject.instance().removeMapLayer(sourceLYR)
                    ###########finish############################################

                elif self.comboBox_format2.currentIndex() == 2:

                    uri = "file:///" + str(
                        self.lineEdit_output.text()
                    ) + "?type=csv&xField=x&yField=y&spatialIndex=yes&subsetIndex=yes&watchFile=no"
                    layer = QgsVectorLayer(
                        uri, "totalopenstation Pyarchinit Sample",
                        "delimitedtext")

                    layer.isValid()

                    QgsProject.instance().addMapLayer(layer)

                    QMessageBox.warning(self, 'Total Open Station',
                                        'data loaded into panel Layer',
                                        QMessageBox.Ok)

                    self.loadCsv(str(self.lineEdit_output.text()))
                    '''copy and past from totalstation to pyarchinit'''
                    sourceLYR = QgsProject.instance().mapLayersByName(
                        'totalopenstation Pyarchinit Sample')[0]
                    destLYR = QgsProject.instance().mapLayersByName(
                        'Punti di campionatura')[0]
                    # Dialog Box for input "name sito archeologico" to select it...
                    ID_Sito = QInputDialog.getText(
                        None, 'Sito', 'Input Nome del sito archeologico')
                    Sito = str(ID_Sito[0])
                    # a=[]
                    if self.checkBox_coord.isChecked():
                        # ID_X = QInputDialog.getText(None, 'X', 'Input coord X')
                        # x = float(ID_X[0])
                        # ID_Y = QInputDialog.getText(None, 'Y', 'Input Coord Y')
                        # y = float(ID_Y[0])

                        features = []
                        # expression1 = QgsExpression('x($geometry)+{}'.format(x))
                        # expression2 = QgsExpression('y($geometry)+{}'.format(y))
                        # context = QgsExpressionContext()
                        # scope = QgsExpressionContextScope()
                        # context.appendScope(scope)

                        for feature in sourceLYR.getFeatures():
                            # scope.setFeature(feature)
                            # a = expression1.evaluate(context)
                            # b = expression2.evaluate(context)
                            # if a and b:
                            features.append(feature)

                            feature.setAttribute('sito', Sito)
                            # geom = feature.geometry()
                            # geom.get().setX(a)
                            # geom.get().setY(b)

                            # feature.setGeometry(geom)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    else:

                        features = []
                        for feature in sourceLYR.getFeatures():
                            features.append(feature)
                            feature.setAttribute('sito', Sito)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    QgsProject.instance().removeMapLayer(sourceLYR)
                    # ###########finish############################################

                else:

                    pass

            except Exception as e:

                QMessageBox.warning(self, 'Total Open Station',
                                    "Error:\n" + str(e), QMessageBox.Ok)
        else:
            try:  # os.system("start cmd /k" + ' python ' +cmd+' '+cmd2)
                p = subprocess.check_call([
                    'python', cmd, '-i',
                    str(self.lineEdit_input.text()), '-o',
                    str(self.lineEdit_output.text()), '-f',
                    self.comboBox_format.currentText(), '-t',
                    self.comboBox_format2.currentText(), '--overwrite'
                ],
                                          shell=True)

                if self.comboBox_format2.currentIndex() == 0:

                    self.convert_csv()
                    uri = "file:///" + str(
                        self.lineEdit_output.text()
                    ) + "?type=csv&xField=x&yField=y&spatialIndex=yes&subsetIndex=yes&watchFile=no"
                    layer = QgsVectorLayer(
                        uri, "totalopenstation Pyarchinit Quote",
                        "delimitedtext")

                    layer.isValid()

                    QgsProject.instance().addMapLayer(layer)

                    QMessageBox.warning(self, 'Total Open Station',
                                        'data loaded into panel Layer',
                                        QMessageBox.Ok)

                    self.loadCsv(str(self.lineEdit_output.text()))
                    '''copy and past from totalstation to pyarchinit'''
                    sourceLYR = QgsProject.instance().mapLayersByName(
                        'totalopenstation Pyarchinit Quote')[0]
                    destLYR = QgsProject.instance().mapLayersByName(
                        'Quote US disegno')[0]
                    # Dialog Box for input "name sito archeologico" to select it...
                    ID_Sito = QInputDialog.getText(
                        None, 'Sito', 'Input Nome del sito archeologico')
                    Sito = str(ID_Sito[0])
                    ID_M = QInputDialog.getText(
                        None, 'Unità di misura',
                        'Input tipo di unità di misura\n (ex: metri)')
                    Misura = str(ID_M[0])
                    ID_Disegnatore = QInputDialog.getText(
                        None, 'Disegnatore', 'Input Nome del Disegnatore')
                    Disegnatore = str(ID_Disegnatore[0])

                    if self.checkBox_coord.isChecked():
                        # ID_X = QInputDialog.getText(None, 'X', 'Input coord X')
                        # x = float(ID_X[0])
                        # ID_Y = QInputDialog.getText(None, 'Y', 'Input Coord Y')
                        # y = float(ID_Y[0])
                        ID_Z = QInputDialog.getText(None, 'Z',
                                                    'Input Elevation')
                        q = float(ID_Z[0])

                        features = []
                        # expression1 = QgsExpression('x($geometry)+{}'.format(x))
                        # expression2 = QgsExpression('y($geometry)+{}'.format(y))
                        # context = QgsExpressionContext()
                        # scope = QgsExpressionContextScope()
                        # context.appendScope(scope)

                        for feature in sourceLYR.getFeatures():
                            # scope.setFeature(feature)
                            # a = expression1.evaluate(context)
                            # b = expression2.evaluate(context)
                            # if a and b:
                            features.append(feature)
                            feature.setAttribute('sito_q', Sito)
                            feature.setAttribute('unita_misu_q', Misura)
                            feature.setAttribute('x',
                                                 str(date.today().isoformat()))
                            feature.setAttribute('y', Disegnatore)
                            attr_Q = feature.attributes()[5]
                            p = q + float(attr_Q)

                            feature.setAttribute('quota_q', p)

                            # geom = feature.geometry()
                            # geom.get().setX(a)
                            # geom.get().setY(b)

                            # feature.setGeometry(geom)
                            sourceLYR.updateFeature(feature)
                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()
                    else:
                        for feature in sourceLYR.getFeatures():
                            features.append(feature)
                            feature.setAttribute('sito_q', Sito)
                            feature.setAttribute('unita_misu_q', Misura)
                            feature.setAttribute('x',
                                                 str(date.today().isoformat()))
                            feature.setAttribute('y', Disegnatore)

                            sourceLYR.updateFeature(feature)
                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    QgsProject.instance().removeMapLayer(sourceLYR)
                    ###########finish############################################

                elif self.comboBox_format2.currentIndex() == 1:

                    uri = "file:///" + str(
                        self.lineEdit_output.text()
                    ) + "?type=csv&xField=x&yField=y&spatialIndex=yes&subsetIndex=yes&watchFile=no"
                    layer = QgsVectorLayer(
                        uri, "totalopenstation Pyarchinit riferimento",
                        "delimitedtext")

                    layer.isValid()

                    QgsProject.instance().addMapLayer(layer)

                    QMessageBox.warning(self, 'Total Open Station',
                                        'data loaded into panel Layer',
                                        QMessageBox.Ok)

                    self.loadCsv(str(self.lineEdit_output.text()))
                    '''copy and past from totalstation to pyarchinit'''
                    sourceLYR = QgsProject.instance().mapLayersByName(
                        'totalopenstation Pyarchinit riferimento')[0]
                    destLYR = QgsProject.instance().mapLayersByName(
                        'Punti di riferimento')[0]

                    # Dialog Box for input "name sito archeologico" to select it...
                    ID_Sito = QInputDialog.getText(
                        None, 'Sito', 'Input Nome del sito archeologico')
                    Sito = str(ID_Sito[0])
                    # a=[]
                    if self.checkBox_coord.isChecked():
                        # ID_X = QInputDialog.getText(None, 'X', 'Input coord X')
                        # x = float(ID_X[0])
                        # ID_Y = QInputDialog.getText(None, 'Y', 'Input Coord Y')
                        # y = float(ID_Y[0])
                        ID_Z = QInputDialog.getText(None, 'Z',
                                                    'Input Elevation')
                        q = float(ID_Z[0])

                        # features = []
                        # expression1 = QgsExpression('x($geometry)+{}'.format(x))
                        # expression2 = QgsExpression('y($geometry)+{}'.format(y))
                        # context = QgsExpressionContext()
                        # scope = QgsExpressionContextScope()
                        # context.appendScope(scope)

                        for feature in sourceLYR.getFeatures():
                            # scope.setFeature(feature)
                            # a = expression1.evaluate(context)
                            # b = expression2.evaluate(context)
                            # if a and b:
                            features.append(feature)

                            feature.setAttribute('sito', Sito)
                            attr_Q = feature.attributes()[4]
                            p = q + float(attr_Q)

                            feature.setAttribute('quota', p)

                            # geom = feature.geometry()
                            # geom.get().setX(a)
                            # geom.get().setY(b)

                            # feature.setGeometry(geom)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    else:

                        features = []
                        for feature in sourceLYR.getFeatures():
                            features.append(feature)
                            feature.setAttribute('sito', Sito)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    QgsProject.instance().removeMapLayer(sourceLYR)
                    ###########finish############################################

                elif self.comboBox_format2.currentIndex() == 2:

                    uri = "file:///" + str(
                        self.lineEdit_output.text()
                    ) + "?type=csv&xField=x&yField=y&spatialIndex=yes&subsetIndex=yes&watchFile=no"
                    layer = QgsVectorLayer(
                        uri, "totalopenstation Pyarchinit Sample",
                        "delimitedtext")

                    layer.isValid()

                    QgsProject.instance().addMapLayer(layer)

                    QMessageBox.warning(self, 'Total Open Station',
                                        'data loaded into panel Layer',
                                        QMessageBox.Ok)

                    self.loadCsv(str(self.lineEdit_output.text()))
                    '''copy and past from totalstation to pyarchinit'''
                    sourceLYR = QgsProject.instance().mapLayersByName(
                        'totalopenstation Pyarchinit Sample')[0]
                    destLYR = QgsProject.instance().mapLayersByName(
                        'Punti di campionatura')[0]
                    # Dialog Box for input "name sito archeologico" to select it...
                    ID_Sito = QInputDialog.getText(
                        None, 'Sito', 'Input Nome del sito archeologico')
                    Sito = str(ID_Sito[0])
                    # a=[]
                    if self.checkBox_coord.isChecked():
                        # ID_X = QInputDialog.getText(None, 'X', 'Input coord X')
                        # x = float(ID_X[0])
                        # ID_Y = QInputDialog.getText(None, 'Y', 'Input Coord Y')
                        # y = float(ID_Y[0])

                        features = []
                        # expression1 = QgsExpression('x($geometry)+{}'.format(x))
                        # expression2 = QgsExpression('y($geometry)+{}'.format(y))
                        # context = QgsExpressionContext()
                        # scope = QgsExpressionContextScope()
                        # context.appendScope(scope)

                        for feature in sourceLYR.getFeatures():
                            # scope.setFeature(feature)
                            # a = expression1.evaluate(context)
                            # b = expression2.evaluate(context)
                            # if a and b:
                            features.append(feature)

                            feature.setAttribute('sito', Sito)
                            # geom = feature.geometry()
                            # geom.get().setX(a)
                            # geom.get().setY(b)

                            # feature.setGeometry(geom)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    else:

                        features = []
                        for feature in sourceLYR.getFeatures():
                            features.append(feature)
                            feature.setAttribute('sito', Sito)
                            sourceLYR.updateFeature(feature)

                        destLYR.startEditing()
                        data_provider = destLYR.dataProvider()
                        data_provider.addFeatures(features)
                        iface.mapCanvas().zoomToSelected()
                        destLYR.commitChanges()

                    QgsProject.instance().removeMapLayer(sourceLYR)
                    ###########finish############################################

                else:

                    pass

            except Exception as e:

                QMessageBox.warning(self, 'Total Open Station',
                                    "Error:\n" + str(e), QMessageBox.Ok)
示例#28
0
 def createTag(self, item):
     tagname, ok = QInputDialog.getText(self, 'Tag name',
                                        'Enter the tag name:')
     if ok:
         self.repo.createtag(item.commit.commitid, tagname)
         self.updateTags(item.commit.commitid, tagname)
示例#29
0
    def saveTemplate(self):
        """
        Creates and saves a new document template.
        """
        # Validate if the user has specified the data source

        if not LayoutUtils.get_stdm_data_source_for_layout(self.composition()):
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper", "Error"),
                QApplication.translate(
                    "ComposerWrapper", "Please specify the "
                    "data source name for the document composition."))
            return

        # Assert if the referenced table name has been set
        if not LayoutUtils.get_stdm_referenced_table_for_layout(
                self.composition()):
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper", "Error"),
                QApplication.translate(
                    "ComposerWrapper", "Please specify the "
                    "referenced table name for the selected data source."))
            return

        # If it is a new unsaved document template then prompt for the document name.
        #template_path = self.composition().customProperty('variable_template_path', None)
        template_path = self.variable_template_path

        if template_path is None:
            docName, ok = QInputDialog.getText(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper", "Template Name"),
                QApplication.translate("ComposerWrapper",
                                       "Please enter the template name below"),
            )

            if not ok:
                return

            if ok and not docName:
                QMessageBox.critical(
                    self.mainWindow(),
                    QApplication.translate("ComposerWrapper", "Error"),
                    QApplication.translate("ComposerWrapper",
                                           "Please enter a template name!"))
                self.saveTemplate()

            if ok and docName:
                templateDir = self._composerTemplatesPath()

                if templateDir is None:
                    QMessageBox.critical(
                        self.mainWindow(),
                        QApplication.translate("ComposerWrapper", "Error"),
                        QApplication.translate(
                            "ComposerWrapper",
                            "Directory for document templates cannot not be found."
                        ))

                    return

                absPath = templateDir + "/" + docName + ".sdt"

                # Check if there is an existing document with the same name
                caseInsenDic = CaseInsensitiveDict(documentTemplates())
                if docName in caseInsenDic:
                    result = QMessageBox.warning(
                        self.mainWindow(),
                        QApplication.translate("ComposerWrapper",
                                               "Existing Template"),
                        "'{0}' {1}.\nDo you want to replace the "
                        "existing template?".format(
                            docName,
                            QApplication.translate("ComposerWrapper",
                                                   "already exists")),
                        QMessageBox.Yes | QMessageBox.No)

                    if result != QMessageBox.Yes:
                        return
                    else:
                        # Delete the existing template
                        delFile = QFile(absPath)
                        remove_status = delFile.remove()
                        if not remove_status:
                            QMessageBox.critical(
                                self.mainWindow(),
                                QApplication.translate("ComposerWrapper",
                                                       "Delete Error"),
                                "'{0}' {1}.".format(
                                    docName,
                                    QApplication.translate(
                                        "ComposerWrapper",
                                        "template could not be removed by the system,"
                                        " please remove it manually from the document templates directory."
                                    )))
                            return

                docFile = QFile(absPath)
                template_path = absPath
        else:
            docFile = QFile(template_path)

            # else:
            # return

        docFileInfo = QFileInfo(docFile)

        if not docFile.open(QIODevice.WriteOnly):
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper",
                                       "Save Operation Error"),
                "{0}\n{1}".format(
                    QApplication.translate("ComposerWrapper",
                                           "Could not save template file."),
                    docFile.errorString()))

            return

        templateDoc = QDomDocument()
        template_name = docFileInfo.completeBaseName()

        # Catch exception raised when writing items' elements
        try:
            self._writeXML(templateDoc, template_name)
        except DummyException as exc:
            msg = str(exc)
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper", "Save Error"), msg)
            docFile.close()
            docFile.remove()

            return

        if docFile.write(templateDoc.toByteArray()) == -1:
            QMessageBox.critical(
                self.mainWindow(),
                QApplication.translate("ComposerWrapper", "Save Error"),
                QApplication.translate("ComposerWrapper",
                                       "Could not save template file."))

            return

        else:
            self.mainWindow().setWindowTitle(template_name)

        self.composition().setCustomProperty('variable_template_path',
                                             template_path)

        docFile.close()
 def inputDialog(self, firstSegment, secondSegment):
     text, ok = QInputDialog.getText(
         self.dlg, 'Input Dialog',
         '(1) :' + str(firstSegment) + ' \n(2) :' + str(secondSegment))
     if ok:
         return text
示例#31
0
 def createBranch(self, ref):
     text, ok = QInputDialog.getText(self, 'Title',
                                     'Enter the name for the new branch:')
     if ok:
         self.repo.createbranch(ref, text)
         repoWatcher.repoChanged.emit(self.repo)
示例#32
0
 def renameWindow(self):
     title, ok = QInputDialog.getText(self, self.tr('Rename window'), self.tr('Enter a new title:'))  
     if ok:
         self.setWindowTitle(title)
示例#33
0
 def createBranch(self):
     text, ok = QInputDialog.getText(self.tree, 'Create New Branch',
                                           'Enter the name for the new branch:')
     if ok:
         self.repo.createbranch(self.branch, text.replace(" ", "_"))
         repoWatcher.repoChanged.emit(self.repo)
示例#34
0
 def changeHeader(self, index):
     txt, ok = QInputDialog.getText(self, self.tr("Enter column name"),
                                    self.tr("Column name"))
     if ok:
         self.tblView.model().setHeaderData(index, Qt.Horizontal, txt)
示例#35
0
 def changeHeader(self, index):
     txt, ok = QInputDialog.getText(self, self.tr("Enter column name"), self.tr("Column name"))
     if ok:
         self.tblView.model().setHeaderData(index, Qt.Horizontal, txt)
 def createTag(self, item):
     tagname, ok = QInputDialog.getText(self, 'Tag name',
                                           'Enter the tag name:')
     if ok:
         self.repo.createtag(item.commit.commitid, tagname)
         self.updateTags(item.commit.commitid, tagname)
示例#37
0
 def createFolder(self):
     name, _ = QInputDialog.getText(self, "Save Search",
                                    "Enter folder name")
     if name and name not in self._folder_names:
         self._folder_names.append(name)
         self.populate_folders()
示例#38
0
    def moveVertex(self, result):
        marker = result[1]
        snappingResult = result[0]

        QMessageBox.critical(self.iface.mainWindow(), "Move vertex error",
                             "Move vertex error", QMessageBox.Ok)

        # The vertex that is found by the tool:
        vertexCoords = snappingResult.point(
        )  # vertexCoord are given in crs of the project
        vertexNr = snappingResult.vertexIndex()
        featureId = snappingResult.featureId()
        layer = snappingResult.layer()
        try:
            layerSrs = layer.srs()  # find out the srs of the layer
        except AttributeError:  # API version >1.8
            layerSrs = layer.crs()  # find out the srs of the layer

        # Give a dialog with the current coords and ask for the new ones
        (input, ok) = QInputDialog.getText(
            self.iface.mainWindow(), "Move Vertex Feature",
            "Enter New Coordinates as 'xcoord, ycoord'", QLineEdit.Normal,
            str(vertexCoords.x()) + "," + str(vertexCoords.y()))
        if not ok:
            # If we are aborting, we have to delete the marker
            self.canvas.scene().removeItem(marker)
            del marker
            return 0

        # Find out which is the current crs of the project
        projectSrsEntry = QgsProject.instance().readEntry(
            "SpatialRefSys", "/ProjectCRSProj4String")
        projectSrs = QgsCoordinateReferenceSystem()
        projectSrs.createFromProj4(projectSrsEntry[0])

        # Set up a coordinate transformation to transform the vertex coord into the srs of his layer
        transformer = QgsCoordinateTransform(projectSrs, layerSrs,
                                             QgsProject.instance())
        # transformedPoint = transformer.transform(input.split(",")[0].toDouble()[0],
        #                                          input.split(",")[1].toDouble()[0])
        transformedPoint = transformer.transform(float(input.split(",")[0]),
                                                 float(input.split(",")[1]))

        # If the transformation is successful, we move the vertex to his new place
        # else we inform the user that there is something wrong
        if (type(transformedPoint.x()).__name__ == 'double' and type(transformedPoint.y()).__name__ == 'double') or\
           (type(transformedPoint.x()).__name__ == 'float' and type(transformedPoint.y()).__name__ == 'float'):

            # If the undo/redo stack is available, we use it
            if self.undoAvailable:
                layer.beginEditCommand("Moved Vertex")
                # Now we move the vertex to the given coordinates
            layer.moveVertex(transformedPoint.x(), transformedPoint.y(),
                             featureId, vertexNr)
            # end of undo/redo stack (if available)
            if self.undoAvailable:
                layer.endEditCommand()
        else:
            QMessageBox.critical(
                self.iface.mainWindow(), "Error while transforming the vertex",
                "It's not possible to transform the coordinates you gave into the srs of this layer."
            )

        # Now refresh the map canvas
        self.canvas.refresh()

        # At last we have to delete the marker
        self.canvas.scene().removeItem(marker)
        del marker
示例#39
0
def get_password():
    """Return Linux user Password."""
    password, ok = QInputDialog.getText(
        None, "Enter Linux user password for install missing dependencies",
        "Password:", QLineEdit.Password)
    return password if ok else ''
示例#40
0
    def postProcess(self, results, feedback=None):
        if not feedback:
            feedback = Feedback()

        self.export_file = results.index_file
        file_count = max(len(results.files), 1)

        # generate a new temp_folder for next export
        self.temp_folder = self.newTempFolder(tempFolder())

        source_folder = results.folder

        if not self.host or not self.username or not self.port:
            return False

        # get password
        password = self.password
        if password is None:
            password, ok = QInputDialog.getText(
                None, 'Enter FTP password', 'Password', QLineEdit.Password)
            if not password or not ok:
                feedback.setFatalError('User cancelled')
                return False

        feedback.showFeedback(
            'Connecting to {} on port {}...'.format(self.host, self.port))

        ftp = ftplib.FTP()
        try:
            ftp.connect(self.host, self.port)
        except Exception:
            feedback.setFatalError('Could not connect to server!')
            return False

        feedback.showFeedback('Connected!')
        feedback.showFeedback('Logging in as {}...'.format(self.username))
        if feedback.cancelled():
            feedback.acceptCancel()
            return False

        try:
            ftp.login(self.username, password)
        except Exception:
            feedback.setFatalError("""Login failed for
                                      user {}!""".format(self.username))
            return False

        feedback.showFeedback('Logged in to {}'.format(self.host))

        def cwd_and_create(p):
            """
            recursively changes directory to an ftp target,
            creating new folders as required.
            """
            if not p:
                return
            try:
                ftp.cwd(p)
            except Exception:
                parent, base = os.path.split(p)
                cwd_and_create(parent)
                if base:
                    feedback.showFeedback('Creating {}'.format(base))
                    ftp.mkd(base)
                    ftp.cwd(base)

        cwd_and_create(self.remote_folder)

        feedback.uploaded_count = 0.0

        def uploadPath(path):
            if feedback.cancelled():
                feedback.acceptCancel()
                return False

            files = os.listdir(path)
            os.chdir(path)
            for f in files:
                if feedback.cancelled():
                    feedback.acceptCancel()
                    return False
                current_path = os.path.join(path, f)
                if os.path.isfile(current_path):
                    feedback.showFeedback('Uploading {}'.format(f))
                    fh = open(f, 'rb')
                    ftp.storbinary('STOR %s' % f, fh)
                    fh.close()
                    feedback.uploaded_count += 1
                    feedback.setProgress(
                        100 * feedback.uploaded_count / file_count)
                elif os.path.isdir(current_path):
                    feedback.showFeedback('Creating folder {}'.format(f))
                    try:
                        ftp.mkd(f)
                    except Exception:
                        pass
                    ftp.cwd(f)
                    if not uploadPath(current_path):
                        return False
            ftp.cwd('..')
            os.chdir('..')
            return True

        if not uploadPath(os.path.join('.', source_folder)):
            return False

        feedback.setCompleted('Upload complete!')
        ftp.close()
        return True
示例#41
0
    def __new_project(self):

        fil, __ = QFileDialog.getSaveFileName(
            None,
            u"New project name (no space, plain ascii)",
            QgsProject.instance().readEntry("albion", "last_dir", "")[0],
            "QGIS poject file (*.qgs)",
        )
        if not fil:
            return
        fil = fil if len(fil) > 4 and fil[-4:] == ".qgs" else fil + ".qgs"
        fil = fil.replace(" ", "_")
        if len(fil) != len(fil.encode()):
            self.__iface.messageBar().pushError(
                "Albion:", "project name may only contain asci character (no accent)"
            )
            return

        srid, ok = QInputDialog.getText(
            self.__iface.mainWindow(),
            "Project SRID",
            "Project SRID EPSG:",
            QLineEdit.Normal,
            "32632",
        )
        if not ok:
            return
        srid = int(srid)

        project_name = str(os.path.split(fil)[1][:-4])

        if Project.exists(project_name):
            if (
                QMessageBox.Yes
                != QMessageBox(
                    QMessageBox.Information,
                    "Delete existing DB",
                    "Database {} exits, do you want to delete it ?".format(
                        project_name
                    ),
                    QMessageBox.Yes | QMessageBox.No,
                ).exec_()
            ):
                self.__iface.messageBar().pushInfo("Albion:", "keeping existing database...")
            else:
                Project.delete(project_name)
                self.__iface.messageBar().pushInfo("Albion:", "creating project...")
                Project.create(project_name, srid)
        else:
            self.__iface.messageBar().pushInfo("Albion:", "creating project...")
            Project.create(project_name, srid)

        if os.path.exists(fil):
            os.remove(fil)

        # load template
        open(fil, "w").write(
            open(resource("template_project.qgs"))
            .read()
            .replace("template_project", project_name)
            .replace("32632", str(srid))
        )
        self.__iface.newProject()
        QgsProject.instance().setFileName(fil)
        QgsProject.instance().read()
        QgsProject.instance().writeEntry("albion", "project_name", project_name)
        QgsProject.instance().writeEntry("albion", "srid", srid)
        QgsProject.instance().write()
        self.__qgis__project__loaded()