Exemple #1
0
    def current_plugin(self):
        """
        Prepare the dockwidget for the select plugin
        """
        if self.ckbPro.isChecked():
            self.lblLang.show()
            self.mCmbLanguage.show()
        else:
            self.lblLang.hide()
            self.mCmbLanguage.hide()

        current_plugin = self.cmbPluginList.currentText()
        startpath = pluginDirectory(current_plugin)

        self.twGraphFile.clear()

        check_format = {
            ".qrc": self.ckbQrc.isChecked(),
            ".ui": self.ckbUi.isChecked(),
            ".png": self.ckbResources.isChecked(),
            ".jpg": self.ckbResources.isChecked(),
            ".pro": self.ckbPro.isChecked(),
            ".qm": self.ckbQm.isChecked(),
            ".ts": self.ckbTs.isChecked()
        }
        sorting = self.ckbFilter.isChecked()
        self.load_project_structure(startpath, self.twGraphFile, check_format,
                                    sorting)
Exemple #2
0
    def dlgpr_selectFileProjectTemplate(self):
        """Vorlage-Projektdatei auswählen"""

        self.setPathToTemplateDir = self.dlgpr.cb_setPathToTemplateDir.isChecked()
        if self.setPathToTemplateDir:
            self.templateDir = os.path.join(pluginDirectory('qkan'), u"database/templates")
        else:
            try:
                self.templateDir = os.path.dirname(self.database_QKan)
            except:
                logger.error('Programmfehler in tools.run_qgsadapt:\nPfad konnte nicht auf ' + \
                             'database_QKan gesetzt werden.\n database_QKan = {}'.format(
                               self.database_QKan))
                self.templateDir = ''

        filename = QFileDialog.getOpenFileName(self.dlgpr,
                                               "Vorlage für zu erstellende Projektdatei auswählen",
                                               self.templateDir,
                                               "*.qgs")
        if os.path.dirname(filename) != '':
            os.chdir(os.path.dirname(filename))
            self.dlgpr.tf_projectTemplate.setText(filename)
Exemple #3
0
    def __init__(self, parent, scope=None, xml_doc=None, md=None):
        super(MetadadoSNIMar, self).__init__(parent)
        if scope is None:
            self.scope = SCOPES.get_code_representation(md.hierarchy)
        else:
            self.scope = scope

        self.current_index = 0
        self.widgetStalker = {}
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)

        self.sidelist = QListWidget(self)
        self.sidelist.setMinimumWidth(150)
        self.sidelist.setMaximumWidth(150)
        self.sidelist.setWordWrap(True)
        self.sidelist.setTextElideMode(Qt.ElideNone)
        self.sidelist.setIconSize(QSize(25, 25))
        self.sidelist.clicked.connect(self.list_clicked)
        index = 0
        if self.scope == SCOPES.SERVICES:
            tabs = cons.TABLIST_SERVICES
        else:
            tabs = cons.TABLIST_CDG_SERIES

        for tab_element in tabs:
            bufWidget = QListWidgetItem(
                qgui.QIcon(':/resourcesFolder/icons/' + tab_element[1]),
                tab_element[0])
            self.widgetStalker[tab_element[2]] = {
                "widget": bufWidget,
                "missingFields": set(),
                "incompleteEntries": set()
            }
            bufWidget.setSizeHint(QSize(150, 50))
            if platform.system() != "Linux":
                font = QFont()
                font.setFamily(u"Segoe UI Symbol")
                bufWidget.setFont(font)

            self.sidelist.insertItem(index, bufWidget)
            index += 1
        self.widgetstack = QStackedWidget(self)

        # Setup metadata stuff
        self.xml_doc = xml_doc
        self.is_new_file = True if xml_doc is None else False
        self.md = md
        self.codelist = self.parent().codelists
        self.helps = self.parent().helps
        self.orgs = self.parent().orgs
        f = open(
            os.path.join(pluginDirectory('EditorMetadadosMarswInforbiomares'),
                         'resourcesFolder/stylesheet.qtcss'))
        self.sytlesheet = f.read()
        for btn in self.findChildren(QPushButton):
            btn.setStyleSheet(self.sytlesheet)
            btn.setFocusPolicy(Qt.NoFocus)
        self.reference_systems_list = self.parent().reference_systems
        tab_list = []

        # Setup snimarEditorController
        self.identification = snimarEditorController.IdentificationWidget(
            self, self.scope)
        tab_list.append(self.identification)
        if self.scope == SCOPES.SERVICES:
            self.operations = snimarEditorController.ServiceOperationsWidget(
                self)
            tab_list.append(self.operations)
        self.keywords = snimarEditorController.KeywordsWidget(self, self.scope)
        tab_list.append(self.keywords)
        self.geographicinfo = snimarEditorController.GeographicInfoWidget(
            self, self.scope)
        tab_list.append(self.geographicinfo)
        self.temporalinfo = snimarEditorController.TemporalInfoWidget(
            self, self.scope)
        tab_list.append(self.temporalinfo)
        self.quality = snimarEditorController.QualityWidget(self, self.scope)
        tab_list.append(self.quality)
        self.restrictions = snimarEditorController.RestrictionsWidget(
            self, self.scope)
        tab_list.append(self.restrictions)
        self.distribution = snimarEditorController.DistributionWidget(
            self, self.scope)
        tab_list.append(self.distribution)
        self.metadata = snimarEditorController.MetadataWidget(self)
        tab_list.append(self.metadata)

        self.setupUi()
        if not self.is_new_file:
            # Setup data
            self.identification.set_data(self.md)
            if self.scope == SCOPES.SERVICES:
                self.operations.set_data(md)
            self.temporalinfo.set_data(self.md)
            self.keywords.set_data(self.md)
            self.metadata.set_data(self.md)
            self.distribution.set_data(self.md)
            self.restrictions.set_data(self.md)
            self.quality.set_data(self.md)
            self.geographicinfo.set_data(self.md)
SNIMAR_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SNIMAR_THESAURUS_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'resourcesFolder/CodeLists/SnimarkeyWords')
SNIMAR_THESAURUS_META = os.path.join(SNIMAR_THESAURUS_DIR,
                                     'snimarThesaurus_meta.json')

# SNIMAR STUFF

SNIMAR_PROFILE_NAME = u'Perfil SNIMar'
SNIMAR_PROFILE_VERSION = u'v.0.9.3'

CODELIST_SERVER_URL = 'http://editor.snimar.pt/CODELISTS/'

RESOURCE_DIR = os.path.join(
    pluginDirectory('EditorMetadadosMarswInforbiomares'), 'resourcesFolder')
NAMESPACES = {
    'gml': 'http://www.opengis.net/gml/3.2',
    'gmx': 'http://www.isotc211.org/2005/gmx',
}
CODELIST_TAGS = [
    'MD_ScopeCode',
    'MD_CharacterSetCode',
    'MD_ProgressCode',
    'MD_MaintenanceFrequencyCode',
    'MD_SpatialRepresentationTypeCode',
    'MD_TopicCategoryCode',
]
TABLIST_SERVICES = [
    (u'Identificação', 'identification_icon.svg', u"identification"),
    (u'Operações (Serviços)', 'metadata_icon.svg', u'operations'),
    def __init__(self, parent, boundingbox):
        super(ExtentDialog, self).__init__(parent)
        self.setupUi(self)
        self.superParent = None
        temp = self.parent()
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        while self.superParent is None:
            if issubclass(type(temp),
                          geographicinformationPanel.Ui_geographicinfo):
                self.superParent = temp
            else:
                temp = temp.parent()
        for info in self.findChildren(qwidgets.QPushButton,
                                      qcore.QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)

        self.layers = []
        self.maxExt = None
        self.boundingbox = boundingbox
        self.outBB = False

        # Create MapCanvas
        self.canvas = gui.QgsMapCanvas(self)

        # Append to Dialog Layout
        self.toolBar = qwidgets.QToolBar()
        self.layout = qwidgets.QVBoxLayout(self.frame)
        self.layout.addWidget(self.toolBar)
        self.layout.addWidget(self.canvas)

        # Trigger on scaleChanged
        self.canvas.scaleChanged.connect(self.scaleChanged)
        # Trigger on renderStarting
        self.canvas.renderStarting.connect(self.renderStarting)

        # Create Map Tools
        actionFullExt = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/globe.svg'), "Mapa total",
            self)
        actionPan = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/pan.svg'), "Mover", self)
        actionZoomIn = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/zoom_in.svg'), "Aproximar",
            self)
        actionZoomOut = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/zoom_out.svg'), "Afastar",
            self)
        actionSelect = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/selection.svg'), 'Desenhar',
            self)
        actionFromLayer = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/layers.svg'),
            'Obter de camada', self)

        actionFullExt.setCheckable(False)
        actionPan.setCheckable(True)
        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionSelect.setCheckable(True)

        actionFullExt.triggered.connect(self.fullext)
        actionPan.triggered.connect(self.pan)
        actionZoomIn.triggered.connect(self.zoomIn)
        actionZoomOut.triggered.connect(self.zoomOut)
        actionSelect.triggered.connect(self.select)
        actionFromLayer.triggered.connect(self.chooseLayer)

        # Add to created ToolBar
        self.toolBar.addAction(actionFullExt)
        self.toolBar.addSeparator()
        self.toolBar.addAction(actionPan)
        self.toolBar.addAction(actionZoomIn)
        self.toolBar.addAction(actionZoomOut)
        self.toolBar.addAction(actionSelect)
        self.toolBar.addAction(actionFromLayer)

        self.toolFullExtent = gui.QgsMapToolPan(self.canvas)
        self.toolFullExtent.setAction(actionFullExt)
        self.toolPan = gui.QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = gui.QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = gui.QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolSelect = SelectionTool(self.canvas, self)
        self.resourcebox.setChecked(True)
        self.pan()

        lugin_path = utils.pluginDirectory('EditorMetadadosMarswInforbiomares')

        # Load Vector
        layerpath = os.path.join(plugin_path, "resourcesFolder/World.shp")
        llayer = core.QgsVectorLayer(layerpath, "WorldLayer", "ogr")

        # Set Layer Symbology
        props = {
            'color_border': '0,0,0,125',
            'style': 'no',
            'style_border': 'solid'
        }
        #s = core.QgsFillSymbolV2.createSimple(props)
        s = core.QgsFillSymbol.createSimple(props)
        #llayer.setRendererV2(core.QgsSingleSymbolRendererV2(s))
        llayer.setRenderer(core.QgsSingleSymbolRenderer(s))

        # Set CRS - necessary to load Raster - it assumes this default CRS
        s = qcore.QSettings()
        oldValidation = str(
            s.value("/Projections/defaultBehaviour", "useGlobal"))
        s.setValue("/Projections/defaultBehaviour", "useGlobal")

        # Load Raster
        fileName = os.path.join(plugin_path, "resourcesFolder/GMRT.tif")
        fileInfo = qcore.QFileInfo(fileName)
        baseName = fileInfo.baseName()
        layer = core.QgsRasterLayer(fileName, baseName)
        layer.setCrs(
            core.QgsCoordinateReferenceSystem(
                4326, core.QgsCoordinateReferenceSystem.EpsgCrsId))
        s.setValue("/Projections/defaultBehaviour", oldValidation)

        # Set Raster ColorRamp
        # layer.setDrawingStyle("SingleBandPseudoColor") # deprecated remove in 2.1.0 please
        vmin = -5683.08
        vmax = 2763.86
        vrange = vmax - vmin
        vadd = vrange // 2
        vint = vmin + vadd
        colDic = {
            'brown': '#90330a',
            'lightblue': '#d5f5f9',
            'blue': '#2099d4'
        }
        valueList = [vmin, vint, vmax]

        lst = [core.QgsColorRampShader.ColorRampItem(valueList[0], qgui.QColor(colDic['blue'])), \
               core.QgsColorRampShader.ColorRampItem(valueList[1],
                                                     qgui.QColor(colDic['lightblue'])), \
               core.QgsColorRampShader.ColorRampItem(valueList[2], qgui.QColor(colDic['brown']))]
        myRasterShader = core.QgsRasterShader()
        myColorRamp = core.QgsColorRampShader()
        myColorRamp.setColorRampItemList(lst)
        myColorRamp.setColorRampType(core.QgsColorRampShader.Interpolated)
        myRasterShader.setRasterShaderFunction(myColorRamp)
        myPseudoRenderer = core.QgsSingleBandPseudoColorRenderer(
            layer.dataProvider(), layer.type(), myRasterShader)
        layer.setRenderer(myPseudoRenderer)

        ## Add vector to map
        #core.QgsMapLayerRegistry.instance().addMapLayer(llayer, False)
        core.QgsProject.instance().addMapLayer(llayer, False)
        ## Add raster to map
        #core.QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        core.QgsProject.instance().addMapLayer(layer, False)

        ## Save Max Extent
        self.maxExt = core.QgsRectangle(-180., -90., 180., 90.)

        # ----------------------------------
        ## Set initial general extent to ZEE or, if one is selected, from the selected boundingbox
        if self.boundingbox.selectionModel().hasSelection() == False:
            ## Change button's title
            self.add_extent.setText(u"Adicionar")
            initialrect = core.QgsRectangle(-46.63064, 22.52146, 9.64473,
                                            47.31826)
        else:
            ## Get selected bounding box coords and resource flag
            index = self.boundingbox.selectionModel().selectedRows()[0].row()
            row = self.boundingbox.model().matrix[index]

            minx = float(row[0].replace(',', '.'))
            miny = float(row[3].replace(',', '.'))
            maxx = float(row[1].replace(',', '.'))
            maxy = float(row[2].replace(',', '.'))

            if minx == 0. and miny == 0. and maxx == 0. and maxy == 0.:
                initialrect = core.QgsRectangle(-46.63064, 22.52146, 9.64473,
                                                47.31826)
            else:
                ## Set fields with these values
                self.xMin.setValue(minx)
                self.xMax.setValue(maxx)
                self.yMin.setValue(miny)
                self.yMax.setValue(maxy)
                self.resourcebox.setChecked(bool(row[4]))

                ## Set the extent and add a bit of zoom out of the selected extent
                initialrect = core.QgsRectangle(minx - minx * 0.1,
                                                miny - miny * 0.1,
                                                maxx + maxx * 0.1,
                                                maxy + maxy * 0.1)

                ## Draw initial extent on the map
                self.toolSelect.drawRect(minx, miny, maxx, maxy)

                ## Change button's title
                self.add_extent.setText(u"Alterar")

        self.canvas.setExtent(initialrect)
        # ----------------------------------

        ## Append layers to MapCanvas
        self.layers.append(llayer)
        self.layers.append(layer)
        #self.layers.append(gui.QgsMapCanvasLayer(llayer))
        #self.layers.append(gui.QgsMapCanvasLayer(layer))
        #self.canvas.setLayerSet(self.layers)
        self.canvas.setLayers([llayer, layer])

        ## Set triggers to buttons
        self.add_extent.clicked.connect(self.add_new_extent)
        self.btn_close.clicked.connect(lambda: self.done(QDialog.Rejected))
        self.finished.connect(self.cleanup)

        ## Disabled coord fields
        self.xMin.setEnabled(False)
        self.xMax.setEnabled(False)
        self.yMin.setEnabled(False)
        self.yMax.setEnabled(False)
Exemple #6
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """

        self.templatepath = os.path.join(pluginDirectory('qkan'), u"database/templates")

        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'ExportToKP_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.dlg = ExportToKPDialog()

        # Anfang Eigene Funktionen -------------------------------------------------
        # (jh, 08.02.2017)

        logger.info('\n\nQKan_ExportKP initialisiert...')

        # --------------------------------------------------------------------------
        # Pfad zum Arbeitsverzeichnis sicherstellen
        wordir = os.path.join(site.getuserbase(), 'qkan')

        if not os.path.isdir(wordir):
            os.makedirs(wordir)

        # --------------------------------------------------------------------------
        # Konfigurationsdatei qkan.json lesen
        #

        self.configfil = os.path.join(wordir, 'qkan.json')
        if os.path.exists(self.configfil):
            with open(self.configfil, 'r') as fileconfig:
                self.config = json.loads(fileconfig.read())
        else:
            self.config['dynafile'] = ''
            # Vorlagedatenbank nur für den Fall, dass der Anwender keine eigene Vorlage erstellen will
            self.config['template_dyna'] = os.path.join(os.path.dirname(__file__), "templates", "dyna.ein")
            self.config['database_QKan'] = ''
            with open(self.configfil, 'w') as fileconfig:
                fileconfig.write(json.dumps(self.config))

        # Standard für Suchverzeichnis festlegen
        project = QgsProject.instance()
        self.default_dir = os.path.dirname(project.fileName())

        # Formularereignisse anbinden ----------------------------------------------

        self.dlg.pb_select_KP_dest.clicked.connect(self.selectFile_kpDB_dest)
        self.dlg.pb_select_KP_template.clicked.connect(self.selectFile_kpDB_template)
        self.dlg.lw_teilgebiete.itemClicked.connect(self.lw_teilgebieteClick)
        self.dlg.cb_selActive.stateChanged.connect(self.selActiveClick)
        self.dlg.button_box.helpRequested.connect(self.helpClick)
        self.dlg.pb_selectQKanDB.clicked.connect(self.selectFile_QKanDB)
Exemple #7
0
def importResults(database_HE,
                  database_QKan,
                  qml_choice,
                  qmlfileResults,
                  epsg=25832,
                  dbtyp=u'SpatiaLite'):
    '''Importiert Simulationsergebnisse aus einer HE-Firebird-Datenbank und schreibt diese in Tabellen 
       der QKan-SpatiaLite-Datenbank.

    :database_HE:   Datenbankobjekt, das die Verknüpfung zur HE-Firebird-Datenbank verwaltet
    :type database: DBConnection (geerbt von firebirdsql...)

    :database_QKan: Datenbankobjekt, das die Verknüpfung zur QKan-SpatiaLite-Datenbank verwaltet.
    :type database: DBConnection (geerbt von dbapi...)

    :dbtyp:         Typ der Datenbank (SpatiaLite, PostGIS)
    :type dbtyp:    String
    
    :returns: void
    '''

    # ------------------------------------------------------------------------------
    # Datenbankverbindungen

    dbHE = FBConnection(
        database_HE)  # Datenbankobjekt der HE-Datenbank zum Lesen

    if dbHE is None:
        fehlermeldung(
            u"Fehler in QKan_Import_from_HE",
            u'ITWH-Datenbank {:s} wurde nicht gefunden!\nAbbruch!'.format(
                database_HE))
        return None

    dbQK = DBConnection(dbname=database_QKan
                        )  # Datenbankobjekt der QKan-Datenbank zum Schreiben
    if not dbQK.connected:
        return None

    if dbQK is None:
        fehlermeldung(
            u"Fehler in QKan_Import_from_HE",
            u'QKan-Datenbank {:s} wurde nicht gefunden!\nAbbruch!'.format(
                database_QKan))
        return None

    # Vorbereiten der temporären Ergebnistabellen
    sqllist = [
        u'''CREATE TABLE IF NOT EXISTS ResultsSch(
            pk INTEGER PRIMARY KEY AUTOINCREMENT,
            schnam TEXT,
            uebstauhaeuf REAL,
            uebstauanz REAL, 
            maxuebstauvol REAL,
            kommentar TEXT,
            createdat TEXT DEFAULT CURRENT_DATE)''',
        u"""SELECT AddGeometryColumn('ResultsSch','geom',{},'POINT',2)""".
        format(epsg), u'''DELETE FROM ResultsSch'''
    ]
    # , u'''CREATE TABLE IF NOT EXISTS ResultsHal(
    # pk INTEGER PRIMARY KEY AUTOINCREMENT,
    # haltnam TEXT,
    # uebstauhaeuf REAL,
    # uebstauanz REAL,
    # maxuebstauvol REAL,
    # kommentar TEXT,
    # createdat TEXT DEFAULT CURRENT_DATE)''',
    # u"""SELECT AddGeometryColumn('ResultsHal','geom',{},'LINESTRING',2)""".format(epsg)
    # u'''DELETE FROM ResultsHal''']

    for sql in sqllist:
        if not dbQK.sql(sql, u"QKan_Import_Results (1)"):
            return False

    # Die folgende Abfrage gilt sowohl bei Einzel- als auch bei Seriensimulationen:
    sql = u'''SELECT MR.KNOTEN, LZ.HAEUFIGKEITUEBERSTAU, LZ.ANZAHLUEBERSTAU, MR.UEBERSTAUVOLUMEN
            FROM LAU_MAX_S AS MR
            LEFT JOIN LANGZEITKNOTEN AS LZ
            ON MR.KNOTEN = LZ.KNOTEN
            ORDER BY KNOTEN'''

    if not dbHE.sql(sql, u"QKan_Import_Results (4)"):
        return False

    for attr in dbHE.fetchall():
        # In allen Feldern None durch NULL ersetzen
        (schnam, uebstauhaeuf, uebstauanz, maxuebstauvol) = \
            (u'NULL' if el is None else el for el in attr)

        sql = u'''INSERT INTO ResultsSch
                (schnam, uebstauhaeuf, uebstauanz, maxuebstauvol, kommentar)
                VALUES ('{schnam}', {uebstauhaeuf}, {uebstauanz}, {maxuebstauvol}, '{kommentar}')'''.format(
            schnam=schnam,
            uebstauhaeuf=uebstauhaeuf,
            uebstauanz=uebstauanz,
            maxuebstauvol=maxuebstauvol,
            kommentar=os.path.basename(database_HE))

        if not dbQK.sql(sql, u'QKan_Import_Results (5)'):
            return False

    sql = '''UPDATE ResultsSch
            SET geom = 
            (   SELECT geop
                FROM schaechte
                WHERE schaechte.schnam = ResultsSch.schnam)'''
    if not dbQK.sql(sql, u'QKan_Import_Results (6)'):
        return False

    dbQK.commit()

    # Einfügen der Ergebnistabelle in die Layerliste, wenn nicht schon geladen
    layers = iface.legendInterface().layers()
    if u'Ergebnisse_LZ' not in [lay.name() for lay in layers]:
        uri = QgsDataSourceURI()
        uri.setDatabase(database_QKan)
        uri.setDataSource(u'', u'ResultsSch', u'geom')
        vlayer = QgsVectorLayer(uri.uri(), u'Überstau Schächte', u'spatialite')
        QgsMapLayerRegistry.instance().addMapLayer(vlayer)

        # Stilvorlage nach Benutzerwahl laden
        templatepath = os.path.join(pluginDirectory('qkan'), u"templates")
        if qml_choice == 'uebh':
            template = os.path.join(templatepath, u"Überstauhäufigkeit.qml")
            try:
                vlayer.loadNamedStyle(template)
            except:
                fehlermeldung(
                    u"Fehler in QKan_Results_from_HE",
                    u'Stildatei "Überstauhäufigkeit.qml" wurde nicht gefunden!\nAbbruch!'
                )
        elif qml_choice == 'uebvol':
            template = os.path.join(templatepath, u"Überstauvolumen.qml")
            try:
                vlayer.loadNamedStyle(template)
            except:
                fehlermeldung(
                    u"Fehler in QKan_Results_from_HE",
                    u'Stildatei "Überstauvolumen.qml" wurde nicht gefunden!\nAbbruch!'
                )
        elif qml_choice == 'userqml':
            try:
                vlayer.loadNamedStyle(qmlfileResults)
            except:
                fehlermeldung(
                    u"Fehler in QKan_Results_from_HE",
                    u'Benutzerdefinierte Stildatei {:s} wurde nicht gefunden!\nAbbruch!'
                    .format(qml_choice))

    del dbQK
    del dbHE
Exemple #8
0
    def __init__(self, dbname=None, tabObject=None, epsg=25832):
        """Constructor.

        :param dbname: Pfad zur SpatiaLite-Datenbankdatei. Falls nicht vorhanden, 
               wird es angelegt.
        :type tabObject: String

        :param tabObject: Vectorlayerobjekt, aus dem die Parameter zum 
            Zugriff auf die SpatiaLite-Tabelle ermittelt werden.
        :type tabObject: QgsVectorLayer
        """

        # Übernahme einiger Attribute in die Klasse
        self.epsg = epsg
        self.dbname = dbname

        # Die nachfolgenden Klassenobjekte dienen dazu, gleichartige (sqlidtext) SQL-Debug-Meldungen
        # nur einmal pro Sekunde zu erzeugen.
        self.sqltime = datetime.datetime(2017, 1, 1, 1, 0, 0)
        self.sqltime = self.sqltime.now()
        self.sqltext = ''
        self.sqlcount = 0
        self.actversion = '2.5.5'
        self.templatepath = os.path.join(pluginDirectory('qkan'),
                                         u"database/templates")

        if dbname is not None:
            # Verbindung zur Datenbank herstellen oder die Datenbank neu erstellen
            if os.path.exists(dbname):
                self.consl = splite.connect(database=dbname,
                                            check_same_thread=False)
                self.cursl = self.consl.cursor()

                logger.debug(
                    u'dbfund.__init__: Datenbank existiert und Verbindung hergestellt:\n{}'
                    .format(dbname))
                # Versionsprüfung
                if not self.updateVersion():
                    self.consl.close()
                    return None

            else:
                iface.messageBar().pushMessage(
                    u"Information",
                    u"SpatiaLite-Datenbank wird erstellt. Bitte waren...",
                    level=QgsMessageBar.INFO)

                datenbank_QKan_Template = os.path.join(self.templatepath,
                                                       u"qkan.sqlite")
                try:
                    shutil.copyfile(datenbank_QKan_Template, dbname)
                except BaseException as err:
                    fehlermeldung(
                        u'Fehler in dbfunc.DBConnection:\n{}\n'.format(err),
                        u'Kopieren von: {}\nnach: {}\n nicht möglich'.format(
                            self.templatepath, dbname))
                    return None

                self.consl = splite.connect(database=dbname)
                self.cursl = self.consl.cursor()

                # sql = u'SELECT InitSpatialMetadata()'
                # self.cursl.execute(sql)

                iface.messageBar().pushMessage(
                    u"Information",
                    u"SpatiaLite-Datenbank ist erstellt!",
                    level=QgsMessageBar.INFO)
                if not createdbtables(self.consl, self.cursl, self.actversion,
                                      self.epsg):
                    iface.messageBar().pushMessage(
                        u"Fehler",
                        u"SpatiaLite-Datenbank: Tabellen konnten nicht angelegt werden",
                        level=QgsMessageBar.CRITICAL)
        elif tabObject is not None:
            tabconnect = tabObject.publicSource()
            t_db, t_tab, t_geo, t_sql = tuple(tabconnect.split())
            dbname = t_db.split(u'=')[1].strip(u"'")
            self.tabname = t_tab.split(u'=')[1].strip(u'"')

            # Pruefung auf korrekte Zeichen in Namen
            if not checknames(self.tabname):
                iface.messageBar().pushMessage(
                    u"Fehler",
                    u"Unzulaessige Zeichen in Tabellenname: " + self.tabname,
                    level=QgsMessageBar.CRITICAL)
                self.consl = None
            else:

                try:
                    self.consl = splite.connect(database=dbname)
                    self.cursl = self.consl.cursor()
                except:
                    iface.messageBar().pushMessage(
                        u"Fehler",
                        u'Fehler beim Öffnen der SpatialLite-Datenbank {:s}!\nAbbruch!'
                        .format(dbname),
                        level=QgsMessageBar.CRITICAL)
                    self.consl = None
        else:
            iface.messageBar().pushMessage(
                u"Fehler",
                u'Fehler beim Anbinden der SpatialLite-Datenbank {:s}!\nAbbruch!'
                .format(dbname),
                level=QgsMessageBar.CRITICAL)
            self.consl = None
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """

        self.templatepath = os.path.join(pluginDirectory('qkan'), u"templates")

        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'ExportToHE_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.dlg = ExportToHEDialog()

        # Anfang Eigene Funktionen -------------------------------------------------
        # (jh, 08.02.2017)

        logger.info('\n\nQKan_ExportHE initialisiert...')

        # --------------------------------------------------------------------------
        # Pfad zum Arbeitsverzeichnis sicherstellen
        wordir = os.path.join(site.getuserbase(), 'qkan')

        if not os.path.isdir(wordir):
            os.makedirs(wordir)

        # --------------------------------------------------------------------------
        # Konfigurationsdatei qkan.json lesen
        #

        self.configfil = os.path.join(wordir, 'qkan.json')
        if os.path.exists(self.configfil):
            with open(self.configfil, 'r') as fileconfig:
                self.config = json.loads(fileconfig.read())
        else:
            self.config['database_HE'] = ''
            # Vorlagedatenbank nur für den Fall, dass der Anwender keine eigene Vorlage erstellen will
            self.config['dbtemplate_HE'] = os.path.join(os.path.dirname(__file__), "templates", "itwh.idbf")
            self.config['database_QKan'] = ''
            with open(self.configfil, 'w') as fileconfig:
                fileconfig.write(json.dumps(self.config))

        # Standard für Suchverzeichnis festlegen
        project = QgsProject.instance()
        self.default_dir = os.path.dirname(project.fileName())

        if 'database_QKan' in self.config:
            database_QKan = self.config['database_QKan']
        else:
            database_QKan = ''
        self.dlg.tf_QKanDB.setText(database_QKan)
        self.dlg.pb_selectQKanDB.clicked.connect(self.selectFile_QKanDB)

        if 'database_HE' in self.config:
            database_HE = self.config['database_HE']
        else:
            database_HE = ''
        self.dlg.tf_heDB_dest.setText(database_HE)
        self.dlg.pb_selectHeDB_dest.clicked.connect(self.selectFile_HeDB_dest)

        if 'dbtemplate_HE' in self.config:
            dbtemplate_HE = self.config['dbtemplate_HE']
        else:
            dbtemplate_HE = ''
        self.dlg.tf_heDB_template.setText(dbtemplate_HE)
        self.dlg.pb_selectHeDB_template.clicked.connect(self.selectFile_HeDB_template)
        self.dlg.pb_selectHeDB_emptytemplate.clicked.connect(self.selectFile_HeDB_emptytemplate)

        if 'datenbanktyp' in self.config:
            datenbanktyp = self.config['datenbanktyp']
        else:
            datenbanktyp = 'spatialite'
            pass  # Es gibt noch keine Wahlmöglichkeit

        # Auswahl der zu exportierenden Tabellen ----------------------------------------------

        # Eigene Funktion für die zahlreichen Checkboxen

        def cb_set(name, cbox, default):
            if name in self.config:
                checked = self.config[name]
            else:
                checked = default
            cbox.setChecked(checked)
            return checked

        export_schaechte = cb_set('export_schaechte', self.dlg.cb_export_schaechte, True)
        export_auslaesse = cb_set('export_auslaesse', self.dlg.cb_export_auslaesse, True)
        export_speicher = cb_set('export_speicher', self.dlg.cb_export_speicher, True)
        export_haltungen = cb_set('export_haltungen', self.dlg.cb_export_haltungen, True)
        export_pumpen = cb_set('export_pumpen', self.dlg.cb_export_pumpen, False)
        export_wehre = cb_set('export_wehre', self.dlg.cb_export_wehre, False)
        export_flaechenrw = cb_set('export_flaechenrw', self.dlg.cb_export_flaechenrw, True)
        export_einleitdirekt = cb_set('export_einleitdirekt', self.dlg.cb_export_einleitdirekt, True)
        export_aussengebiete = cb_set('export_aussengebiete', self.dlg.cb_export_aussengebiete, True)
        export_abflussparameter = cb_set('export_abflussparameter', self.dlg.cb_export_abflussparameter, True)
        export_regenschreiber = cb_set('export_regenschreiber', self.dlg.cb_export_regenschreiber, False)
        export_rohrprofile = cb_set('export_rohrprofile', self.dlg.cb_export_rohrprofile, False)
        export_speicherkennlinien = cb_set('export_speicherkennlinien', self.dlg.cb_export_speicherkennlinien, False)
        export_bodenklassen = cb_set('export_bodenklassen', self.dlg.cb_export_bodenklassen, False)

        modify_schaechte = cb_set('modify_schaechte', self.dlg.cb_modify_schaechte, False)
        modify_auslaesse = cb_set('modify_auslaesse', self.dlg.cb_modify_auslaesse, False)
        modify_speicher = cb_set('modify_speicher', self.dlg.cb_modify_speicher, False)
        modify_haltungen = cb_set('modify_haltungen', self.dlg.cb_modify_haltungen, False)
        modify_pumpen = cb_set('modify_pumpen', self.dlg.cb_modify_pumpen, False)
        modify_wehre = cb_set('modify_wehre', self.dlg.cb_modify_wehre, False)
        modify_flaechenrw = cb_set('modify_flaechenrw', self.dlg.cb_modify_flaechenrw, False)
        modify_einleitdirekt = cb_set('modify_einleitdirekt', self.dlg.cb_modify_einleitdirekt, False)
        modify_aussengebiete = cb_set('modify_aussengebiete', self.dlg.cb_modify_aussengebiete, False)
        modify_abflussparameter = cb_set('modify_abflussparameter', self.dlg.cb_modify_abflussparameter, False)
        modify_regenschreiber = cb_set('modify_regenschreiber', self.dlg.cb_modify_regenschreiber, False)
        modify_rohrprofile = cb_set('modify_rohrprofile', self.dlg.cb_modify_rohrprofile, False)
        modify_speicherkennlinien = cb_set('modify_speicherkennlinien', self.dlg.cb_modify_speicherkennlinien, False)
        modify_bodenklassen = cb_set('modify_bodenklassen', self.dlg.cb_modify_bodenklassen, False)

        combine_flaechenrw = cb_set('combine_flaechenrw', self.dlg.cb_combine_flaechenrw, True)
        combine_einleitdirekt = cb_set('combine_einleitdirekt', self.dlg.cb_combine_einleitdirekt, True)

        # Formularereignisse anbinden ----------------------------------------------

        self.dlg.pb_exportall.clicked.connect(self.exportall)
        self.dlg.pb_modifyall.clicked.connect(self.modifyall)
        self.dlg.pb_exportnone.clicked.connect(self.exportnone)
        self.dlg.pb_modifynone.clicked.connect(self.modifynone)

        self.dlg.lw_teilgebiete.itemClicked.connect(self.countselection)
        self.dlg.lw_teilgebiete.itemClicked.connect(self.lw_teilgebieteClick)
        self.dlg.cb_selActive.stateChanged.connect(self.selActiveClick)
        self.dlg.button_box.helpRequested.connect(self.helpClick)
    def __init__(self, parent, orgslist, in_distribution=False):
        super(InlineContactWidget, self).__init__(parent)
        self.parent = parent
        self.superParent = parent.superParent
        self.setupUi(self)
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)

        self.orgs = {}
        org = orgslist
        for x in org:
            name = org[x] + " (" + x + ")"
            self.orgs[x] = customCombo.CodeListItem(name, name, name)

        self.combo_org.setModel(
            customCombo.CustomComboBoxModel(
                self, [customCombo.CodeListItem(OUTRA, OUTRA, OUTRA)] +
                sorted(list(self.orgs.values()), key=lambda x: x.term_pt)))
        self.combo_org.currentIndexChanged.connect(self.check_org)

        # initialized where because if was on the spot the c++ garbage collector will destroy it and cause a error
        self.dialog = None
        tla.setupListView(self.phone, QgsFilterLineEdit, self, NoParent=True)
        tla.setupListView(self.email, QgsFilterLineEdit, self, NoParent=True)
        tla.setupListView(self.fax, QgsFilterLineEdit, self, NoParent=True)

        tla.setupMandatoryField(None, self.organization,
                                self.label_organization,
                                tla.formatTooltip(u"Elemento Obrigatório."))
        tla.setupMandatoryField(
            None, self.email, self.label_email,
            tla.formatTooltip(
                u"Deve ser indicado pelo menos um endereço eletrónico (\'<em>email</em>\')."
            ))

        for btn in self.findChildren(qwidgets.QPushButton,
                                     qcore.QRegExp('btn_*')):
            if '_add_' in btn.objectName():
                btn.setIcon(
                    qgui.QIcon(':/resourcesFolder/icons/plus_icon.svg'))
                btn.setText('')
            elif '_del_' in btn.objectName():
                btn.setIcon(
                    qgui.QIcon(':/resourcesFolder/icons/delete_icon.svg'))
                btn.setText('')
        for info in self.findChildren(qwidgets.QPushButton,
                                      qcore.QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)
        f = open(
            os.path.join(pluginDirectory('EditorMetadadosMarswInforbiomares'),
                         'resourcesFolder/stylesheet.qtcss'))
        self.sytlesheet = f.read()
        for btn in self.findChildren(qwidgets.QPushButton):
            btn.setStyleSheet(self.sytlesheet)
            btn.setFocusPolicy(Qt.NoFocus)
        self.name.editingFinished.connect(self.updateTitle)
        self.organization.textChanged.connect(self.updateTitle)
        self.city.editingFinished.connect(self.updateTitle)
        self.country.editingFinished.connect(self.updateTitle)
        self.email.model().dataChanged.connect(self.updateTitle)
        self.btn_del_contact.clicked.connect(self.deleteContact)
        self.btn_contact_list.clicked.connect(self.importFromListContacts)
        self.btn_addto_list_contacts.clicked.connect(self.addtoListOfContacts)
        self.mGroupBox.collapsedStateChanged.connect(self.hideButtons)
        self.btn_del_contact.setToolTip(tla.formatTooltip(u"Agagar contacto."))
        self.updateTitle()

        self.btn_addto_list_contacts.setIcon(
            qgui.QIcon(':/resourcesFolder/icons/save_icon.svg'))
        self.btn_addto_list_contacts.setToolTip(
            tla.formatTooltip(u"Guardar contacto na Lista de Contactos."))
        self.btn_contact_list.setIcon(
            qgui.QIcon(':/resourcesFolder/icons/contactsList_icon.svg'))
        self.btn_contact_list.setToolTip(u'Importar da Lista de Contactos')
        self.btn_contact_list.setText('')
        self.btn_addto_list_contacts.setText('')
        self.eater = tla.EatWheel()
        for x in self.findChildren(qwidgets.QComboBox):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)
        for x in self.findChildren(QDateTimeEdit):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)
        for x in self.findChildren(QDateEdit):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)

        if in_distribution:
            temp = {}
            temp["distributor"] = {}
            temp["distributor"]["en"] = "distributor"
            temp["distributor"]["pt"] = "Distribuidor"
            temp["distributor"]["description"] = "Distribuidor"

            self.roles = customCombo.dic_to_CustomComboBox_dic(temp)
            self.combo_role.setModel(
                customCombo.CustomComboBoxModel(
                    self,
                    sorted(list(self.roles.values()),
                           key=lambda x: x.term_pt)))
            self.combo_role.setDisabled(True)
        else:
            self.roles = customCombo.dic_to_CustomComboBox_dic(
                self.superParent.codelist["CI_RoleCode"])
            self.combo_role.setModel(
                customCombo.CustomComboBoxModel(
                    self,
                    sorted(list(self.roles.values()),
                           key=lambda x: x.term_pt)))
            tla.setupMandatoryField(
                None, self.combo_role, self.label_role,
                u"Tem que ser especificada uma função para o contacto.")
            self.combo_role.currentIndexChanged.connect(
                self.check_mandatory_completude)
Exemple #11
0
def qgsadapt(projectTemplate,
             qkanDB,
             epsg,
             projectFile,
             setPathToTemplateDir=True,
             dbtyp=u'SpatiaLite'):
    '''Lädt eine (Vorlage-) Projektdatei (*.qgs) und adaptiert diese auf eine QKan-Datenbank an. 
    Anschließend wird dieses Projekt geladen. 
    Voraussetzungen: keine

    :projectTemplate:           Vorlage-Projektdatei
    :type database:             String

    :qkanDB:                    Ziel-Datenbank, auf die die Projektdatei angepasst werden soll
    :type qkanDB:               String

    :projectFile:               Zu Erzeugende Projektdatei
    :type projectFile:          String

    :setPathToTemplateDir:      Option, ob das Suchverzeichnis auf das Template-Verzeichnis gesetzt werden soll. 
    :type setPathToTemplateDir: Boolean

    :dbtyp:                     Typ der Datenbank (SpatiaLite, PostGIS)
    :type dbtyp:                String
    
    :returns: void
    '''

    # ------------------------------------------------------------------------------
    # Datenbankverbindungen

    dbQK = DBConnection(
        dbname=qkanDB,
        epsg=epsg)  # Datenbankobjekt der QKan-Datenbank zum Schreiben

    if dbQK is None:
        fehlermeldung(
            u"Fehler in qgsadapt",
            u'QKan-Datenbank {:s} wurde nicht gefunden!\nAbbruch!'.format(
                qkanDB))
        iface.messageBar().pushMessage(u"Fehler in qgsadapt",
                    u'QKan-Datenbank {:s} wurde nicht gefunden!\nAbbruch!'.format( \
            qkanDB), level=QgsMessageBar.CRITICAL)
        return None

    # --------------------------------------------------------------------------
    # Zoom-Bereich für die Projektdatei vorbereiten
    sql = u'''SELECT min(xsch) AS xmin, 
                    max(xsch) AS xmax, 
                    min(ysch) AS ymin, 
                    max(ysch) AS ymax
             FROM schaechte'''
    try:
        dbQK.sql(sql)
    except BaseException as e:
        fehlermeldung('SQL-Fehler', str(e))
        fehlermeldung("Fehler in qgsadapt",
                      u"\nFehler in sql_zoom: \n" + sql + '\n\n')

    daten = dbQK.fetchone()
    try:
        zoomxmin, zoomxmax, zoomymin, zoomymax = daten
    except BaseException as e:
        fehlermeldung('SQL-Fehler', str(e))
        fehlermeldung("Fehler in qgsadapt",
                      u"\nFehler in sql_zoom; daten= " + str(daten) + '\n')

    # --------------------------------------------------------------------------
    # Projektionssystem für die Projektdatei vorbereiten
    sql = """SELECT srid
            FROM geom_cols_ref_sys
            WHERE Lower(f_table_name) = Lower('schaechte')
            AND Lower(f_geometry_column) = Lower('geom')"""
    if not dbQK.sql(sql, 'importkanaldaten_dyna (37)'):
        return None

    srid = dbQK.fetchone()[0]
    try:
        crs = QgsCoordinateReferenceSystem(
            srid, QgsCoordinateReferenceSystem.EpsgCrsId)
        srsid = crs.srsid()
        proj4text = crs.toProj4()
        description = crs.description()
        projectionacronym = crs.projectionAcronym()
        if 'ellipsoidacronym' in dir(crs):
            ellipsoidacronym = crs.ellipsoidacronym()
        else:
            ellipsoidacronym = None
    except BaseException as e:
        srid, srsid, proj4text, description, projectionacronym, ellipsoidacronym = \
            'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy'

        fehlermeldung('\nFehler in "daten"', str(e))
        fehlermeldung("Fehler in qgsadapt",
                      u"\nFehler bei der Ermittlung der srid: \n" + str(daten))

    # --------------------------------------------------------------------------
    # Datenbankverbindungen schliessen

    del dbQK

    # --------------------------------------------------------------------------
    # Projektdatei schreiben, falls ausgewählt

    if projectFile is None or projectFile == u'':
        fehlermeldung(u'Bedienerfehler!',
                      u'Es wurde keine Projektdatei ausgewählt')
        return False

    if setPathToTemplateDir:
        templatepath = os.path.join(pluginDirectory('qkan'),
                                    u"database/templates")

    projectpath = os.path.dirname(projectFile)
    if os.path.dirname(qkanDB) == projectpath:
        datasource = qkanDB.replace(os.path.dirname(qkanDB), u'.')
    else:
        datasource = qkanDB

    # Liste der Geotabellen aus QKan, um andere Tabellen von der Bearbeitung auszuschliessen
    # Liste steht in 3 Modulen: tools.k_tools, importdyna.import_from_dyna, importhe.import_from_he
    tabliste = [
        u'einleit', u'einzugsgebiete', u'flaechen', u'haltungen', u'linkfl',
        u'linksw', u'pumpen', u'schaechte', u'teilgebiete', u'tezg', u'wehre'
    ]

    # Liste der QKan-Formulare, um individuell erstellte Formulare von der Bearbeitung auszuschliessen
    formsliste = [
        'qkan_abflussparameter.ui', 'qkan_anbindungageb.ui',
        'qkan_anbindungeinleit.ui', 'qkan_anbindungflaechen.ui',
        'qkan_auslaesse.ui', 'qkan_auslasstypen.ui', 'qkan_aussengebiete.ui',
        'qkan_bodenklassen.ui', 'qkan_einleit.ui', 'qkan_einzugsgebiete.ui',
        'qkan_entwaesserungsarten.ui', 'qkan_flaechen.ui', 'qkan_haltungen.ui',
        'qkan_profildaten.ui', 'qkan_profile.ui', 'qkan_pumpen.ui',
        'qkan_pumpentypen.ui', 'qkan_schaechte.ui',
        'qkan_simulationsstatus.ui', 'qkan_speicher.ui',
        'qkan_speicherkennlinien.ui', 'qkan_swref.ui', 'qkan_teilgebiete.ui',
        'qkan_tezg.ui', 'qkan_wehre.ui'
    ]

    # Lesen der Projektdatei ------------------------------------------------------------------
    qgsxml = ET.parse(projectTemplate)
    root = qgsxml.getroot()

    # Projektionssystem anpassen --------------------------------------------------------------

    for tag_maplayer in root.findall(u".//projectlayers/maplayer"):
        tag_datasource = tag_maplayer.find(u"./datasource")
        tex = tag_datasource.text
        # Nur QKan-Tabellen bearbeiten
        if tex[tex.index(u'table="') + 7:].split(u'" ')[0] in tabliste:

            # <extend> löschen
            for tag_extent in tag_maplayer.findall(u"./extent"):
                tag_maplayer.remove(tag_extent)

            for tag_spatialrefsys in tag_maplayer.findall(
                    u"./srs/spatialrefsys"):
                tag_spatialrefsys.clear()

                elem = ET.SubElement(tag_spatialrefsys, u'proj4')
                elem.text = proj4text
                elem = ET.SubElement(tag_spatialrefsys, u'srsid')
                elem.text = u'{}'.format(srsid)
                elem = ET.SubElement(tag_spatialrefsys, u'srid')
                elem.text = u'{}'.format(srid)
                elem = ET.SubElement(tag_spatialrefsys, u'authid')
                elem.text = u'EPSG: {}'.format(srid)
                elem = ET.SubElement(tag_spatialrefsys, u'description')
                elem.text = description
                elem = ET.SubElement(tag_spatialrefsys, u'projectionacronym')
                elem.text = projectionacronym
                if ellipsoidacronym is not None:
                    elem = ET.SubElement(tag_spatialrefsys,
                                         u'ellipsoidacronym')
                    elem.text = ellipsoidacronym

    # Pfad zu Formularen auf plugin-Verzeichnis setzen -----------------------------------------

    formspath = os.path.join(pluginDirectory('qkan'), u"forms")
    for tag_maplayer in root.findall(u".//projectlayers/maplayer"):
        tag_editform = tag_maplayer.find(u"./editform")
        dateiname = os.path.basename(tag_editform.text)
        if dateiname in formsliste:
            # Nur QKan-Tabellen bearbeiten
            tag_editform.text = os.path.join(formspath, dateiname)

    # Zoom für Kartenfenster einstellen -------------------------------------------------------

    for tag_extent in root.findall(u".//mapcanvas/extent"):
        elem = tag_extent.find(u"./xmin")
        elem.text = u'{:.3f}'.format(zoomxmin)
        elem = tag_extent.find(u"./ymin")
        elem.text = u'{:.3f}'.format(zoomymin)
        elem = tag_extent.find(u"./xmax")
        elem.text = u'{:.3f}'.format(zoomxmax)
        elem = tag_extent.find(u"./ymax")
        elem.text = u'{:.3f}'.format(zoomymax)

    # Projektionssystem anpassen --------------------------------------------------------------

    for tag_spatialrefsys in root.findall(
            u".//mapcanvas/destinationsrs/spatialrefsys"):
        tag_spatialrefsys.clear()

        elem = ET.SubElement(tag_spatialrefsys, u'proj4')
        elem.text = proj4text
        elem = ET.SubElement(tag_spatialrefsys, u'srid')
        elem.text = u'{}'.format(srid)
        elem = ET.SubElement(tag_spatialrefsys, u'authid')
        elem.text = u'EPSG: {}'.format(srid)
        elem = ET.SubElement(tag_spatialrefsys, u'description')
        elem.text = description
        elem = ET.SubElement(tag_spatialrefsys, u'projectionacronym')
        elem.text = projectionacronym
        if ellipsoidacronym is not None:
            elem = ET.SubElement(tag_spatialrefsys, u'ellipsoidacronym')
            elem.text = ellipsoidacronym

    # Pfad zur QKan-Datenbank anpassen

    for tag_datasource in root.findall(
            u".//projectlayers/maplayer/datasource"):
        text = tag_datasource.text
        tag_datasource.text = u"dbname='" + datasource + u"' " + text[
            text.find(u'table='):]

    qgsxml.write(projectFile)  # writing modified project file
    logger.debug(u'Projektdatei: {}'.format(projectFile))
    # logger.debug(u'encoded string: {}'.format(tex))

    # ------------------------------------------------------------------------------
    # Abschluss: Ggfs. Protokoll schreiben und Datenbankverbindungen schliessen

    iface.mainWindow().statusBar().clearMessage()
    iface.messageBar().pushMessage(
        "Information",
        "Projektdatei ist angepasst und muss neu geladen werden!",
        level=QgsMessageBar.INFO)