def testVisibility(self):
        """ test that map canvas annotation item visibility follows layer"""
        a = QgsTextAnnotation()
        canvas = QgsMapCanvas()
        i = QgsMapCanvasAnnotationItem(a, canvas)

        self.assertTrue(i.isVisible())

        layer = QgsVectorLayer("Point?crs=EPSG:3111&field=fldtxt:string",
                               'test', "memory")
        a.setMapLayer(layer)
        self.assertFalse(i.isVisible())
        canvas.setLayers([layer])
        self.assertTrue(i.isVisible())
Example #2
0
 def testFillSymbol(self):
     """ test rendering an annotation with fill symbol"""
     a = QgsTextAnnotation()
     a.setFrameSize(QSizeF(400, 250))
     a.setHasFixedMapPosition(False)
     a.setFillSymbol(QgsFillSymbol.createSimple({'color': 'blue', 'width_border': '5', 'outline_color': 'black'}))
     im = self.renderAnnotation(a, QPointF(20, 30))
     self.assertTrue(self.imageCheck('annotation_fillstyle', 'annotation_fillstyle', im))
Example #3
0
 def testTextAnnotation(self):
     """ test rendering a text annotation"""
     a = QgsTextAnnotation()
     a.setFrameSize(QSizeF(300, 200))
     a.setFrameOffsetFromReferencePoint(QPointF(40, 50))
     doc = QTextDocument()
     doc.setHtml('<p style="font-family: arial; font-weight: bold; font-size: 40px;">test annotation</p>')
     a.setDocument(doc)
     im = self.renderAnnotation(a, QPointF(20, 30))
     self.assertTrue(self.imageCheck('text_annotation', 'text_annotation', im))
Example #4
0
    def testTextAnnotation(self):
        """ test rendering a text annotation"""
        a = QgsTextAnnotation()
        a.fillSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
        a.markerSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
        a.setFrameSize(QSizeF(300, 200))
        a.setFrameOffsetFromReferencePoint(QPointF(40, 50))
        doc = QTextDocument()
        doc.setHtml('<p style="font-family: arial; font-weight: bold; font-size: 40px;">test annotation</p>')
        a.setDocument(doc)
        im = self.renderAnnotation(a, QPointF(20, 30))
        self.assertTrue(self.imageCheck('text_annotation', 'text_annotation', im))

        # check clone
        clone = a.clone()
        im = self.renderAnnotation(a, QPointF(20, 30))
        self.assertTrue(self.imageCheck('text_annotation', 'text_annotation', im))
    def testSize(self):
        """ test that map canvas annotation item size is correct """
        a = QgsTextAnnotation()
        a.setFrameSize(QSizeF(300, 200))
        a.setHasFixedMapPosition(False)
        a.setFillSymbol(QgsFillSymbol.createSimple({'color': 'blue', 'width_border': '0'}))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.show()

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)
        self.assertAlmostEqual(i.boundingRect().width(), 300, 1)
        self.assertAlmostEqual(i.boundingRect().height(), 200, 1)

        a.setHasFixedMapPosition(True)
        a.setFrameOffsetFromReferencePoint(QPointF(0, 0))
        self.assertAlmostEqual(i.boundingRect().width(), 300, -1)
        self.assertAlmostEqual(i.boundingRect().height(), 200, -1)
        a.setFrameOffsetFromReferencePoint(QPointF(10, 20))
        self.assertAlmostEqual(i.boundingRect().width(), 310, -1)
        self.assertAlmostEqual(i.boundingRect().height(), 220, -1)
Example #6
0
    def drawCostPaths(self, rows, con, args, geomType, canvasItemList, mapCanvas):
        resultPathsRubberBands = canvasItemList['paths']
        rubberBand = None
        cur_path_id = -1
        for row in rows:
            cur2 = con.cursor()
            args['result_path_id'] = row[0]
            args['result_source_id'] = sql.Literal(row[1])
            args['result_target_id'] = sql.Literal(row[2])
            args['result_cost'] = row[3]
            if args['result_path_id'] != cur_path_id:
                cur_path_id = args['result_path_id']
                if rubberBand:
                    resultPathsRubberBands.append(rubberBand)
                    rubberBand = None

                rubberBand = QgsRubberBand(mapCanvas, Utils.getRubberBandType(False))
                rubberBand.setColor(QColor(255, 0, 0, 128))
                rubberBand.setWidth(4)
            if args['result_cost'] != -1:
                query2 = sql.SQL("""
                    SELECT ST_AsText( ST_MakeLine(
                        (SELECT {geometry_vt} FROM  {vertex_schema}.{vertex_table} WHERE id = {result_source_id}),
                        (SELECT {geometry_vt} FROM  {vertex_schema}.{vertex_table} WHERE id = {result_target_id})
                        ))
                    """).format(**args)
                # Utils.logMessage(query2)
                cur2.execute(query2)
                row2 = cur2.fetchone()
                # Utils.logMessage(str(row2[0]))

                geom = QgsGeometry().fromWkt(str(row2[0]))
                if geom.wkbType() == QgsWkbTypes.MultiLineString:
                    for line in geom.asMultiPolyline():
                        for pt in line:
                            rubberBand.addPoint(pt)
                elif geom.wkbType() == QgsWkbTypes.LineString:
                    for pt in geom.asPolyline():
                        rubberBand.addPoint(pt)

        # TODO label the edge instead of labeling the target points
        if rubberBand:
            resultPathsRubberBands.append(rubberBand)
            rubberBand = None
        resultNodesTextAnnotations = canvasItemList['annotations']
        for row in rows:
            cur2 = con.cursor()
            args['result_seq'] = row[0]
            args['result_source_id'] = sql.Literal(row[1])
            result_target_id = row[2]
            args['result_target_id'] = sql.Literal(result_target_id)
            result_cost = row[3]
            query2 = sql.SQL("""
                SELECT ST_AsText( ST_startPoint({geometry}) ) FROM {edge_schema}.{edge_table}
                    WHERE {source} = {result_target_id}
                UNION
                SELECT ST_AsText( ST_endPoint( {geometry} ) ) FROM {edge_schema}.{edge_table}
                    WHERE {target} = {result_target_id}
                """).format(**args)
            cur2.execute(query2)
            row2 = cur2.fetchone()

            geom = QgsGeometry().fromWkt(str(row2[0]))
            pt = geom.asPoint()
            textDocument = QTextDocument("{0!s}:{1}".format(result_target_id, result_cost))
            textAnnotation = QgsTextAnnotation()
            textAnnotation.setMapPosition(geom.asPoint())
            textAnnotation.setFrameSize(QSizeF(textDocument.idealWidth(), 20))
            textAnnotation.setFrameOffsetFromReferencePoint(QPointF(20, -40))
            textAnnotation.setDocument(textDocument)

            QgsMapCanvasAnnotationItem(textAnnotation, mapCanvas)
            resultNodesTextAnnotations.append(textAnnotation)
    def testSize(self):
        """ test that map canvas annotation item size is correct """
        a = QgsTextAnnotation()
        a.setFrameSize(QSizeF(300, 200))
        a.setHasFixedMapPosition(False)
        a.setFillSymbol(
            QgsFillSymbol.createSimple({
                'color': 'blue',
                'width_border': '0'
            }))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.show()

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)
        self.assertAlmostEqual(i.boundingRect().width(), 300, 1)
        self.assertAlmostEqual(i.boundingRect().height(), 200, 1)

        a.setHasFixedMapPosition(True)
        a.setFrameOffsetFromReferencePoint(QPointF(0, 0))
        self.assertAlmostEqual(i.boundingRect().width(), 300, -1)
        self.assertAlmostEqual(i.boundingRect().height(), 200, -1)
        a.setFrameOffsetFromReferencePoint(QPointF(10, 20))
        self.assertAlmostEqual(i.boundingRect().width(), 310, -1)
        self.assertAlmostEqual(i.boundingRect().height(), 220, -1)
Example #8
0
    def run(self):
        project_id = self.settings.value("project/id")
        epsg = self.settings.value("project/epsg")

        locale = QSettings().value('locale/userLocale')[0:2]

        if not project_id:
            self.message_bar.pushCritical(
                "Error",
                _translate("VeriSO_EE_Geb_LokTest", "project_id not set",
                           None))
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_EE_Geb_LokTest",
                               "Gebaeudeadressen - Lokalisationstest", None)
            group += " (" + str(project_id) + ")"

            # TODO: Check "tid" vs. t_ili_tid... in queries. Do not import
            # i_ili_tid?

            # define layer names here
            lokalisation = _translate("VeriSO_EE_Geb_LokTest",
                                      "Lokalisation Lokalisationstest", None)
            strassenstueck_geometrie = _translate(
                "VeriSO_EE_Geb_LokTest", "Strassenstueck (geometrie) "
                "Lokalisationstest", None)
            strassenstueck_anfangspunkt = _translate(
                "VeriSO_EE_Geb_LokTest", "Strassenstueck ("
                "anfangspunkt) "
                "Lokalisationstest", None)
            benanntesgebiet = _translate("VeriSO_EE_Geb_LokTest",
                                         "Benanntes Gebiet Lokalisationstest",
                                         None)
            gebaeudeeingang = _translate("VeriSO_EE_Geb_LokTest",
                                         "Gebaeudeeingang Lokalisationstest",
                                         None)
            shortestline = _translate("VeriSO_EE_Geb_LokTest",
                                      "Kuerzeste Linie Lokalisationstest",
                                      None)
            hausnummerpos = _translate("VeriSO_EE_Geb_LokTest",
                                       "HausnummerPos Lokalisationstest", None)
            lokalisationsname = _translate("VeriSO_EE_Geb_LokTest",
                                           "LokalisationsName", None)

            vlayer_lokalisation = self.get_vector_layer_by_name(lokalisation)
            if not vlayer_lokalisation:
                layer = {
                    "type": "postgres",
                    "title": lokalisation,
                    "featuretype": "gebaeudeadressen_lokalisation",
                    "key": "ogc_fid",
                    "sql": "ogc_fid = -1",
                    "readonly": True,
                    "group": group
                }
                vlayer_lokalisation = self.layer_loader.load(layer)

            vlayer_strassenstueck_geometrie = self.get_vector_layer_by_name(
                strassenstueck_geometrie)
            if not vlayer_strassenstueck_geometrie:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Strassenstueck (geometrie) Lokalisationstest",
                    "featuretype":
                    "gebaeudeadressen_strassenstueck",
                    "geom":
                    "geometrie",
                    "key":
                    "ogc_fid",
                    "sql":
                    "strassenstueck_von = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/strassenachsen_rot"
                    ".qml"
                }
                vlayer_strassenstueck_geometrie = self.layer_loader.load(layer)

            vlayer_strassenstueck_anfangspunkt = self.get_vector_layer_by_name(
                strassenstueck_anfangspunkt)
            if not vlayer_strassenstueck_anfangspunkt:
                layer = {
                    "type": "postgres",
                    "title": "Strassenstueck (anfangspunkt) Lokalisationstest",
                    "featuretype": "gebaeudeadressen_strassenstueck",
                    "geom": "anfangspunkt",
                    "key": "ogc_fid",
                    "sql": "strassenstueck_von = -1",
                    "readonly": True,
                    "group": group,
                    "style": "global_qml/gebaeudeadressen/anfangspunkt_rot.qml"
                }
                vlayer_strassenstueck_anfangspunkt = self.layer_loader.load(
                    layer)

            vlayer_benanntesgebiet = self.get_vector_layer_by_name(
                benanntesgebiet)
            if not vlayer_benanntesgebiet:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Benanntes Gebiet Lokalisationstest",
                    "featuretype":
                    "gebaeudeadressen_benanntesgebiet",
                    "geom":
                    "flaeche",
                    "key":
                    "ogc_fid",
                    "sql":
                    "benanntesgebiet_von = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/benanntesgebiet_rot"
                    ".qml"
                }
                vlayer_benanntesgebiet = self.layer_loader.load(layer)

            vlayer_gebaeudeeingang = self.get_vector_layer_by_name(
                gebaeudeeingang)
            if not vlayer_gebaeudeeingang:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Gebaeudeeingang Lokalisationstest",
                    "featuretype":
                    "gebaeudeadressen_gebaeudeeingang",
                    "geom":
                    "lage",
                    "key":
                    "ogc_fid",
                    "sql":
                    "gebaeudeeingang_von = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/gebaeudeeingang_rot"
                    ".qml"
                }
                vlayer_gebaeudeeingang = self.layer_loader.load(layer)

            vlayer_shortestline = self.get_vector_layer_by_name(shortestline)
            if not vlayer_shortestline:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Kuerzeste Linie Lokalisationstest",
                    "featuretype":
                    "t_shortestline_hausnummerpos",
                    "geom":
                    "the_geom",
                    "key":
                    "ogc_fid",
                    "sql":
                    "lok_tid = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/shortestline_linie_rot.qml"
                }
                vlayer_shortestline = self.layer_loader.load(layer)

            vlayer_hausnummerpos = self.get_vector_layer_by_name(hausnummerpos)
            if not vlayer_hausnummerpos:
                layer = {
                    "type": "postgres",
                    "title": "HausnummerPos Lokalisationstest",
                    "featuretype": "v_gebaeudeadressen_hausnummerpos",
                    "geom": "pos",
                    "key": "ogc_fid",
                    "sql": "lok_tid = -1",
                    "readonly": True,
                    "group": group,
                    "style":
                    "global_qml/gebaeudeadressen/hausnummerpos_rot.qml"
                }
                vlayer_hausnummerpos = self.layer_loader.load(layer)

            vlayer_lokalisationsname = self.get_vector_layer_by_name(
                lokalisationsname)
            if not vlayer_lokalisationsname:
                self.message_bar.pushMessage(
                    "Error",
                    _translate("VeriSO_EE_Geb_LokTest",
                               "Layer _LokalisationsName_ not found.", None),
                    level=Qgis.Critical,
                    duration=0)
                QApplication.restoreOverrideCursor()
                return

            iterator = vlayer_lokalisationsname.getFeatures()
            ids = []

            for feature in iterator:
                ids.append(feature.id())

            if vlayer_lokalisationsname.selectedFeatureCount() < 1:
                self.message_bar.pushCritical(
                    "Error",
                    _translate("VeriSO_EE_Geb_LokTest",
                               "No _LokalisationsName_ selected.", None))
                QApplication.restoreOverrideCursor()
                return

            if vlayer_lokalisationsname.selectedFeatureCount() > 1:
                self.message_bar.pushCritical(
                    "Error",
                    _translate(
                        "VeriSO_EE_Geb_LokTest",
                        "Please select only one (1) _LokalisationsName_.",
                        None))
                QApplication.restoreOverrideCursor()
                return

            feat = QgsFeature()
            id = vlayer_lokalisationsname.selectedFeatureIds()[0]
            feat = vlayer_lokalisationsname.selectedFeatures()[0]
            idx = ids.index(id)

            benannte_idx = vlayer_lokalisationsname.lookupField("benannte")
            text_idx = vlayer_lokalisationsname.lookupField("atext")

            if benannte_idx == -1 or text_idx == -1:
                self.message_bar.pushCritical(
                    "Error",
                    _translate("VeriSO_EE_Geb_LokTest",
                               "Field _benannte_ or _text_ not found.", None))
                QApplication.restoreOverrideCursor()
                return

            benannte = feat.attributes()[benannte_idx]
            lokalisationsname = feat.attributes()[text_idx]

            vlayer_strassenstueck_geometrie.setSubsetString(
                "(strassenstueck_von = " + str(benannte) + ")")
            vlayer_strassenstueck_anfangspunkt.setSubsetString(
                "(strassenstueck_von = " + str(benannte) + ")")
            vlayer_benanntesgebiet.setSubsetString("(benanntesgebiet_von = " +
                                                   str(benannte) + ")")
            vlayer_gebaeudeeingang.setSubsetString("(gebaeudeeingang_von = " +
                                                   str(benannte) + ")")
            vlayer_lokalisation.setSubsetString("(ogc_fid = " + str(benannte) +
                                                ")")
            vlayer_shortestline.setSubsetString("(lok_tid = " + str(benannte) +
                                                ")")
            vlayer_hausnummerpos.setSubsetString("(lok_tid = " +
                                                 str(benannte) + ")")

            if vlayer_strassenstueck_geometrie.featureCount() > 0:
                x_min = vlayer_strassenstueck_geometrie.extent().xMinimum()
                y_min = vlayer_strassenstueck_geometrie.extent().yMinimum()
                x_max = vlayer_strassenstueck_geometrie.extent().xMaximum()
                y_max = vlayer_strassenstueck_geometrie.extent().yMaximum()

            if vlayer_benanntesgebiet.featureCount() > 0:
                x_min = vlayer_benanntesgebiet.extent().xMinimum()
                y_min = vlayer_benanntesgebiet.extent().yMinimum()
                x_max = vlayer_benanntesgebiet.extent().xMaximum()
                y_max = vlayer_benanntesgebiet.extent().yMaximum()

            try:
                if vlayer_gebaeudeeingang.featureCount() > 0:
                    if vlayer_gebaeudeeingang.extent().xMinimum() < x_min:
                        x_min = vlayer_gebaeudeeingang.extent().xMinimum()
                    if vlayer_gebaeudeeingang.extent().yMinimum() < y_min:
                        y_min = vlayer_gebaeudeeingang.extent().yMinimum()
                    if vlayer_gebaeudeeingang.extent().xMaximum() > x_max:
                        x_max = vlayer_gebaeudeeingang.extent().xMaximum()
                    if vlayer_gebaeudeeingang.extent().yMaximum() > y_max:
                        y_max = vlayer_gebaeudeeingang.extent().yMaximum()

                rect = QgsRectangle(x_min, y_min, x_max, y_max)
                rect.scale(1.3)

            except UnboundLocalError:
                vlayer_gemeindegrenze = self.getVectorLayerByName(
                    "Gemeindegrenze")
                if vlayer_gemeindegrenze is None:
                    rect = self.canvas.fullExtent()
                else:
                    rect = vlayer_gemeindegrenze.extent()

            self.iface.mapCanvas().setExtent(rect)
            self.iface.mapCanvas().refresh()

            iterator = vlayer_lokalisation.getFeatures()

            # only one feature is selected
            for feature in iterator:
                prinzip_idx = vlayer_lokalisation.lookupField(
                    "nummerierungsprinzip_txt")
                attributeprovisorisch_idx = vlayer_lokalisation.lookupField(
                    "attributeprovisorisch_txt")
                offiziell_idx = vlayer_lokalisation.lookupField(
                    "istoffiziellebezeichnung_txt")
                status_idx = vlayer_lokalisation.lookupField("status_txt")
                inaenderung_idx = vlayer_lokalisation.lookupField(
                    "inaenderung_txt")
                art_idx = vlayer_lokalisation.lookupField("art_txt")

                something_missing = (prinzip_idx == -1
                                     or attributeprovisorisch_idx == -1
                                     or offiziell_idx == -1 or status_idx == -1
                                     or inaenderung_idx == -1 or art_idx == -1)
                if something_missing:
                    self.message_bar.pushMessage("Error",
                                                 _translate(
                                                     "VeriSO_EE_Geb_LokTest",
                                                     "Field not found.", None),
                                                 level=Qgis.Critical,
                                                 duration=0)
                    QApplication.restoreOverrideCursor()
                    return

                prinzip = feature.attributes()[prinzip_idx]
                attributeprovisorisch = feature.attributes(
                )[attributeprovisorisch_idx]
                offiziell = feature.attributes()[offiziell_idx]
                status = feature.attributes()[status_idx]
                inaenderung = feature.attributes()[inaenderung_idx]
                art = feature.attributes()[art_idx]

            map_extent = self.canvas.extent()
            x = map_extent.xMinimum()
            y = map_extent.yMaximum()

            text_item_found = False
            items = list(self.iface.mapCanvas().scene().items())
            for i in range(len(items)):
                try:
                    name = items[i].data(0)
                    if str(name) == "LokalisationsInfo":
                        text_item = items[i]
                        text_item_found = True
                except Exception:
                    pass

            if not text_item_found:
                text_item = QgsTextAnnotation(self.canvas)
                # text_item.setData(0, "LokalisationsInfo")

            # noinspection PyUnboundLocalVariable
            text_item.setMapPosition(
                QgsPointXY(x + 10 * self.canvas.mapUnitsPerPixel(),
                           y - 10 * self.canvas.mapUnitsPerPixel()))
            text_item.setHasFixedMapPosition(False)
            # text_item.setFrameBorderWidth(0.0)
            # text_item.setFrameColor(QColor(250, 250, 250, 255))
            # text_item.setFrameBackgroundColor(QColor(250, 250, 250, 123))
            text_item.setFrameSize(QSizeF(250, 150))
            text_document = QTextDocument()
            text_document.setHtml(
                "<table style='font-size:12px;'><tr><td>Lok.Name: </td><td>" +
                lokalisationsname + "</td></tr><tr><td>TID: </td><td>" +
                str(benannte) + "</td></tr> <tr><td>Num.prinzip: "
                "</td><td>" + str(prinzip) +
                "</td></tr> <tr><td>Attr. prov.: </td><td>" +
                str(attributeprovisorisch) + "</td></tr> <tr><td>ist "
                "offiziell: </td><td>" + str(offiziell) +
                "</td></tr> <tr><td>Status: "
                "</td><td>" + str(status) + "</td></tr> <tr><td>in Aenderung: "
                "</td><td>" + str(inaenderung) + "</td></tr> <tr><td>Art: "
                "</td><td>" + str(art) + "</td></tr>  </table>")
            text_item.setDocument(text_document)

            # This is a workaround: first ever position is not correct.
            text_item.setMapPosition(
                QgsPointXY(x + 10 * self.canvas.mapUnitsPerPixel(),
                           y - 10 * self.canvas.mapUnitsPerPixel()))
            text_item.update()

            self.iface.mapCanvas().refresh()

            try:
                vlayer_lokalisationsname.selectByIds([ids[idx + 1]])
            except IndexError:
                self.message_bar.pushInfo(
                    "Information",
                    _translate("VeriSO_EE_Geb_LokTest", "End of table.", None))

        except Exception as e:
            QApplication.restoreOverrideCursor()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.message_bar.pushMessage(
                "Error",
                str(traceback.format_exc(exc_traceback)),
                level=Qgis.Critical,
                duration=0)
        QApplication.restoreOverrideCursor()
    def testPosition(self):
        """ test that map canvas annotation item syncs position correctly """
        a = QgsTextAnnotation()
        a.setFrameSizeMm(QSizeF(300 / 3.7795275, 200 / 3.7795275))
        a.setFrameOffsetFromReferencePointMm(QPointF(40 / 3.7795275, 50 / 3.7795275))
        a.setMapPosition(QgsPointXY(12, 34))
        a.setMapPositionCrs(QgsCoordinateReferenceSystem(4326))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.show()

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)
        self.assertEqual(canvas.width(), 600)
        self.assertEqual(canvas.height(), 400)

        # test that correct initial position is set
        self.assertAlmostEqual(i.pos().x(), 120, 1)
        self.assertAlmostEqual(i.pos().y(), 110, 1)

        # shift annotation map position, check that item is moved
        a.setMapPosition(QgsPointXY(14, 32))
        self.assertAlmostEqual(i.pos().x(), 240, 1)
        self.assertAlmostEqual(i.pos().y(), 230, 1)

        # check relative position
        a.setHasFixedMapPosition(False)
        a.setRelativePosition(QPointF(0.8, 0.4))
        self.assertAlmostEqual(i.pos().x(), 480, 1)
        self.assertAlmostEqual(i.pos().y(), 160, 1)

        # flicking between relative and fixed position
        a.setHasFixedMapPosition(True)
        self.assertAlmostEqual(i.pos().x(), 240, 1)
        self.assertAlmostEqual(i.pos().y(), 230, 1)
        a.setHasFixedMapPosition(False)
        self.assertAlmostEqual(i.pos().x(), 480, 1)
        self.assertAlmostEqual(i.pos().y(), 160, 1)
Example #10
0
    def testTextAnnotation(self):
        """ test rendering a text annotation"""
        a = QgsTextAnnotation()
        a.fillSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
        a.markerSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
        a.setFrameSize(QSizeF(300, 200))
        a.setFrameOffsetFromReferencePoint(QPointF(40, 50))
        doc = QTextDocument()
        doc.setHtml(
            '<p style="font-family: arial; font-weight: bold; font-size: 40px;">test annotation</p>'
        )
        a.setDocument(doc)
        im = self.renderAnnotation(a, QPointF(20, 30))
        self.assertTrue(
            self.imageCheck('text_annotation', 'text_annotation', im))

        # check clone
        clone = a.clone()
        im = self.renderAnnotation(a, QPointF(20, 30))
        self.assertTrue(
            self.imageCheck('text_annotation', 'text_annotation', im))
Example #11
0
 def testTextAnnotationInLayout(self):
     """ test rendering a text annotation"""
     a = QgsTextAnnotation()
     a.fillSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
     a.markerSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
     a.setFrameSizeMm(QSizeF(300 / 3.7795275, 200 / 3.7795275))
     a.setFrameOffsetFromReferencePointMm(
         QPointF(40 / 3.7795275, 50 / 3.7795275))
     doc = QTextDocument()
     doc.setHtml(
         '<p style="font-family: arial; font-weight: bold; font-size: 40px;">test annotation</p>'
     )
     a.setDocument(doc)
     self.assertTrue(
         self.renderAnnotationInLayout('text_annotation_in_layout', a))
Example #12
0
 def testTextAnnotationInLayout(self):
     """ test rendering a text annotation"""
     a = QgsTextAnnotation()
     a.fillSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
     a.markerSymbol().symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
     a.setFrameSizeMm(QSizeF(300 / 3.7795275, 200 / 3.7795275))
     a.setFrameOffsetFromReferencePointMm(QPointF(40 / 3.7795275, 50 / 3.7795275))
     doc = QTextDocument()
     doc.setHtml('<p style="font-family: arial; font-weight: bold; font-size: 40px;">test annotation</p>')
     a.setDocument(doc)
     self.assertTrue(self.renderAnnotationInLayout('text_annotation_in_layout', a))
Example #13
0
    def testSize(self):
        """ test that map canvas annotation item size is correct """
        a = QgsTextAnnotation()
        a.setFrameSizeMm(QSizeF(300 / 3.7795275, 200 / 3.7795275))
        a.setHasFixedMapPosition(False)
        a.setFillSymbol(
            QgsFillSymbol.createSimple({
                'color': 'blue',
                'width_border': '0'
            }))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.show()

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)
        # ugly, but Travis has different default DPI:
        if 299 < i.boundingRect().width() < 301:
            self.assertAlmostEqual(i.boundingRect().width(), 300, 1)
            self.assertAlmostEqual(i.boundingRect().height(), 200, 1)

            a.setHasFixedMapPosition(True)
            a.setFrameOffsetFromReferencePoint(QPointF(0, 0))
            self.assertAlmostEqual(i.boundingRect().width(), 300, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 200, -1)
            a.setFrameOffsetFromReferencePoint(QPointF(10, 20))
            self.assertAlmostEqual(i.boundingRect().width(), 310, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 220, -1)
        else:
            self.assertAlmostEqual(i.boundingRect().width(), 312.5, 1)
            self.assertAlmostEqual(i.boundingRect().height(), 208.33, 1)

            a.setHasFixedMapPosition(True)
            a.setFrameOffsetFromReferencePoint(QPointF(0, 0))
            self.assertAlmostEqual(i.boundingRect().width(), 312.5, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 208.33, -1)
            a.setFrameOffsetFromReferencePoint(QPointF(10, 20))
            self.assertAlmostEqual(i.boundingRect().width(), 322.91, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 229.166, -1)
Example #14
0
    def _linetool_annotate_point(self, point, idx):
        annotation = QgsTextAnnotation()

        c = QTextDocument()
        html = "<strong>" + str(idx) + "</strong>"
        c.setHtml(html)

        annotation.setDocument(c)

        annotation.setFrameSize(QSizeF(27, 20))
        annotation.setFrameOffsetFromReferencePoint(QPointF(5, 5))
        annotation.setMapPosition(point)
        annotation.setMapPositionCrs(self.map_crs)

        return QgsMapCanvasAnnotationItem(
            annotation, self._iface.mapCanvas()).annotation()
    def testSettingFeature(self):
        """ test that feature is set when item moves """
        a = QgsTextAnnotation()
        a.setFrameSize(QSizeF(300, 200))
        a.setFrameOffsetFromReferencePoint(QPointF(40, 50))
        a.setHasFixedMapPosition(True)
        a.setMapPosition(QgsPointXY(12, 34))
        a.setMapPositionCrs(QgsCoordinateReferenceSystem(4326))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)  # NOQA

        layer = QgsVectorLayer(
            "Point?crs=EPSG:4326&field=station:string&field=suburb:string",
            'test', "memory")
        canvas.setLayers([layer])
        f = QgsFeature(layer.fields())
        f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(14, 31)))
        f.setValid(True)
        f.setAttributes(['hurstbridge', 'somewhere'])
        self.assertTrue(layer.dataProvider().addFeatures([f]))
        a.setMapLayer(layer)
        self.assertFalse(a.associatedFeature().isValid())

        a.setMapPosition(QgsPointXY(14, 31))
        self.assertTrue(a.associatedFeature().isValid())
        self.assertEqual(a.associatedFeature().attributes()[0], 'hurstbridge')

        a.setMapPosition(QgsPointXY(17, 31))
        self.assertFalse(a.associatedFeature().isValid())
    def testSettingFeature(self):
        """ test that feature is set when item moves """
        a = QgsTextAnnotation()
        a.setFrameSizeMm(QSizeF(300 / 3.7795275, 200 / 3.7795275))
        a.setFrameOffsetFromReferencePointMm(QPointF(40 / 3.7795275, 50 / 3.7795275))
        a.setHasFixedMapPosition(True)
        a.setMapPosition(QgsPointXY(12, 34))
        a.setMapPositionCrs(QgsCoordinateReferenceSystem(4326))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)  # NOQA

        layer = QgsVectorLayer("Point?crs=EPSG:4326&field=station:string&field=suburb:string",
                               'test', "memory")
        canvas.setLayers([layer])
        f = QgsFeature(layer.fields())
        f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(14, 31)))
        f.setValid(True)
        f.setAttributes(['hurstbridge', 'somewhere'])
        self.assertTrue(layer.dataProvider().addFeatures([f]))
        a.setMapLayer(layer)
        self.assertFalse(a.associatedFeature().isValid())

        a.setMapPosition(QgsPointXY(14, 31))
        self.assertTrue(a.associatedFeature().isValid())
        self.assertEqual(a.associatedFeature().attributes()[0], 'hurstbridge')

        a.setMapPosition(QgsPointXY(17, 31))
        self.assertFalse(a.associatedFeature().isValid())
    def testPosition(self):
        """ test that map canvas annotation item syncs position correctly """
        a = QgsTextAnnotation()
        a.setFrameSize(QSizeF(300, 200))
        a.setFrameOffsetFromReferencePoint(QPointF(40, 50))
        a.setMapPosition(QgsPointXY(12, 34))
        a.setMapPositionCrs(QgsCoordinateReferenceSystem(4326))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.show()

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)
        self.assertEqual(canvas.width(), 600)
        self.assertEqual(canvas.height(), 400)

        # test that correct initial position is set
        self.assertAlmostEqual(i.pos().x(), 120, 1)
        self.assertAlmostEqual(i.pos().y(), 110, 1)

        # shift annotation map position, check that item is moved
        a.setMapPosition(QgsPointXY(14, 32))
        self.assertAlmostEqual(i.pos().x(), 240, 1)
        self.assertAlmostEqual(i.pos().y(), 230, 1)

        # check relative position
        a.setHasFixedMapPosition(False)
        a.setRelativePosition(QPointF(0.8, 0.4))
        self.assertAlmostEqual(i.pos().x(), 480, 1)
        self.assertAlmostEqual(i.pos().y(), 160, 1)

        # flicking between relative and fixed position
        a.setHasFixedMapPosition(True)
        self.assertAlmostEqual(i.pos().x(), 240, 1)
        self.assertAlmostEqual(i.pos().y(), 230, 1)
        a.setHasFixedMapPosition(False)
        self.assertAlmostEqual(i.pos().x(), 480, 1)
        self.assertAlmostEqual(i.pos().y(), 160, 1)
    def testSize(self):
        """ test that map canvas annotation item size is correct """
        a = QgsTextAnnotation()
        a.setFrameSizeMm(QSizeF(300 / 3.7795275, 200 / 3.7795275))
        a.setHasFixedMapPosition(False)
        a.setFillSymbol(QgsFillSymbol.createSimple({'color': 'blue', 'width_border': '0'}))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        canvas.show()

        canvas.setExtent(QgsRectangle(10, 30, 20, 35))

        i = QgsMapCanvasAnnotationItem(a, canvas)
        # ugly, but Travis has different default DPI:
        if 299 < i.boundingRect().width() < 301:
            self.assertAlmostEqual(i.boundingRect().width(), 300, 1)
            self.assertAlmostEqual(i.boundingRect().height(), 200, 1)

            a.setHasFixedMapPosition(True)
            a.setFrameOffsetFromReferencePoint(QPointF(0, 0))
            self.assertAlmostEqual(i.boundingRect().width(), 300, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 200, -1)
            a.setFrameOffsetFromReferencePoint(QPointF(10, 20))
            self.assertAlmostEqual(i.boundingRect().width(), 310, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 220, -1)
        else:
            self.assertAlmostEqual(i.boundingRect().width(), 312.5, 1)
            self.assertAlmostEqual(i.boundingRect().height(), 208.33, 1)

            a.setHasFixedMapPosition(True)
            a.setFrameOffsetFromReferencePoint(QPointF(0, 0))
            self.assertAlmostEqual(i.boundingRect().width(), 312.5, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 208.33, -1)
            a.setFrameOffsetFromReferencePoint(QPointF(10, 20))
            self.assertAlmostEqual(i.boundingRect().width(), 322.91, -1)
            self.assertAlmostEqual(i.boundingRect().height(), 229.166, -1)
Example #19
0
    def annotatePredictions(self):
        if self.stationFeature is None:
            return

        a = QgsTextAnnotation()
        a.setMapLayer(self.predictionManager.stationsLayer)

        document = a.document()

        columnWidth = [80, 100, 60]
        columnAlign = ['left', 'left', 'right']

        html = '<font size="+2"><b>'
        html += self.stationFeature['name'] + '<br>' + self.dateEdit.date(
        ).toString() + '<br>'
        html += '</b></font>'
        html += '<font size="+1"><table cellpadding="0" cellspacing="0">'
        html += '<tr>'
        for j in range(0, self.tableWidget.columnCount()):
            html += '<td width="{}"><b>{}</b></td>'.format(
                columnWidth[j],
                self.tableWidget.horizontalHeaderItem(j).text())
        html += '</tr>'

        for i in range(0, self.tableWidget.rowCount()):
            html += '<tr bgcolor="{}">'.format('#FFFFFF' if i %
                                               2 else '#EEEEEE')
            for j in range(0, self.tableWidget.columnCount()):
                html += '<td align="{}" width="{}">{}</td>'.format(
                    columnAlign[j], columnWidth[j],
                    self.tableWidget.item(i, j).text())
            html += '</tr>'

        html += '</table></font>'
        document.setHtml(html)

        # TODO: this size and offset are wack. Can we dynamically calculate from the content somehow?
        a.setFrameSize(QSizeF(270, 300))
        a.setFrameOffsetFromReferencePoint(QPointF(-300, -200))
        a.setMapPosition(self.stationFeature.geometry().asPoint())
        a.setMapPositionCrs(
            QgsCoordinateReferenceSystem(
                self.predictionManager.stationsLayer.crs()))

        # disable its symbol
        for symbol in a.markerSymbol().symbolLayers():
            symbol.setEnabled(False)

        QgsProject.instance().annotationManager().addAnnotation(a)