def append_CharacterMarkerSymbolLayerAsSvg(symbol, layer, context: Context): # pylint: disable=too-many-locals """ Appends a CharacterMarkerSymbolLayer to a symbol, rendering the font character to an SVG file. """ font_family = layer.font character = chr(layer.unicode) color = symbol_color_to_qcolor(layer.color) angle = convert_angle(layer.angle) font = QFont(font_family) font.setPointSizeF(layer.size) # Using the rect of a painter path gives better results then using font metrics path = QPainterPath() path.setFillRule(Qt.WindingFill) path.addText(0, 0, font, character) rect = path.boundingRect() font_bounding_rect = QFontMetricsF(font).boundingRect(character) # adjust size -- marker size in esri is the font size, svg marker size in qgis is the svg rect size scale = rect.width() / font_bounding_rect.width() gen = QSvgGenerator() svg_path = symbol_name_to_filename(context.symbol_name, context.picture_folder, 'svg') gen.setFileName(svg_path) gen.setViewBox(rect) painter = QPainter(gen) painter.setFont(font) # todo -- size! if context.parameterise_svg: painter.setBrush(QBrush(QColor(255, 0, 0))) else: painter.setBrush(QBrush(color)) painter.setPen(Qt.NoPen) painter.drawPath(path) painter.end() if context.parameterise_svg: with open(svg_path, 'r') as f: t = f.read() t = t.replace('#ff0000', 'param(fill)') t = t.replace('fill-opacity="1" ', 'fill-opacity="param(fill-opacity)"') t = t.replace( 'stroke="none"', 'stroke="param(outline)" stroke-opacity="param(outline-opacity) 1" stroke-width="param(outline-width) 0"' ) with open(svg_path, 'w') as f: f.write(t) svg_path = context.convert_path(svg_path) out = QgsSvgMarkerSymbolLayer(svg_path) out.setSizeUnit(context.units) out.setSize(context.convert_size(scale * rect.width())) out.setAngle(angle) out.setFillColor(color) out.setStrokeWidth(0) out.setEnabled(layer.enabled) out.setLocked(layer.locked) out.setOffset( adjust_offset_for_rotation( QPointF(context.convert_size(layer.x_offset), -context.convert_size(layer.y_offset)), layer.angle)) out.setOffsetUnit(context.units) symbol.appendSymbolLayer(out)
def paint(self, painter, option, widget=None): rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2.0, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2.0, ModelerGraphicItem.BOX_WIDTH + 2, ModelerGraphicItem.BOX_HEIGHT + 2) if isinstance(self.element, QgsProcessingModelAlgorithm.ModelParameter): color = QColor(238, 242, 131) stroke = QColor(234, 226, 118) selected = QColor(116, 113, 68) elif isinstance(self.element, QgsProcessingModelAlgorithm.ChildAlgorithm): color = QColor(255, 255, 255) stroke = Qt.gray selected = QColor(50, 50, 50) else: color = QColor(172, 196, 114) stroke = QColor(90, 140, 90) selected = QColor(42, 65, 42) if self.isSelected(): stroke = selected color = color.darker(110) painter.setPen(QPen(stroke, 0)) # 0 width "cosmetic" pen painter.setBrush(QBrush(color, Qt.SolidPattern)) painter.drawRect(rect) font = QFont('Verdana', 8) font.setPixelSize(12) painter.setFont(font) painter.setPen(QPen(Qt.black)) text = self.getAdjustedText(self.text) if isinstance(self.element, QgsProcessingModelAlgorithm.ChildAlgorithm ) and not self.element.isActive(): painter.setPen(QPen(Qt.gray)) text = text + "\n(deactivated)" fm = QFontMetricsF(font) text = self.getAdjustedText(self.text) h = fm.ascent() pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, ModelerGraphicItem.BOX_HEIGHT / 2.0 - h + 1) painter.drawText(pt, text) painter.setPen(QPen(Qt.black)) if isinstance(self.element, QgsProcessingModelAlgorithm.ChildAlgorithm): h = -(fm.height() * 1.2) h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h) painter.drawText(pt, 'In') i = 1 if not self.element.parametersCollapsed(): for param in [ p for p in self.element.algorithm().parameterDefinitions() if not p.isDestination() ]: if not param.flags( ) & QgsProcessingParameterDefinition.FlagHidden: text = self.getAdjustedText(param.description()) h = -(fm.height() * 1.2) * (i + 1) h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h) painter.drawText(pt, text) i += 1 h = fm.height() * 1.1 h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h) painter.drawText(pt, 'Out') if not self.element.outputsCollapsed(): for i, out in enumerate( self.element.algorithm().outputDefinitions()): text = self.getAdjustedText(out.description()) h = fm.height() * 1.2 * (i + 2) h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h) painter.drawText(pt, text) if self.pixmap: painter.drawPixmap(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8, self.pixmap) elif self.picture: painter.drawPicture(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8, self.picture)
def run(self): print ("paso por el run") #coloco el puntero arriba del todo QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint( QgsProject.instance().layerTreeRoot(), 0 ) """Run method that performs all the real work""" #genero una lista con las columnas de la capa de puntos vl2=iface.activeLayer() if vl2 is None: iface.messageBar().pushMessage("ATENCION", "Selecciona una capa de puntos", duration=10) #if vl2.wkbType()< 1 or vl2.wkbType() > 1: #iface.messageBar().pushMessage("ATENCION", "Selecciona una capa de puntos", duration=10) #else: if vl2.wkbType()== 1 or vl2.wkbType()==1001: misdatos=[] misdatos = [f.name() for f in vl2.fields()] #trato de rellenar el desplegable con las columnas #anado un elemneto en blanco en el desplegable self.dlg.cb1.clear() self.dlg.cb1.addItem( "") for element in misdatos: self.dlg.cb1.addItem( element) # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: column = self.dlg.cb1.currentIndex() columna=misdatos[int(column)-1] #parece que lo mejor sera la seleccion de una capa y dentro de ella de los elementos en ella seleccionados solo. Para ello habria que crear una capa temporal con solo los seleccioandos #if vl2.wkbType()== 1 or vl2.wkbType()==1001: selection = vl2.selectedFeatures() elementosseleccionados=len(selection) if elementosseleccionados ==0: vl2.selectAll() if elementosseleccionados ==1 or elementosseleccionados ==2: iface.messageBar().pushMessage("ATENCION", "Tienes algun elemento seleccionado pero no los suficientes para crear un poligono", duration=10) #onlySelectedFeatures results0=processing.run("native:saveselectedfeatures", {'INPUT':vl2,'OUTPUT':'memory:puntos_seleccionados_ptos2pol'}) result_layer0 = results0['OUTPUT'] entrada=result_layer0 QgsProject.instance().addMapLayer(result_layer0) #hay que hacer que cree una columna con el orden el solo por si por defecto no se pone ninguna params={'INPUT':entrada,'GROUP_FIELD':None,'ORDER_FIELD':columna,'DATE_FORMAT':'', 'OUTPUT':'memory:lineas_ptos2pol'} results=processing.run("qgis:pointstopath", params) result_layer = results['OUTPUT'] QgsProject.instance().addMapLayer(result_layer) params={'INPUT':result_layer,'OUTPUT':'memory:poligono_ptos2pol '} results2=processing.run("qgis:linestopolygons", params ) result_layer2 = results2['OUTPUT'] #por el mismo precio calculo la superficie #ADDING NEW FIELD layer_provider=result_layer2.dataProvider() layer_provider.addAttributes([QgsField("hectarea",QVariant.Double, "double", 10, 4)]) result_layer2.updateFields() #UPDATING/ADD ATTRIBUTE VALUE result_layer2.startEditing() features = result_layer2.getFeatures() for f in features: id=f.id() area=f.geometry().area()/10000 fieldindex = result_layer2.dataProvider().fieldNameIndex("hectarea") attr_value={fieldindex:area}#fieldindex, antes era 2 layer_provider.changeAttributeValues({id:attr_value}) result_layer2.commitChanges() #tendra que etiquetar la superficie con dos decimales y cambiar la simbologia, ya que estamos. sym1 = QgsFillSymbol.createSimple({'style': 'vertical','color': '0,0,0,0', 'outline_color': 'red'}) renderer=QgsSingleSymbolRenderer(sym1) #etiqueto layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setSize(12) text_format.setColor(QColor("Red")) layer_settings.setFormat(text_format) layer_settings.fieldName = '''concat(round("hectarea",2),' ha.')''' layer_settings.isExpression = True layer_settings.enabled = True layer_settings = QgsVectorLayerSimpleLabeling(layer_settings) result_layer2.setLabelsEnabled(True) result_layer2.setLabeling(layer_settings) result_layer2.triggerRepaint() result_layer2.setRenderer(renderer) QgsProject.instance().addMapLayer(result_layer2) else: print(vl2.wkbType()) iface.messageBar().pushMessage("ATENCION", "Selecciona una capa de puntos", duration=10)
def __init__(self, parent=None): super(LCDefineDegradationWidget, self).__init__(parent) self.setupUi(self) self.classes = [self.tr("Tree-covered"), self.tr("Grassland"), self.tr("Cropland"), self.tr("Wetland"), self.tr("Artificial"), self.tr("Bare land"), self.tr("Water body")] self.deg_def_matrix.setRowCount(len(self.classes)) self.deg_def_matrix.setColumnCount(len(self.classes)) self.deg_def_matrix.setHorizontalHeaderLabels(self.classes) self.deg_def_matrix.setVerticalHeaderLabels(self.classes) self.trans_matrix_default = [0, -1, -1, -1, -1, -1, 0, # Tree-covered 1, 0, 1, -1, -1, -1, 0, # grassland 1, -1, 0, -1, -1, -1, 0, # cropland -1, -1, -1, 0, -1, -1, 0, # wetland 1, 1, 1, 1, 0, 1, 0, # artificial 1, 1, 1, 1, -1, 0, 0, # Other land 0, 0, 0, 0, 0, 0, 0] # water body for row in range(0, self.deg_def_matrix.rowCount()): for col in range(0, self.deg_def_matrix.columnCount()): line_edit = TransMatrixEdit() line_edit.setValidator(QRegExpValidator(QRegExp("[-0+]"))) line_edit.setAlignment(Qt.AlignHCenter) self.deg_def_matrix.setCellWidget(row, col, line_edit) self.trans_matrix_set() # Setup the vertical label for the rows of the table label_lc_baseline_year = VerticalLabel(self) label_lc_baseline_year.setText(self.tr("Land cover in initial year ")) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label_lc_target_year.sizePolicy().hasHeightForWidth()) label_lc_baseline_year.setSizePolicy(sizePolicy) font = QFont() font.setBold(True) font.setWeight(75) label_lc_baseline_year.setFont(font) self.lc_trans_table_layout.addWidget(label_lc_baseline_year, 1, 0, 1, 1, Qt.AlignCenter) self.deg_def_matrix.setStyleSheet('QTableWidget {border: 0px;}') self.deg_def_matrix.horizontalHeader().setStyleSheet('QHeaderView::section {background-color: white;border: 0px;}') self.deg_def_matrix.verticalHeader().setStyleSheet('QHeaderView::section {background-color: white;border: 0px;}') for row in range(0, self.deg_def_matrix.rowCount()): self.deg_def_matrix.horizontalHeader().setSectionResizeMode(row, QtWidgets.QHeaderView.Stretch) for col in range(0, self.deg_def_matrix.columnCount()): self.deg_def_matrix.verticalHeader().setSectionResizeMode(col, QtWidgets.QHeaderView.Stretch) self.btn_transmatrix_reset.clicked.connect(self.trans_matrix_set) self.btn_transmatrix_loadfile.clicked.connect(self.trans_matrix_loadfile) self.btn_transmatrix_savefile.clicked.connect(self.trans_matrix_savefile) self.legend_deg.setStyleSheet('QLineEdit {background: #AB2727;} QLineEdit:hover {border: 1px solid gray; background: #AB2727;}') self.legend_imp.setStyleSheet('QLineEdit {background: #45A146;} QLineEdit:hover {border: 1px solid gray; background: #45A146;}') self.legend_stable.setStyleSheet('QLineEdit {background: #FFFFE0;} QLineEdit:hover {border: 1px solid gray; background: #FFFFE0;}')
class DrawToolBar(object): NameSpace = getNameSpace() small_pt = 5 white_pen = QPen(Qt.white, small_pt) white_pen.setCapStyle(Qt.RoundCap) black_pen = QPen(Qt.black, small_pt) black_pen.setCapStyle(Qt.RoundCap) glass_pen = QPen(QColor(192, 192, 192, 128), 3) transparent_brush = QBrush(Qt.transparent) black_brush = QBrush(Qt.black) bold_12 = QFont("Arial", 12, QFont.Bold) # Stamp Image confidential = QPixmap.fromImage( QImage(":/imgFMV/images/stamp/confidential.png")) @staticmethod def setValues(options=None): """ Function to set Drawing Values """ s = QSettings() # Magnifier Glass # shape_type = s.value(DrawToolBar.NameSpace + "/Options/magnifier/shape") if shape_type is not None: global TYPE_MAGNIFIER TYPE_MAGNIFIER = shape_type if options is not None: if TYPE_MAGNIFIER == 0: # Square options.rB_Square_m.setChecked(True) else: # Circle options.rB_Circle_m.setChecked(True) mFactor = s.value(DrawToolBar.NameSpace + "/Options/magnifier/factor") if mFactor is not None: global MAX_FACTOR MAX_FACTOR = int(mFactor) if options is not None: options.sb_factor.setValue(MAX_FACTOR) mSize = s.value(DrawToolBar.NameSpace + "/Options/magnifier/size") if mSize is not None: global MAX_MAGNIFIER MAX_MAGNIFIER = int(mSize) if options is not None: options.sl_Size.setValue(MAX_MAGNIFIER) # Drawings # poly_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/width") if poly_w is not None: global PolyWidth PolyWidth = int(poly_w) if options is not None: options.poly_width.setValue(PolyWidth) poly_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/pen") if poly_p is not None: global PolyPen PolyPen = QPen(QColor(poly_p)) PolyPen.setCapStyle(Qt.RoundCap) PolyPen.setWidth(PolyWidth) if options is not None: options.poly_pen.setColor(QColor(poly_p)) poly_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/brush") if poly_b is not None: global PolyBrush PolyBrush = QBrush(QColor(poly_b)) if options is not None: options.poly_brush.setColor(QColor(poly_b)) point_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/width") if point_w is not None: global PointWidth PointWidth = int(point_w) if options is not None: options.point_width.setValue(PointWidth) point_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/pen") if point_p is not None: global PointPen PointPen = QPen(QColor(point_p)) PointPen.setCapStyle(Qt.RoundCap) PointPen.setWidth(PointWidth) if options is not None: options.point_pen.setColor(QColor(point_p)) line_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/width") if line_w is not None: global LineWidth LineWidth = int(line_w) if options is not None: options.lines_width.setValue(LineWidth) line_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/pen") if line_p is not None: global LinePen LinePen = QPen(QColor(line_p)) LinePen.setCapStyle(Qt.RoundCap) LinePen.setWidth(LineWidth) if options is not None: options.lines_pen.setColor(QColor(line_p)) measure_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/width") if measure_w is not None: global MeasureWidth MeasureWidth = int(measure_w) if options is not None: options.measures_width.setValue(MeasureWidth) measure_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/pen") if measure_p is not None: global MeasurePen MeasurePen = QPen(QColor(measure_p)) MeasurePen.setCapStyle(Qt.RoundCap) MeasurePen.setWidth(MeasureWidth) if options is not None: options.measures_pen.setColor(QColor(measure_p)) measure_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/brush") if measure_b is not None: global MeasureBrush MeasureBrush = QBrush(QColor(measure_b)) if options is not None: options.measures_brush.setColor(QColor(measure_b)) return @staticmethod def drawOnVideo( drawPtPos, drawLines, drawPolygon, drawMDistance, drawMArea, drawCesure, painter, surface, gt, ): """ Function to paint over the video """ # Draw clicked points on video for position, pt in enumerate(drawPtPos): DrawToolBar.drawPointOnVideo(position + 1, pt, painter, surface, gt) # Draw clicked lines on video if len(drawLines) > 1: for idx, pt in enumerate(drawLines): if pt[0] is None: continue else: DrawToolBar.drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines) # Draw clicked Polygons on video if len(drawPolygon) > 1: poly = [] if any(x[1] is None for x in drawPolygon): for pt in drawPolygon: if pt[0] is None: DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len(drawPolygon) - drawPolygon[::-1].index( [None, None, None]) poly = [] for pt in range(last_occurence, len(drawPolygon)): poly.append(drawPolygon[pt]) if len(poly) > 1: DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt) else: DrawToolBar.drawPolygonOnVideo(drawPolygon, painter, surface, gt) # Draw Measure Distance on video # the measures don't persist in the video if len(drawMDistance) > 1: DrawToolBar.resetMeasureDistance() for idx, pt in enumerate(drawMDistance): if pt[0] is None: DrawToolBar.resetMeasureDistance() continue else: DrawToolBar.drawMeasureDistanceOnVideo( pt, idx, painter, surface, gt, drawMDistance) # Draw Measure Area on video # the measures don't persist in the video if len(drawMArea) > 1: poly = [] if any(x[1] is None for x in drawMArea): for pt in drawMArea: if pt[0] is None: DrawToolBar.drawMeasureAreaOnVideo( poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len(drawMArea) - drawMArea[::-1].index( [None, None, None]) poly = [] for pt in range(last_occurence, len(drawMArea)): poly.append(drawMArea[pt]) if len(poly) > 1: DrawToolBar.drawMeasureAreaOnVideo(poly, painter, surface, gt) else: DrawToolBar.drawMeasureAreaOnVideo(drawMArea, painter, surface, gt) # Draw Censure if drawCesure: DrawToolBar.drawCensuredOnVideo(painter, drawCesure) return return @staticmethod def drawPointOnVideo(number, pt, painter, surface, gt): """ Draw Points on Video """ scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) # don't draw something outside the screen. if scr_x < vut.GetXBlackZone(surface) or scr_y < vut.GetYBlackZone( surface): return if scr_x > vut.GetXBlackZone(surface) + vut.GetNormalizedWidth( surface) or scr_y > vut.GetYBlackZone( surface) + vut.GetNormalizedHeight(surface): return center = QPoint(scr_x, scr_y) painter.setPen(PointPen) painter.drawPoint(center) painter.setFont(DrawToolBar.bold_12) painter.drawText(center + QPoint(5, -5), str(number)) return @staticmethod def drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines): """ Draw Lines on Video """ scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) painter.setPen(LinePen) if len(drawLines) > 1: try: pt = drawLines[idx + 1] scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) # Draw Start/End Points painter.setPen(DrawToolBar.white_pen) painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawPolygonOnVideo(values, painter, surface, gt): """ Draw Polygons on Video """ poly = [] for pt in values: scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setPen(PolyPen) painter.drawPolygon(polygon) painter.fillPath(path, PolyBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) return @staticmethod def resetMeasureDistance(): global RulerTotalMeasure RulerTotalMeasure = 0.0 @staticmethod def drawMeasureDistanceOnVideo(pt, idx, painter, surface, gt, drawMDistance): """ Draw Measure Distance on Video """ global RulerTotalMeasure scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) if len(drawMDistance) > 1: try: painter.setPen(MeasurePen) end_pt = drawMDistance[idx + 1] scr_x, scr_y = vut.GetInverseMatrix(end_pt[1], end_pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) painter.setFont(DrawToolBar.bold_12) initialPoint = QgsPointXY(pt[0], pt[1]) destPoint = QgsPointXY(end_pt[0], end_pt[1]) da = QgsDistanceArea() da.setEllipsoid(WGS84String) m = da.measureLine(initialPoint, destPoint) distance = round(m, 2) text = str(distance) + " m" # Sum values to total distance RulerTotalMeasure += distance # Line lenght painter.setPen(MeasurePen) painter.drawText(end + QPoint(5, -10), text) painter.setPen(DrawToolBar.white_pen) # Total lenght painter.drawText(end + QPoint(5, 10), str(round(RulerTotalMeasure, 2)) + " m") # Draw Start/End Points painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawMeasureAreaOnVideo(values, painter, surface, gt): """ Draw Measure Area on Video """ da = QgsDistanceArea() da.setEllipsoid(WGS84String) points = [] poly = [] for pt in values: scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) points.append(QgsPointXY(pt[1], pt[0])) # Create Video Polygon polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setFont(DrawToolBar.bold_12) painter.setPen(MeasurePen) painter.drawPolygon(polygon) painter.fillPath(path, MeasureBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) # Create QGIS Polygon mapPolygon = QgsGeometry.fromPolygonXY([points]) # Calculate polygon area area = da.measureArea(mapPolygon) try: ctr = mapPolygon.centroid().asPoint() # Calculate Centroid Position scr_x, scr_y = vut.GetInverseMatrix(ctr.x(), ctr.y(), gt, surface) centroid = QPoint(scr_x, scr_y) # Area if area >= 10000: painter.drawText( centroid, str(round(da.convertAreaMeasurement(area, 1), 2)) + " km²") else: painter.drawText(centroid, str(round(area, 2)) + " m²") except Exception: None return @staticmethod def drawCensuredOnVideo(painter, drawCesure): """ Draw Censure on Video """ try: for geom in drawCesure: painter.setPen(DrawToolBar.black_pen) painter.setBrush(DrawToolBar.black_brush) painter.drawRect(geom[0].x(), geom[0].y(), geom[0].width(), geom[0].height()) except Exception: None return @staticmethod def drawMagnifierOnVideo(widget, dragPos, source, painter): """ Draw Magnifier on Video """ oldTransform = painter.transform() painter.setTransform(oldTransform) painter.setBrush(DrawToolBar.transparent_brush) dim = min(widget.width(), widget.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) center = dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * MAX_FACTOR - QPoint(radius, radius) # only set the dimension to the magnified portion zoomPixmap = QPixmap(box) zoomPixmap.fill(Qt.black) painter_p = QPainter(zoomPixmap) painter_p.setRenderHint(QPainter.HighQualityAntialiasing) painter_p.translate(-xy) painter_p.scale(MAX_FACTOR, MAX_FACTOR) painter_p.drawImage(widget.surface.videoRect(), source, widget.surface.sourceRect()) painter_p.end() clipPath = QPainterPath() center = QPointF(center) # Shape Type if TYPE_MAGNIFIER == 0: # Square clipPath.addRect(center.x(), center.y(), magnifierSize, magnifierSize) clipPath.translate(-radius, -radius) else: # Circle clipPath.addEllipse(center, ring, ring) painter.setClipPath(clipPath) painter.drawPixmap(corner, zoomPixmap) painter.setPen(DrawToolBar.glass_pen) painter.drawPath(clipPath) return @staticmethod def drawStampOnVideo(widget, painter): """ Draw Stamp Confidential on Video """ painter.drawPixmap( widget.surface.videoRect(), DrawToolBar.confidential, widget.surface.sourceRect(), )
def setupTableTab(self, model1): #*********************** TAble tab ************************************************* try: #Reinitializing the table tab self.VLayout = self.dockwidget.scrollAreaWidgetContents.layout() while 1: child = self.VLayout.takeAt(0) if not child: break child.widget().deleteLater() except: self.VLayout = QVBoxLayout(self.dockwidget.scrollAreaWidgetContents) self.VLayout.setContentsMargins(9, -1, -1, -1) #Setup the table tab self.groupBox = [] self.profilePushButton = [] self.tableView = [] self.verticalLayout = [] for i in range(0 , model1.rowCount()): self.groupBox.append( QGroupBox(self.dockwidget.scrollAreaWidgetContents) ) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox[i].sizePolicy().hasHeightForWidth()) self.groupBox[i].setSizePolicy(sizePolicy) self.groupBox[i].setMinimumSize(QSize(0, 150)) self.groupBox[i].setMaximumSize(QSize(16777215, 350)) self.groupBox[i].setTitle(QApplication.translate("GroupBox" + str(i), self.profiles[i]["layer"].name(), None)) self.groupBox[i].setObjectName("groupBox" + str(i)) self.verticalLayout.append( QVBoxLayout(self.groupBox[i]) ) self.verticalLayout[i].setObjectName("verticalLayout") #The table self.tableView.append( QTableView(self.groupBox[i]) ) self.tableView[i].setObjectName("tableView" + str(i)) font = QFont("Arial", 8) columns = len(self.profiles[i]["l"]) rowNames = list(self.profiles[i].keys()) rowNames.remove("layer") # holds the QgsMapLayer instance rowNames.remove("l") # holds the band number rows = len(rowNames) self.mdl = QStandardItemModel(rows+1, columns) self.mdl.setVerticalHeaderLabels(["band"] + rowNames) for j in range(columns): self.mdl.setData(self.mdl.index(0, j, QModelIndex()), str(self.profiles[i]["l"][j])) self.mdl.setData(self.mdl.index(0, j, QModelIndex()), font ,Qt.FontRole) for k in range(rows): self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), str(self.profiles[i][rowNames[k]][j])) self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), font ,Qt.FontRole) #self.tableView[i].setVerticalHeaderLabels(rowNames) self.tableView[i].verticalHeader().setDefaultSectionSize(18) self.tableView[i].horizontalHeader().setDefaultSectionSize(60) self.tableView[i].setModel(self.mdl) self.verticalLayout[i].addWidget(self.tableView[i]) self.horizontalLayout = QHBoxLayout() #the copy to clipboard button self.profilePushButton.append( QPushButton(self.groupBox[i]) ) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.profilePushButton[i].sizePolicy().hasHeightForWidth()) self.profilePushButton[i].setSizePolicy(sizePolicy) self.profilePushButton[i].setText(QApplication.translate("GroupBox", "Copy to clipboard", None)) self.profilePushButton[i].setObjectName(str(i)) self.horizontalLayout.addWidget(self.profilePushButton[i]) self.horizontalLayout.addStretch(0) self.verticalLayout[i].addLayout(self.horizontalLayout) self.VLayout.addWidget(self.groupBox[i]) self.profilePushButton[i].clicked.connect(self.copyTable)
def setComposerTemplates(self, comptecommunal): """ Set parameters for given comptecommunal """ # List of templates comptecommunalAbrev = comptecommunal[9:] self.composerTemplates = { 'header1': { 'names': ['annee', 'ccodep', 'ccodir', 'ccocom', 'libcom'], 'position': [3.5, 2.5, 145, 7.5], 'align': [128, 4], 'keepContent': True, 'type': 'sql', 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND comptecommunal = '%s'" % comptecommunal }, 'sticky': True }, 'header2': { 'names': ['type'], 'position': [153.5, 2.5, 60, 7.5], 'align': [128, 4], 'keepContent': True, 'type': 'properties', 'source': [self.typeLabel], 'sticky': True }, 'header3': { 'names': ['comptecommunal'], 'position': [218.5, 2.5, 75, 7.5], 'align': [128, 2], 'keepContent': True, 'type': 'properties', 'source': [comptecommunalAbrev], 'sticky': True }, 'proprietaires': { 'names': ['lines'], 'position': [3.5, 10, 290, 40], 'align': [32, 1], 'keepContent': False, 'type': 'parent', 'source': 'proprietaires_line' }, 'proprietes_baties': { 'names': ['lines'], 'position': [3.5, 50, 290, 65], 'align': [32, 1], 'keepContent': False, 'type': 'parent', 'source': 'proprietes_baties_line' }, 'proprietes_baties_sum': { 'names': [ 'revenucadastral', 'co_vlbaia', 'co_bipevla', 'gp_vlbaia', 'gp_bipevla', 'de_vlbaia', 'de_bipevla', 're_vlbaia', 're_bipevla' ], 'position': [3.5, 115, 290, 15], 'align': [32, 1], 'type': 'sql', 'keepContent': True, 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND l10.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle } }, 'proprietes_non_baties': { 'names': ['lines'], 'position': [3.5, 130, 290, 65], 'align': [32, 1], 'keepContent': False, 'type': 'parent', 'source': 'proprietes_non_baties_line' }, 'proprietes_non_baties_sum': { 'names': [ 'sum_ha_contenance', 'sum_a_contenance', 'sum_ca_contenance', 'sum_drcsuba' ], 'position': [3.5, 195, 290, 13], 'align': [32, 1], 'type': 'sql', 'keepContent': True, 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND p.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle }, 'bgcolor': Qt.transparent }, 'footer': { 'names': ['foot'], 'position': [3.5, 208, 288, 4], 'align': [128, 4], 'keepContent': True, 'type': 'properties', 'source': [ u"Ce document est donné à titre indicatif - Il n'a pas de valeur légale" ], 'bgcolor': Qt.white, 'htmlState': 0, 'font': QFont('sans-serif', 4, 1, True), 'sticky': True } } self.mainTables = { 'proprietaires_line': { 'names': ['mainprop', 'epousede', 'adrprop', 'nele'], 'type': 'sql', 'keepContent': True, 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND comptecommunal = '%s'" % comptecommunal } }, 'proprietes_baties_line': { 'names': [ 'section', 'ndeplan', 'ndevoirie', 'adresse', 'coderivoli', 'bat', 'ent', 'niv', 'ndeporte', 'numeroinvar', 'star', 'meval', 'af', 'natloc', 'cat', 'revenucadastral', 'coll', 'natexo', 'anret', 'andeb', 'fractionrcexo', 'pourcentageexo', 'txom', 'coefreduc' ], 'type': 'sql', 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND l10.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle } }, 'proprietes_non_baties_line': { 'names': [ 'section', 'ndeplan', 'ndevoirie', 'adresse', 'coderivoli', 'nparcprim', 'fpdp', 'star', 'suf', 'grssgr', 'cl', 'natcult', 'ha_contenance', 'a_contenance', 'ca_contenance', 'revenucadastral', 'coll', 'natexo', 'anret', 'fractionrcexo', 'pourcentageexo', 'tc', 'lff' ], 'type': 'sql', 'and': { 'proprietaire': u" AND p.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle } } } # items for which to count number of lines self.lineCount = { 'proprietes_baties_line': { 'count': 0, 'data': None }, 'proprietes_non_baties_line': { 'count': 0, 'data': None } } # items for which not the run a query for each page # but only once and keep content for next pages self.contentKeeped = {} for key, item in list(self.composerTemplates.items()): if 'keepContent' in item and item['keepContent']: self.contentKeeped[key] = '' for key, item in list(self.mainTables.items()): if 'keepContent' in item and item['keepContent']: self.contentKeeped[key] = ''
def restoreSettings(self): settings = QgsSettings() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.spinBox.setValue(settings.value("pythonConsole/fontsize", font.pointSize(), type=int)) self.spinBoxEditor.setValue(settings.value("pythonConsole/fontsizeEditor", font.pointSize(), type=int)) self.fontComboBox.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytext", font.family()))) self.fontComboBoxEditor.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytextEditor", font.family()))) self.preloadAPI.setChecked(settings.value("pythonConsole/preloadAPI", True, type=bool)) self.lineEdit.setText(settings.value("pythonConsole/preparedAPIFile", "", type=str)) itemTable = settings.value("pythonConsole/userAPI", []) if itemTable: self.tableWidget.setRowCount(0) for i in range(len(itemTable)): self.tableWidget.insertRow(i) self.tableWidget.setColumnCount(2) pathSplit = itemTable[i].split("/") apiName = pathSplit[-1][0:-4] self.tableWidget.setItem(i, 0, QTableWidgetItem(apiName)) self.tableWidget.setItem(i, 1, QTableWidgetItem(itemTable[i])) self.autoSaveScript.setChecked(settings.value("pythonConsole/autoSaveScript", False, type=bool)) self.autoCompThreshold.setValue(settings.value("pythonConsole/autoCompThreshold", 2, type=int)) self.autoCompThresholdEditor.setValue(settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int)) self.groupBoxAutoCompletionEditor.setChecked( settings.value("pythonConsole/autoCompleteEnabledEditor", True, type=bool)) self.groupBoxAutoCompletion.setChecked(settings.value("pythonConsole/autoCompleteEnabled", True, type=bool)) self.enableObjectInspector.setChecked(settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.autoCloseBracketEditor.setChecked(settings.value("pythonConsole/autoCloseBracketEditor", False, type=bool)) self.autoCloseBracket.setChecked(settings.value("pythonConsole/autoCloseBracket", False, type=bool)) self.autoInsertionImportEditor.setChecked( settings.value("pythonConsole/autoInsertionImportEditor", True, type=bool)) self.autoInsertionImport.setChecked(settings.value("pythonConsole/autoInsertionImport", True, type=bool)) if settings.value("pythonConsole/autoCompleteSource") == 'fromDoc': self.autoCompFromDoc.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromAPI': self.autoCompFromAPI.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromDocAPI': self.autoCompFromDocAPI.setChecked(True) if settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDoc': self.autoCompFromDocEditor.setChecked(True) elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromAPI': self.autoCompFromAPIEditor.setChecked(True) elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDocAPI': self.autoCompFromDocAPIEditor.setChecked(True) # Setting font lexer color self.defaultFontColor.setColor(QColor(settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.defaultFontColorEditor.setColor( QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(Qt.black)))) self.keywordFontColor.setColor(QColor(settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen)))) self.keywordFontColorEditor.setColor( QColor(settings.value("pythonConsole/keywordFontColorEditor", QColor(Qt.darkGreen)))) self.classFontColor.setColor(QColor(settings.value("pythonConsole/classFontColor", QColor(Qt.blue)))) self.classFontColorEditor.setColor( QColor(settings.value("pythonConsole/classFontColorEditor", QColor(Qt.blue)))) self.methodFontColor.setColor(QColor(settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray)))) self.methodFontColorEditor.setColor( QColor(settings.value("pythonConsole/methodFontColorEditor", QColor(Qt.darkGray)))) self.decorFontColor.setColor(QColor(settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue)))) self.decorFontColorEditor.setColor( QColor(settings.value("pythonConsole/decorFontColorEditor", QColor(Qt.darkBlue)))) self.commentFontColor.setColor(QColor(settings.value("pythonConsole/commentFontColor", QColor(Qt.gray)))) self.commentFontColorEditor.setColor( QColor(settings.value("pythonConsole/commentFontColorEditor", QColor(Qt.gray)))) self.commentBlockFontColor.setColor( QColor(settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray)))) self.commentBlockFontColorEditor.setColor( QColor(settings.value("pythonConsole/commentBlockFontColorEditor", QColor(Qt.gray)))) self.paperBackgroundColor.setColor( QColor(settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))) self.paperBackgroundColorEditor.setColor( QColor(settings.value("pythonConsole/paperBackgroundColorEditor", QColor(Qt.white)))) self.caretLineColor.setColor(QColor(settings.value("pythonConsole/caretLineColor", QColor("#fcf3ed")))) self.caretLineColorEditor.setColor( QColor(settings.value("pythonConsole/caretLineColorEditor", QColor("#fcf3ed")))) self.cursorColor.setColor(QColor(settings.value("pythonConsole/cursorColor", QColor(Qt.black)))) self.cursorColorEditor.setColor(QColor(settings.value("pythonConsole/cursorColorEditor", QColor(Qt.black)))) self.stderrFontColor.setColor(QColor(settings.value("pythonConsole/stderrFontColor", QColor(Qt.red)))) self.singleQuoteFontColor.setColor(settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))) self.singleQuoteFontColorEditor.setColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(Qt.blue))) self.doubleQuoteFontColor.setColor(settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))) self.doubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(Qt.blue))) self.tripleSingleQuoteFontColor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))) self.tripleSingleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColorEditor", QColor(Qt.blue))) self.tripleDoubleQuoteFontColor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))) self.tripleDoubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(Qt.blue)))
def CreatePDF(self, task, out, timestamp, data, frame, rows, columns, fileName, VManager): """ Create PDF QgsTask """ font_normal = QFont("Helvetica", 8, QFont.Normal) font_bold = QFont("Helvetica", 9, QFont.Bold) printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) printer.setOutputFileName(out) printer.setFullPage(True) document = QTextDocument() document.setDefaultFont(font_normal) document.setPageSize(printer.paperSize(QPrinter.Point)) cursor = QTextCursor(document) video_t = QCoreApplication.translate("QgsFmvMetadata", "Video : ") time_t = QCoreApplication.translate("QgsFmvMetadata", "TimeStamp : ") cursor.insertHtml(""" <p style='text-align: center;'> <img style='display: block; margin-left: auto; margin-right: auto;' src=\':/imgFMV/images/header_logo.png\' width='200' height='25' /> <p style='text-align: center;'> <strong>%s</strong>%s<strong> <p style='text-align: center;'> <strong>%s</strong>%s <p></p> """ % (video_t, fileName, time_t, timestamp)) tableFormat = QTextTableFormat() tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setHeaderRowCount(1) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(2) cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setFont(font_bold) tableHeaderFormat.setBackground(QColor("#67b03a")) tableHeaderFormat.setForeground(Qt.white) tableHeaderFormat.setVerticalAlignment(QTextCharFormat.AlignMiddle) alternate_background = QTextCharFormat() alternate_background.setBackground(QColor("#DDE9ED")) for column in range(columns): cursor.mergeBlockCharFormat(tableHeaderFormat) cursor.insertText(VManager.horizontalHeaderItem(column).text()) cursor.movePosition(QTextCursor.NextCell) row = 1 for key in sorted(data.keys()): values = [str(key), str(data[key][0]), str(data[key][1])] for column in range(columns): cursor.insertText(values[column]) if (row) % 2 == 0: cursor.mergeBlockCharFormat(alternate_background) cursor.movePosition(QTextCursor.NextCell) row += 1 cursor.movePosition(QTextCursor.End) current_t = QCoreApplication.translate("QgsFmvMetadata", "Current Frame") self.TextBlockCenter(cursor, TextFormat=QTextFormat.PageBreak_AlwaysBefore) cursor.insertHtml(""" <br><p style='text-align: center;'><strong>""" + current_t + """</strong></p><br> """) self.TextBlockCenter(cursor) cursor.insertImage(frame.scaledToWidth(500, Qt.SmoothTransformation)) document.print_(printer) if task.isCanceled(): return None return {"task": task.description()}
def setupUi(self): self.resize(550, 550) self.setWindowTitle('Settings') #create tabWidget that holds the tabs self.tabWidget = QtGui.QTabWidget(self) self.tabWidget.setGeometry(QRect(10, 20, 500, 480)) self.tabWidget.setObjectName('tabWidget') tab0labels = [['Name', (50, 50, 56, 17)], ['Description', (50, 100, 70, 25)], ['Language', (50, 150, 56, 17)]] tab1labels = [[ 'Which tools/ buttons shall be activated in the application:', (50, 25, 56, 17) ]] tab2labels = [['Center:', (50, 50, 70, 17)], ['X:', (160, 53, 10, 10)], ['Y:', (320, 53, 10, 10)], ['Zoom:', (50, 100, 70, 17)], ['Extent:', (50, 363, 70, 17)], ['MinX:', (132, 367, 40, 17)], ['MinY:', (222, 327, 40, 17)], ['MaxX:', (306, 367, 40, 17)], ['MaxY:', (222, 407, 40, 17)]] tab3labels = [['All Layers', (90, 40, 80, 30)], ['Layer Tree', (325, 40, 80, 30)]] tab4labels = [['Users', (100, 10, 50, 20)], ['Groups', (320, 10, 50, 20)]] tabwidgets = [['General', tab0labels], ['Tools', tab1labels], ['Homeview', tab2labels], ['Layer', tab3labels], ['Permissions', tab4labels]] #first set the labes for all tabwwidgets in a loop: for tab in tabwidgets: t = QtGui.QWidget() t.setObjectName(tab[0]) self.tabs.append(t) self.tabWidget.addTab(t, tab[0]) for label in tab[1]: l = QtGui.QLabel(t) l.setText(label[0]) l.setGeometry( QRect(label[1][0], label[1][1], label[1][2], label[1][3])) if (tab[0] == 'Layer'): font = QFont('Arial', 12) font.setBold(True) l.setFont(font) self.tabWidget.setCurrentIndex(0) #then populate the specific tabwidgets with other QObjects: #tab 0 = 'General': self.nameEdit = QtGui.QLineEdit(self.tabs[0]) self.nameEdit.setGeometry(QRect(250, 40, 150, 27)) self.tabedits.append(self.nameEdit) self.descriptionEdit = QtGui.QLineEdit(self.tabs[0]) self.descriptionEdit.setGeometry(QRect(250, 90, 150, 27)) self.tabedits.append(self.descriptionEdit) self.languageBox = QtGui.QComboBox(self.tabs[0]) self.languageBox.setGeometry(QRect(250, 140, 113, 27)) self.languageBox.addItems(['en', 'de']) self.tabedits.append(self.languageBox) self.boxPublic = QtGui.QCheckBox(self.tabs[0]) self.boxPublic.setGeometry(QRect(250, 180, 80, 17)) self.boxPublic.setText('Public') self.tabboxes.append(self.boxPublic) self.boxActive = QtGui.QCheckBox(self.tabs[0]) self.boxActive.setGeometry(QRect(250, 230, 80, 17)) self.boxActive.setText('Active') self.tabboxes.append(self.boxActive) #tab 1 = 'Tools': toollist = [ 'Zoom in button', 'Zoom out button', 'Zoom to extent button', 'Step back to previous extent button', 'Step forward to next extent button', 'Activate hover-select tool', 'Print button', 'Show measure tools button', 'Show redlining tools button', 'Show workstate tools button', 'Show addwms tools button', 'Show meta toolbar button' ] y = 50 self.tools = {} # a dictonary with toolbutton id as key and reference to the QCheckBox # as value, i.e.: {58: -Reference to QCheckBox Object-} tcount = 57 for tool in toollist: t = QtGui.QCheckBox(self.tabs[1]) t.setGeometry(QRect(60, y, 180, 17)) t.setText(tool) self.tools[tcount] = t y += 30 tcount += 1 #tab 2 = 'Homeview': self.homeviewCenterEditX = QtGui.QLineEdit(self.tabs[2]) self.homeviewCenterEditX.setGeometry(QRect(170, 50, 125, 25)) self.tabedits.append(self.homeviewCenterEditX) self.homeviewCenterEditY = QtGui.QLineEdit(self.tabs[2]) self.homeviewCenterEditY.setGeometry(QRect(330, 50, 125, 25)) self.tabedits.append(self.homeviewCenterEditY) self.homeviewZoomBox = QtGui.QSpinBox(self.tabs[2]) self.homeviewZoomBox.setGeometry(QRect(170, 100, 40, 25)) self.moreObjects.append(self.homeviewZoomBox) self.extentEdits = [] minX = QtGui.QLineEdit(self.tabs[2]) minX.setGeometry(175, 360, 120, 25) self.extentEdits.append(minX) minY = QtGui.QLineEdit(self.tabs[2]) minY.setGeometry(265, 320, 120, 25) self.extentEdits.append(minY) maxX = QtGui.QLineEdit(self.tabs[2]) maxX.setGeometry(350, 360, 120, 25) self.extentEdits.append(maxX) maxY = QtGui.QLineEdit(self.tabs[2]) maxY.setGeometry(265, 400, 120, 25) self.extentEdits.append(maxY) style = 'QLineEdit { background-color : #a6a6a6; color : white; }' for edit in self.extentEdits: edit.setReadOnly(True) edit.lower() edit.setStyleSheet(style) self.origExtentButton = QtGui.QPushButton(self.tabs[2]) self.origExtentButton.setGeometry(100, 150, 190, 30) self.origExtentButton.setText('Set original homview') self.moreObjects.append(self.origExtentButton) self.qgsExtentButton = QtGui.QPushButton(self.tabs[2]) self.qgsExtentButton.setGeometry(290, 150, 190, 30) self.qgsExtentButton.setText('Set current QGIS view') self.moreObjects.append(self.qgsExtentButton) self.homeviewEpsgWarning = QtGui.QLabel(self.tabs[2]) self.homeviewEpsgWarning.setGeometry(QRect(50, 220, 435, 80)) self.homeviewEpsgWarning.setFont(QFont('Arial', 9)) self.jumpButtonOrig = QtGui.QPushButton(self.tabs[2]) self.jumpButtonOrig.setGeometry(QRect(115, 192, 160, 20)) self.jumpButtonOrig.setText('Jump to original homeview') self.jumpButtonOrig.setStyleSheet( 'QPushButton { background-color : #a6a6a6; color : white; }') self.jumpButtonNew = QtGui.QPushButton(self.tabs[2]) self.jumpButtonNew.setGeometry(QRect(305, 192, 160, 20)) self.jumpButtonNew.setText('Jump to new homeview') self.moreObjects.append(self.jumpButtonNew) #tab 3 = 'Layer' (layertree) self.layerlistwidget = LayerListWidget(self.tabs[3]) self.layerlistwidget.setGeometry(QRect(25, 70, 210, 350)) self.layertreewidget = LayerTreeWidget(self.tabs[3]) self.layertreewidget.setGeometry(QRect(260, 70, 210, 350)) #tab 4 = 'Permissions' self.usertabel = QtGui.QTableWidget(self.tabs[4]) self.usertabel.setGeometry(QRect(10, 30, 230, 300)) self.usertabel.setColumnCount(3) self.usertabel.setHorizontalHeaderLabels(['Read', 'Update', 'Delete']) self.moreObjects.append(self.usertabel) self.groupstabel = QtGui.QTableWidget(self.tabs[4]) self.groupstabel.setGeometry(QRect(250, 30, 230, 300)) self.groupstabel.setColumnCount(3) self.groupstabel.setHorizontalHeaderLabels( ['Read', 'Update', 'Delete']) self.moreObjects.append(self.groupstabel) #create Gui surrounding the tabs self.editCheckBox = QtGui.QCheckBox(self) self.editCheckBox.setGeometry(QRect(420, 10, 50, 17)) self.editCheckBox.setText('Edit') self.pushButtonOk = QtGui.QPushButton(self) self.pushButtonOk.setGeometry(QRect(420, 500, 85, 27)) self.pushButtonCancel = QtGui.QPushButton(self) self.pushButtonCancel.setGeometry(QRect(320, 500, 85, 27)) self.pushButtonCancel.setText('Cancel') self.warnLabel = QtGui.QLabel(self) self.warnLabel.setGeometry(QRect(300, 505, 80, 15)) self.warnLabel.setText('Please fill out all mandatory fields') self.warnLabel.setHidden(True) self.warnLabel.setStyleSheet('QLabel { color : #ff6666; }')
def run(self): global almacen #coloco el puntero arriba del todo QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint( QgsProject.instance().layerTreeRoot(), 0) #genero una lista con los sistemas de referencia misdatos = [["Etrs89 Zona30 (25830)", "25830"], ["Etrs89 Zona29 (25829)", "25829"], ["ED50 Zona30 (23030)", "23030"], ["ED50_Zona29 (23029)", "23029"], ["WGS84 geograficas sexagesimales(4326)", "4326"], ["WGS84 geograficas centesimales(4326)", "4258"]] self.dlg.comboBox_src.clear() for element in misdatos: self.dlg.comboBox_src.addItem(element[0]) """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False #leo la cache rutacache = os.path.join(QgsApplication.qgisSettingsDirPath(), r"python\plugins\zoomSigmena\cache.txt") if os.path.isfile(rutacache) == True: filecache = open(rutacache, "r") filecacheleido = filecache.readlines() try: import ast almacen = ast.literal_eval((filecacheleido[0].replace( '\n', '')).replace(" [[", "[[").replace("]] ", "]]")) #.split(',')) cache_utm = int(almacen[0]) cache_geo = int(almacen[1]) cache_escala = almacen[2] print(cache_escala) print(almacen) #miscomarcas=(filecacheleido[3].replace('\n','')).strip('][').split(',') #convierto una str en una list #mismunicipios=ast.literal_eval((filecacheleido[4].replace('\n','')).replace(" [[","[[").replace("]] ","]]"))#.split(',')) #convierto una str en una list filecache.close() except: print("esta no encuentra el file cache") self.dlg.lineEdit_escala.setText(str(cache_escala)) self.dlg.checkBox_utm.setChecked(cache_utm) self.dlg.checkBox_geo.setChecked(cache_geo) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. def deg_to_dms(deg, type='lat'): decimals, number = math.modf(deg) d = int(number) m = int(decimals * 60) s = (deg - d - m / 60) * 3600.00 compass = {'lat': ('N', 'S'), 'lon': ('E', 'W')} compass_str = compass[type][0 if d >= 0 else 1] return '{}º{}\'{:.2f}"{}'.format(abs(d), abs(m), abs(s), compass_str) #saco de aqui variables que estan en las cajitas src_seleccionado = self.dlg.comboBox_src.currentIndex() # Get the coordinates and scale factor from the dialog x = self.dlg.XX.text() ##displayText() y = self.dlg.YY.text() ##displayText() escala = self.dlg.lineEdit_escala.text() x = x.replace(',', '.') y = y.replace(',', '.') escala = int(escala.replace('.', '')) src = misdatos[int(src_seleccionado)][1] if src == "4326": latext = y longtext = x lag = float(latext.split()[0]) lam = float(latext.split()[1]) las = float(latext.split()[2]) log = float(longtext.split()[0]) lom = float(longtext.split()[1]) los = float(longtext.split()[2]) lon = -1 * (log + (lom / 60) + (los / 3600)) lat = lag + (lam / 60) + (las / 3600) x = float(lon) y = float(lat) print(x) print(y) huso = 30 destinoProj = pyproj.Proj(proj="utm", zone=huso, ellps="WGS84", units="m") origenProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') UTM_X, UTM_Y = pyproj.transform(origenProj, destinoProj, lon, lat) if src == "4258": print("por el camino adecuado") lat = float(y) lonn = float(x) lon = -1.0 * lonn print(lat) print(lon) huso = 30 destinoProj = pyproj.Proj(proj="utm", zone=huso, ellps="WGS84", units="m") origenProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') UTM_X, UTM_Y = pyproj.transform(origenProj, destinoProj, lon, lat) print(UTM_X) print(UTM_Y) x = lon y = lat #creo una capa temporal con las coordenadas # create layer vl2 = QgsVectorLayer("Point?crs=EPSG:" + src, "Zoom", "memory") pr2 = vl2.dataProvider() vl2.startEditing() # add fields pr2.addAttributes([ QgsField("x", QVariant.Double), QgsField("y", QVariant.Double), QgsField("xx", QVariant.String), QgsField("yy", QVariant.String), QgsField("xxx", QVariant.Double), QgsField("yyy", QVariant.Double) ]) vl2.updateFields() # tell the vector layer to fetch changes from the provider #$add a feature fet = QgsFeature() print("punto") print(x) print(y) fet.setGeometry( QgsGeometry.fromPointXY(QgsPointXY(float(x), float(y)))) if src == "25830": huso = 30 origenProj = pyproj.Proj(proj="utm", zone=huso, ellps="WGS84", units="m") destinoProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y) xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) if src == "25829": huso = 29 origenProj = pyproj.Proj(proj="utm", zone=huso, ellps="WGS84", units="m") destinoProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y) xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) if src == "23030": huso = 30 origenProj = pyproj.Proj(proj="utm", zone=huso, ellps="intl", units="m") destinoProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y) xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) if src == "23029": huso = 29 origenProj = pyproj.Proj(proj="utm", zone=huso, ellps="intl", units="m") destinoProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y) xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) #para que lo pase a utms en pantalla if src == "4326": x = int(UTM_X) y = int(UTM_Y) #xx=longtext #yy=latext huso = 30 origenProj = pyproj.Proj(proj="utm", zone=huso, ellps="intl", units="m") destinoProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y) xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) #para que lo pase a utms en pantalla if src == "4258": x = int(UTM_X) y = int(UTM_Y) xxx = lon yyy = lat xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) fet.setAttributes( [float(x), float(y), str(xx), str(yy), float(xxx), float(yyy)]) pr2.addFeatures([fet]) #cambio la simbologia symbol = QgsMarkerSymbol.createSimple({ 'name': 'circle', 'color': 'red', 'size': '3', }) vl2.renderer().setSymbol(symbol) # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setSize(12) text_format.setColor(QColor("Orange")) layer_settings.setFormat(text_format) layer_settings.placement = 1 layer_settings.xOffset = 0.0 layer_settings.yOffset = 10.0 mostrar = True if self.dlg.checkBox_utm.isChecked( ) and self.dlg.checkBox_geo.isChecked(): layer_settings.fieldName = '''concat('X: ',"X",' Y: ',"Y",'\n','Lon: ',"xx",' Lat: ',"yy" )''' almacen = [1, 1] else: if self.dlg.checkBox_utm.isChecked(): layer_settings.fieldName = '''concat('X: ',"X",' Y: ',"Y" )''' almacen = [1, 0] print("caso1") if self.dlg.checkBox_geo.isChecked(): layer_settings.fieldName = '''concat('Lon: ',"xx",' Lat: ',"yy" )''' almacen = [0, 1] print("caso2") if not self.dlg.checkBox_utm.isChecked( ) and not self.dlg.checkBox_geo.isChecked(): mostrar = False almacen = [0, 0] print("caso3") print("almacen despues de etiquetar", almacen) layer_settings.isExpression = True print(mostrar) layer_settings.enabled = mostrar layer_settings = QgsVectorLayerSimpleLabeling(layer_settings) vl2.setLabelsEnabled(True) vl2.setLabeling(layer_settings) vl2.triggerRepaint() # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer vl2.updateExtents() vl2.commitChanges() vl2.updateExtents() canvas = self.iface.mapCanvas() canvas.setExtent(vl2.extent()) crsSrc = QgsCoordinateReferenceSystem('EPSG:' + str(src)) crsDest = QgsProject.instance().crs() if crsSrc != crsDest: xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance()) canvas.setExtent(xform.transform(vl2.extent())) self.iface.mapCanvas().zoomScale(escala) #self.limpiar_pressed() almacen.append(escala) #lo escribo en el txt, mavhacando lo que ya tenia f = open(rutacache, "w") escribir = str(almacen) f.write(escribir) f.close() print(almacen) QgsProject.instance().addMapLayer(vl2)
def __init__(self, parent, combos, coord=None): if not coord: coord = ["", None, "", None, None] super(FreeKeyWordsDialog, self).__init__(parent) if platform.system() != "Linux": font = QFont() font.setFamily(u"Segoe UI Symbol") self.setFont(font) self.setupUi(self) self.date_date_2 = NullQDateEditWrapper(self.date_date_2) self.setModal(True) self.combo_dataType.setModel( CustomComboBoxModel( self, [None] + sorted(list(combos[1].values()), key=lambda x: x.term_pt))) self.combo_dataType.setCurrentIndex(0) self.date_date_2.clear() self.combo_type.setModel( CustomComboBoxModel( self, [None] + sorted(list(combos[0].values()), key=lambda x: x.term_pt))) self.btn_cancelar.clicked.connect(lambda: self.done(QDialog.Rejected)) self.line_keyword.textChanged.connect(lambda: self.check_fields()) self.line_thesaurus.textChanged.connect(lambda: self.check_fields()) self.combo_type.currentIndexChanged.connect( lambda: self.check_fields()) self.combo_dataType.currentIndexChanged.connect( lambda: self.check_fields()) self.date_date_2.get_original().dateTimeChanged.connect( lambda: self.check_fields()) self.btn_adicionar.clicked.connect(lambda: self.done(QDialog.Accepted)) self.btn_adicionar.setDisabled(True) self.combo_type.setDisabled(True) self.line_thesaurus.setDisabled(True) self.date_date_2.setDisabled(True) self.btn_clear_date_date_2.setDisabled(True) self.combo_dataType.setDisabled(True) self.line_keyword.setText(coord[0]) if coord[1] is not None: buf = combos[0].get(coord[1].term_pt, None) if buf is not None: self.combo_type.setCurrentIndex( self.combo_type.findText(buf.term_pt)) self.line_thesaurus.setText(coord[2]) if coord[3] is None: self.date_date_2.clear() else: self.date_date_2.setDate(coord[3]) if coord[4] is not None: buf = combos[1].get(coord[4].term, None) if buf is not None: self.combo_dataType.setCurrentIndex( self.combo_dataType.findText(buf.term_pt)) self.superParent = None temp = self.parent() while self.superParent is None: if issubclass(type(temp), keywordsPanel.Ui_keywords): self.superParent = temp else: temp = temp.parent() for info in self.findChildren(qwidgets.QPushButton, QRegExp('info_*')): info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg')) info.setText('') info.pressed.connect(self.printHelp) self.btn_clear_date_date_2.setIcon( qgui.QIcon(':/resourcesFolder/icons/delete_field.svg')) self.btn_clear_date_date_2.pressed.connect( lambda: self.date_date_2.clear())
class DrawToolBar(object): NameSpace = getNameSpace() small_pt = 5 white_pen = QPen(Qt.white, small_pt) white_pen.setCapStyle(Qt.RoundCap) black_pen = QPen(Qt.black, small_pt) black_pen.setCapStyle(Qt.RoundCap) glass_pen = QPen(QColor(192, 192, 192, 128), 3) transparent_brush = QBrush(Qt.transparent) black_brush = QBrush(Qt.black) bold_12 = QFont("Arial", 12, QFont.Bold) # Stamp Image confidential = QPixmap.fromImage(QImage(":/imgFMV/images/stamp/confidential.png")) @staticmethod def setValues(options=None): ''' Function to set Drawing Values ''' s = QSettings() ####### Magnifier Glass ####### shape_type = s.value(DrawToolBar.NameSpace + "/Options/magnifier/shape") if shape_type is not None: global TYPE_MAGNIFIER TYPE_MAGNIFIER = shape_type if options is not None: if TYPE_MAGNIFIER == 0: # Square options.rB_Square_m.setChecked(True) else: # Circle options.rB_Circle_m.setChecked(True) mFactor = s.value(DrawToolBar.NameSpace + "/Options/magnifier/factor") if mFactor is not None: global MAX_FACTOR MAX_FACTOR = int(mFactor) if options is not None: options.sb_factor.setValue(MAX_FACTOR) mSize = s.value(DrawToolBar.NameSpace + "/Options/magnifier/size") if mSize is not None: global MAX_MAGNIFIER MAX_MAGNIFIER = int(mSize) if options is not None: options.sl_Size.setValue(MAX_MAGNIFIER) ####### Drawings ####### poly_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/width") if poly_w is not None: global PolyWidth PolyWidth = int(poly_w) if options is not None: options.poly_width.setValue(PolyWidth) poly_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/pen") if poly_p is not None: global PolyPen PolyPen = QPen(QColor(poly_p)) PolyPen.setCapStyle(Qt.RoundCap) PolyPen.setWidth(PolyWidth) if options is not None: options.poly_pen.setColor(QColor(poly_p)) poly_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/brush") if poly_b is not None: global PolyBrush PolyBrush = QBrush(QColor(poly_b)) if options is not None: options.poly_brush.setColor(QColor(poly_b)) point_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/width") if point_w is not None: global PointWidth PointWidth = int(point_w) if options is not None: options.point_width.setValue(PointWidth) point_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/pen") if point_p is not None: global PointPen PointPen = QPen(QColor(point_p)) PointPen.setCapStyle(Qt.RoundCap) PointPen.setWidth(PointWidth) if options is not None: options.point_pen.setColor(QColor(point_p)) line_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/width") if line_w is not None: global LineWidth LineWidth = int(line_w) if options is not None: options.lines_width.setValue(LineWidth) line_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/pen") if line_p is not None: global LinePen LinePen = QPen(QColor(line_p)) LinePen.setCapStyle(Qt.RoundCap) LinePen.setWidth(LineWidth) if options is not None: options.lines_pen.setColor(QColor(line_p)) measure_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/width") if measure_w is not None: global MeasureWidth MeasureWidth = int(measure_w) if options is not None: options.measures_width.setValue(MeasureWidth) measure_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/pen") if measure_p is not None: global MeasurePen MeasurePen = QPen(QColor(measure_p)) MeasurePen.setCapStyle(Qt.RoundCap) MeasurePen.setWidth(MeasureWidth) if options is not None: options.measures_pen.setColor(QColor(measure_p)) measure_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/brush") if measure_b is not None: global MeasureBrush MeasureBrush = QBrush(QColor(measure_b)) if options is not None: options.measures_brush.setColor(QColor(measure_b)) return @staticmethod def drawOnVideo(drawPtPos, drawLines, drawPolygon, drawMDistance, drawMArea, drawCesure, painter, surface, gt): ''' Function to paint over the video ''' # Draw clicked points on video for position, pt in enumerate(drawPtPos): DrawToolBar.drawPointOnVideo(position + 1, pt, painter, surface, gt) # Draw clicked lines on video if len(drawLines) > 1: for idx, pt in enumerate(drawLines): if pt[0] is None: continue else: DrawToolBar.drawLinesOnVideo( pt, idx, painter, surface, gt, drawLines) # Draw clicked Polygons on video if len(drawPolygon) > 1: poly = [] if any(None == x[1] for x in drawPolygon): for pt in drawPolygon: if pt[0] is None: DrawToolBar.drawPolygonOnVideo( poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len( drawPolygon) - drawPolygon[::-1].index([None, None, None]) poly = [] for pt in range(last_occurence, len(drawPolygon)): poly.append(drawPolygon[pt]) if len(poly) > 1: DrawToolBar.drawPolygonOnVideo( poly, painter, surface, gt) else: DrawToolBar.drawPolygonOnVideo( drawPolygon, painter, surface, gt) # Draw Measure Distance on video # the measures don't persist in the video if len(drawMDistance) > 1: DrawToolBar.resetMeasureDistance() for idx, pt in enumerate(drawMDistance): if pt[0] is None: DrawToolBar.resetMeasureDistance() continue else: DrawToolBar.drawMeasureDistanceOnVideo( pt, idx, painter, surface, gt, drawMDistance) # Draw Measure Area on video # the measures don't persist in the video if len(drawMArea) > 1: poly = [] if any(None == x[1] for x in drawMArea): for pt in drawMArea: if pt[0] is None: DrawToolBar.drawMeasureAreaOnVideo( poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len( drawMArea) - drawMArea[::-1].index([None, None, None]) poly = [] for pt in range(last_occurence, len(drawMArea)): poly.append(drawMArea[pt]) if len(poly) > 1: DrawToolBar.drawMeasureAreaOnVideo( poly, painter, surface, gt) else: DrawToolBar.drawMeasureAreaOnVideo( drawMArea, painter, surface, gt) # Draw Censure if drawCesure: DrawToolBar.drawCensuredOnVideo(painter, drawCesure) return return @staticmethod def drawPointOnVideo(number, pt, painter, surface, gt): ''' Draw Points on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( pt[1], pt[0], gt, surface) # don't draw something outside the screen. if scr_x < vut.GetXBlackZone(surface) or scr_y < vut.GetYBlackZone(surface): return if scr_x > vut.GetXBlackZone(surface) + vut.GetNormalizedWidth(surface) or scr_y > vut.GetYBlackZone(surface) + vut.GetNormalizedHeight(surface): return center = QPoint(scr_x, scr_y) painter.setPen(PointPen) painter.drawPoint(center) painter.setFont(DrawToolBar.bold_12) painter.drawText(center + QPoint(5, -5), str(number)) return @staticmethod def drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines): ''' Draw Lines on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) painter.setPen(LinePen) if len(drawLines) > 1: try: pt = drawLines[idx + 1] if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( pt[1], pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) # Draw Start/End Points painter.setPen(DrawToolBar.white_pen) painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawPolygonOnVideo(values, painter, surface, gt): ''' Draw Polygons on Video ''' poly = [] for pt in values: if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setPen(PolyPen) painter.drawPolygon(polygon) painter.fillPath(path, PolyBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) return @staticmethod def resetMeasureDistance(): global RulerTotalMeasure RulerTotalMeasure = 0.0 @staticmethod def drawMeasureDistanceOnVideo(pt, idx, painter, surface, gt, drawMDistance): ''' Draw Measure Distance on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) if len(drawMDistance) > 1: try: painter.setPen(MeasurePen) end_pt = drawMDistance[idx + 1] if hasElevationModel(): end_pt = GetLine3DIntersectionWithPlane( GetSensor(), end_pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( end_pt[1], end_pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) painter.setFont(DrawToolBar.bold_12) distance = round(sphere.distance( (pt[0], pt[1]), (end_pt[0], end_pt[1])), 2) text = str(distance) + " m" global RulerTotalMeasure RulerTotalMeasure += distance # Line lenght painter.setPen(MeasurePen) painter.drawText(end + QPoint(5, -10), text) painter.setPen(DrawToolBar.white_pen) # Total lenght painter.drawText(end + QPoint(5, 10), str(round(RulerTotalMeasure, 2)) + " m") # Draw Start/End Points painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawMeasureAreaOnVideo(values, painter, surface, gt): ''' Draw Measure Area on Video ''' a_value = sphere.polygon_area([values]) poly = [] lat = [] long = [] for pt in values: if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix( pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) lat.append(pt[0]) long.append(pt[1]) # Fix: Temporary correction # mousePressEvent calls after mouseMoveEvent. # A problem occurs because the centroid is miscalculated. # We remove duplicates values lat = list(dict.fromkeys(lat)) long = list(dict.fromkeys(long)) # Calculate Centroid Position scr_x, scr_y = vut.GetInverseMatrix( sum(long) / len(long), sum(lat) / len(lat), gt, surface) centroid = QPoint(scr_x, scr_y) # Create Poligon polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setFont(DrawToolBar.bold_12) painter.setPen(MeasurePen) painter.drawPolygon(polygon) painter.fillPath(path, MeasureBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) # Area if a_value >= 10000: painter.drawText(centroid , str(round(a_value / 1000000, 2)) + " km²") else: painter.drawText(centroid , str(round(a_value, 2)) + " m²") return @staticmethod def drawCensuredOnVideo(painter, drawCesure): ''' Draw Censure on Video ''' try: for geom in drawCesure: painter.setPen(DrawToolBar.black_pen) painter.setBrush(DrawToolBar.black_brush) painter.drawRect(geom[0].x(), geom[0].y(), geom[0].width(), geom[0].height()) except Exception: None return @staticmethod def drawMagnifierOnVideo(widget, dragPos, source, painter): ''' Draw Magnifier on Video ''' oldTransform = painter.transform() painter.setTransform(oldTransform) painter.setBrush(DrawToolBar.transparent_brush) dim = min(widget.width(), widget.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) center = dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * MAX_FACTOR - QPoint(radius, radius) # only set the dimension to the magnified portion zoomPixmap = QPixmap(box) zoomPixmap.fill(Qt.black) painter_p = QPainter(zoomPixmap) painter_p.setRenderHint(QPainter.HighQualityAntialiasing) painter_p.translate(-xy) painter_p.scale(MAX_FACTOR, MAX_FACTOR) painter_p.drawImage(widget.surface.videoRect(), source, widget.surface.sourceRect()) painter_p.end() clipPath = QPainterPath() center = QPointF(center) # Shape Type if TYPE_MAGNIFIER == 0: # Square clipPath.addRect(center.x(), center.y(), magnifierSize, magnifierSize) clipPath.translate(-radius , -radius) else: # Circle clipPath.addEllipse(center, ring, ring) painter.setClipPath(clipPath) painter.drawPixmap(corner, zoomPixmap) painter.setPen(DrawToolBar.glass_pen) painter.drawPath(clipPath) return @staticmethod def drawStampOnVideo(widget, painter): ''' Draw Stamp Confidential on Video ''' painter.drawPixmap(widget.surface.videoRect(), DrawToolBar.confidential, widget.surface.sourceRect())
def __init__(self, parent, combos, coord=None): if not coord: coord = ["", None, None, ""] super(LegalRestrictionsDialog, self).__init__(parent) if platform.system() != "Linux": font = QFont() font.setFamily(u"Segoe UI Symbol") self.setFont(font) self.setupUi(self) self.setModal(True) self.restrict_dic = combos[0] self.combo_accessrestrictions.setModel( CustomComboBoxModel( self, [None] + sorted(list(combos[0].values()), key=lambda x: x.term_pt))) self.combo_userestrictions.setModel( CustomComboBoxModel( self, [None] + sorted(list(combos[0].values()), key=lambda x: x.term_pt))) self.btn_cancel.clicked.connect(lambda: self.done(QDialog.Rejected)) self.btn_add.clicked.connect(lambda: self.done(QDialog.Accepted)) self.line_uselimitations.textChanged.connect(self.checkInput) self.combo_accessrestrictions.currentIndexChanged.connect( self.checkInput) self.combo_userestrictions.currentIndexChanged.connect(self.checkInput) self.line_otherrestrictions.textEdited.connect(self.checkInput) self.line_uselimitations.setText(coord[0]) if coord[1] is not None: buf = combos[0].get(coord[1].term, None) if buf is not None: self.combo_accessrestrictions.setCurrentIndex( self.combo_accessrestrictions.findText(buf.term_pt)) if coord[2] is not None: buf = combos[0].get(coord[2].term, None) if buf is not None: self.combo_userestrictions.setCurrentIndex( self.combo_userestrictions.findText(buf.term_pt)) self.line_otherrestrictions.setText(coord[3]) self.checkInput() tla.setupMandatoryField(None, self.line_uselimitations, self.label_line_uselimitations, u"Elemento Obrigatório.") tla.setupMandatoryField(None, self.combo_accessrestrictions, self.label_combo_accessrestrictions, u"Elemento Obrigatório.") tla.setupMandatoryField(None, self.combo_userestrictions, self.label_combo_userestrictions, u"Elemento Obrigatório.") self.superParent = None temp = self.parent() while self.superParent is None: if issubclass(type(temp), restrictionsPanel.Ui_restrictions): self.superParent = temp else: temp = temp.parent() for info in self.findChildren(qgui.QPushButton, qcore.QRegExp('info_*')): info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg')) info.setText('') info.pressed.connect(self.printHelp)
def data(self, index: QModelIndex, role: Qt.ItemDataRole = Qt.DisplayRole) -> Union[ None, QBrush, QFont, Qt.AlignmentFlag, str]: """ Returns data from the table cell? """ if not index.isValid() or not 0 <= index.row() < self.rowCount(): return None row = index.row() - self.offsetY column = index.column() - self.offsetX if role == Qt.DisplayRole: # Table cell data if row >= 0 and column >= 0: return self.tab[row][column][0] # Row descriptions? elif column < 0 and row >= 0 and self.rows[0]: return self.rows[row + 1][column] # Row title field? elif row == -1 and column < 0 and self.rows[0]: return self.rows[0][column] # Column description and names? elif column >= -1 and row < 0 and self.columns[0]: if self.rows[0]: # Break line? if row == -1: return '' # Descriptions and column names if there is a break line? return self.columns[column + 1][row + 1] # Column descriptions and names if there is no break line? return self.columns[column + 1][row] elif role == Qt.UserRole: if row >= 0 and column >= 0: return self.tab[row][column][1] elif role == Qt.UserRole + 1: if row < 0 and column >= 0: return 'column' elif row >= 0 and column < 0: return 'row' elif row >= 0 and column >= 0: return 'data' # Cell filling elif role == Qt.BackgroundRole: if row < 0 or column < 0: # Gray for cells with descriptions and names color = QColor(245, 235, 235) brush = QBrush(color) return brush elif role == Qt.TextAlignmentRole: if column < 0 and row < -1 and self.rows: return Qt.AlignRight | Qt.AlignVCenter elif column >= 0 and row < 0: return Qt.AlignHCenter | Qt.AlignVCenter elif column >= 0 and row >= 0: return Qt.AlignRight | Qt.AlignVCenter elif role == Qt.FontRole: if row < 0 and column < 0: font = QFont() font.setBold(True) return font return None
def setLexers(self): self.lexer = QsciLexerPython() loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace") fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int) font = QFont(loadFont) font.setFixedPitch(True) font.setPointSize(fontSize) font.setStyleHint(QFont.TypeWriter) font.setStretch(QFont.SemiCondensed) font.setLetterSpacing(QFont.PercentageSpacing, 87.0) font.setBold(False) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1) self.lexer.setColor( QColor( self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5) self.lexer.setColor( QColor( self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8) self.lexer.setColor( QColor( self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9) self.lexer.setColor( QColor( self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12) self.lexer.setColor( QColor( self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4) self.lexer.setColor( QColor( self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7) self.lexer.setColor(QColor(Qt.red), 14) self.lexer.setFont(font, 1) self.lexer.setFont(font, 2) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) for style in range(0, 33): paperColor = QColor( self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white))) self.lexer.setPaper(paperColor, style) self.setLexer(self.lexer)
# coding=utf-8 """Fonts which are used in InaSAFE.""" from qgis.PyQt.QtGui import QFont big_font = QFont() big_font.setPointSize(80) bold_font = QFont() bold_font.setItalic(True) bold_font.setBold(True) bold_font.setWeight(75)
def __init__(self, parent=None): super(ShellOutputScintilla, self).__init__(parent) self.parent = parent self.shell = self.parent.shell self.settings = QSettings() # Creates layout for message bar self.layout = QGridLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # messageBar instance self.infoBar = QgsMessageBar() sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # Enable non-ascii chars for editor self.setUtf8(True) sys.stdout = writeOut(self, sys.stdout) sys.stderr = writeOut(self, sys.stderr, "_traceback") self.insertInitText() self.refreshSettingsOutput() self.setReadOnly(True) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers self.setMarginWidth(0, 0) self.setMarginWidth(1, 0) self.setMarginWidth(2, 0) #fm = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(1, "00000") self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor("#3E3EE3")) self.setMarginsBackgroundColor(QColor("#f9f9f9")) self.setCaretLineVisible(True) self.setCaretWidth(0) self.setMinimumHeight(120) self.setWrapMode(QsciScintilla.WrapCharacter) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self) self.runScut.setContext(Qt.WidgetShortcut) self.runScut.activated.connect(self.enteredSelected) # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view self.copyShortcut = QShortcut(QKeySequence.Copy, self) self.copyShortcut.activated.connect(self.copy) self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self) self.selectAllShortcut.activated.connect(self.selectAll)
def showFeatureAttributes(self): conflictItem = self.lastSelectedItem self.oursgeom = None self.theirsgeom = None geoms = (self.oursgeom, self.theirsgeom) self.currentConflictedAttributes = [] attribs = list(conflictItem.origin.keys()) self.attributesTable.setRowCount(len(attribs)) self.conflicted = [] for idx, name in enumerate(attribs): font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(name) item.setFont(font) self.attributesTable.setItem(idx, 3, item) self.attributesTable.setItem(idx, 4, ValueItem(None, False)) try: values = (conflictItem.origin[name], conflictItem.local[name], conflictItem.remote[name]) except Exception: #Local has been deleted self._afterSolve(False) self.solveModifyAndDelete(conflictItem.conflict.path, self.REMOTE) return except TypeError: #Remote has been deleted self._afterSolve(False) self.solveModifyAndDelete(conflictItem.conflict.path, self.LOCAL) return try: geom = QgsGeometry.fromWkt(values[0]) except: geom = None if geom is not None: self.theirsgeom = QgsGeometry().fromWkt(values[1]) self.oursgeom = QgsGeometry.fromWkt(values[2]) geoms = (self.oursgeom, self.theirsgeom) ok = values[0] == values[1] or values[1] == values[2] or values[ 0] == values[2] for i, v in enumerate(values): self.attributesTable.setItem(idx, i, ValueItem(v, not ok, geoms)) if not ok: self.conflicted.append(name) else: if values[0] == values[1]: newvalue = values[2] else: newvalue = values[1] self.attributesTable.setItem(idx, 4, ValueItem(newvalue, False, geoms)) self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True)
def addMenuItem(self, uri, filename, node, menu, absolute, mapLayersDict): """Add menu to an item.""" yaLayer = False if node is None or node.nodeName() == "": return yaLayer element = node.toElement() # if legendlayer tag if node.nodeName() == "layer-tree-layer": try: name = element.attribute("name") layerId = element.attribute("id") visible = element.attribute("checked", "") == "Qt::Checked" expanded = element.attribute("expanded", "0") == "1" action = QAction(name, self.iface.mainWindow()) embedNd = getFirstChildByAttrValue(element, "property", "key", "embedded") # is layer embedded ? if embedNd and embedNd.toElement().attribute("value") == "1": # layer is embeded efilename = None eFileNd = getFirstChildByAttrValue(element, "property", "key", "embedded_project") if eFileNd: # get project file name embeddedFile = eFileNd.toElement().attribute("value") if not absolute and (embeddedFile.find(".") == 0): efilename = QFileInfo( filename).path() + "/" + embeddedFile # if ok if efilename: # add menu item action.triggered.connect( lambda checked, uri=uri, f=efilename, lid= layerId, m=menu, v=visible, x=expanded: self. loadLayer(uri, f, lid, m, v, x)) menu.addAction(action) yaLayer = True if self.optionTooltip: # search embeded maplayer (for title, abstract) mapLayer = self.getMapLayerDomFromQgs( efilename, layerId) if mapLayer is not None: self.addToolTip(mapLayer, action) else: self.log("Menu from layer: {} not found in project {}". format(layerId, efilename)) # layer is not embedded else: efilename = filename if self.optionTooltip: self.addToolTip(mapLayersDict[layerId], action) action.triggered.connect( lambda checked, uri=uri, f=filename, lid=layerId, m= menu, v=visible, x=expanded: self.loadLayer( uri, f, lid, m, v, x)) menu.addAction(action) yaLayer = True # Add geometry type icon try: map_layer = self.getMapLayerDomFromQgs( efilename, layerId).toElement() geometry_type = map_layer.attribute("geometry") if geometry_type == "": # A TMS has not a geometry attribute. # Let's read the "type" geometry_type = map_layer.attribute("type") action.setIcon(icon_per_geometry_type(geometry_type)) except Exception: pass except Exception as e: for m in e.args: self.log(m) # / if element.tagName() == "layer-tree-layer": # if legendgroup tag if node.nodeName() == "layer-tree-group": name = element.attribute("name") propertiesNode = node.firstChild() embedNd = getFirstChildByAttrValue(propertiesNode.toElement(), "property", "key", "embedded") # is group embedded ? if embedNd and embedNd.toElement().attribute("value") == "1": # group is embeded efilename = None eFileNd = getFirstChildByAttrValue(element, "property", "key", "embedded_project") if eFileNd: # get project file name embeddedFile = eFileNd.toElement().attribute("value") if not absolute and (embeddedFile.find(".") == 0): efilename = QFileInfo( filename).path() + "/" + embeddedFile # if ok if efilename: # add menu group doc, _ = self.getQgsDoc(efilename) groupNode = getFirstChildByAttrValue( doc.documentElement(), "layer-tree-group", "name", name) # and do recursion r = self.addMenuItem( efilename, efilename, groupNode, menu, absolute, getMapLayersDict(doc), ) yaLayer = yaLayer or r else: self.log( "Menu from layer: {} not found in project {}".format( layerId, efilename)) # group is not embedded else: if name == "-": menu.addSeparator() elif name.startswith("-"): action = QAction(name[1:], self.iface.mainWindow()) font = QFont() font.setBold(True) action.setFont(font) menu.addAction(action) else: # sub-menu sousmenu = menu.addMenu("&" + element.attribute("name")) sousmenu.menuAction().setToolTip("") sousmenu.setToolTipsVisible(self.optionTooltip) childNode = node.firstChild() # ! recursion r = self.addMenuItem(uri, filename, childNode, sousmenu, absolute, mapLayersDict) if r and self.optionLoadAll and (len(sousmenu.actions()) > 1): action = QAction(self.tr("Load all"), self.iface.mainWindow()) font = QFont() font.setBold(True) action.setFont(font) sousmenu.addAction(action) action.triggered.connect( lambda checked, f=None, w=None, m=sousmenu: self. loadLayer(uri, f, w, m)) # / if element.tagName() == "legendgroup": nextNode = node.nextSibling() if nextNode is not None: # ! recursion r = self.addMenuItem(uri, filename, nextNode, menu, absolute, mapLayersDict) yaLayer = yaLayer or r return yaLayer
def addMenuItem(self, filename, node, menu, domdoc, mapLayersDict): yaLayer = False initialFilename = filename if node is None or node.nodeName() == "": return yaLayer element = node.toElement() # if legendlayer tag if node.nodeName() == "layer-tree-layer": try: name = element.attribute("name") layerId = element.attribute("id") visible = element.attribute("checked", "") == "Qt::Checked" expanded = element.attribute("expanded", "0") == "1" action = QAction(name, self.iface.mainWindow()) embedNd = getFirstChildByAttrValue(element, "property", "key", "embedded") # is layer embedded ? if embedNd and embedNd.toElement().attribute("value") == "1": # layer is embeded efilename = None eFileNd = getFirstChildByAttrValue(element, "property", "key", "embedded_project") # get project file name embeddedFile = eFileNd.toElement().attribute("value") if not self.absolute and (embeddedFile.find(".") == 0): efilename = self.projectpath + "/" + embeddedFile # if ok if efilename: # add menu item action.triggered.connect( lambda checked, f=efilename, lid=layerId, m=menu, v =visible, x=expanded: self.do_aeag_menu( f, lid, m, v, x)) menu.addAction(action) yaLayer = True if self.optionTooltip: # search embeded maplayer (for title, abstract) mapLayer = getMapLayerDomFromQgs( efilename, layerId) if mapLayer is not None: self.addToolTip(mapLayer, action) else: QgsMessageLog.logMessage( "Menu from layer: " + layerId + " not found in project " + efilename, 'Extensions') # layer is not embedded else: if self.optionTooltip: self.addToolTip(mapLayersDict[layerId], action) action.triggered.connect( lambda checked, f=filename, lid=layerId, m=menu, v= visible, x=expanded: self.do_aeag_menu( f, lid, m, v, x)) menu.addAction(action) yaLayer = True except Exception as e: for m in e.args: QgsMessageLog.logMessage(m, 'Extensions') # / if element.tagName() == "layer-tree-layer": # if legendgroup tag if node.nodeName() == "layer-tree-group": name = element.attribute("name") if name == "-": menu.addSeparator() elif name.startswith("-"): action = QAction(name[1:], self.iface.mainWindow()) font = QFont() font.setBold(True) action.setFont(font) menu.addAction(action) else: # sub-menu sousmenu = menu.addMenu('&' + element.attribute("name")) sousmenu.menuAction().setToolTip("") sousmenu.setToolTipsVisible(self.optionTooltip) childNode = node.firstChild() # ! recursion r = self.addMenuItem(initialFilename, childNode, sousmenu, domdoc, mapLayersDict) if r and self.optionLoadAll and (len(sousmenu.actions()) > 1): action = QAction(self.tr("Load all"), self.iface.mainWindow()) font = QFont() font.setBold(True) action.setFont(font) sousmenu.addAction(action) action.triggered.connect( lambda checked, f=None, w=None, m=sousmenu: self. do_aeag_menu(f, w, m)) # / if element.tagName() == "legendgroup": nextNode = node.nextSibling() if nextNode is not None: # ! recursion r = self.addMenuItem(initialFilename, nextNode, menu, domdoc, mapLayersDict) yaLayer = yaLayer or r return yaLayer
def populate_classified_values(unassigned_values, assigned_values, default_classes, list_unique_values, tree_mapping_widget): """Populate lstUniqueValues and treeClasses.from the parameters. :param unassigned_values: List of values that haven't been assigned to a class. It will be put in list_unique_values. :type unassigned_values: list :param assigned_values: Dictionary with class as the key and list of value as the value of the dictionary. It will be put in tree_mapping_widget. :type assigned_values: dict :param default_classes: Default classes from unit. :type default_classes: list :param list_unique_values: List Widget for unique values :type list_unique_values: QListWidget :param tree_mapping_widget: Tree Widget for classifying. :type tree_mapping_widget: QTreeWidget """ # Populate the unique values list list_unique_values.clear() list_unique_values.setSelectionMode( QAbstractItemView.ExtendedSelection) for value in unassigned_values: value_as_string = value is not None and str(value) or 'NULL' list_item = QListWidgetItem(list_unique_values) list_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) list_item.setData(Qt.UserRole, value) list_item.setText(value_as_string) list_unique_values.addItem(list_item) # Populate assigned values tree tree_mapping_widget.clear() bold_font = QFont() bold_font.setItalic(True) bold_font.setBold(True) bold_font.setWeight(75) tree_mapping_widget.invisibleRootItem().setFlags(Qt.ItemIsEnabled) for default_class in default_classes: # Create branch for class tree_branch = QTreeWidgetItem(tree_mapping_widget) tree_branch.setFlags(Qt.ItemIsDropEnabled | Qt.ItemIsEnabled) tree_branch.setExpanded(True) tree_branch.setFont(0, bold_font) if 'name' in default_class: default_class_name = default_class['name'] else: default_class_name = default_class['key'] tree_branch.setText(0, default_class_name) tree_branch.setData(0, Qt.UserRole, default_class['key']) if 'description' in default_class: tree_branch.setToolTip(0, default_class['description']) # Assign known values for value in assigned_values[default_class['key']]: string_value = value is not None and str(value) or 'NULL' tree_leaf = QTreeWidgetItem(tree_branch) tree_leaf.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) tree_leaf.setData(0, Qt.UserRole, value) tree_leaf.setText(0, string_value)
def _setupUI(self): self.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred) self.setMinimumHeight(180) self.main_horizontal_layout = QHBoxLayout(self) italic_font = QFont() italic_font.setItalic(True) # deselected widget self.deselected_widget = QListWidget(self) self._set_list_widget_defaults(self.deselected_widget) deselected_label = QLabel() deselected_label.setText('Deselected') deselected_label.setAlignment(Qt.AlignCenter) deselected_label.setFont(italic_font) deselected_v_layout = QVBoxLayout() deselected_v_layout.addWidget(deselected_label) deselected_v_layout.addWidget(self.deselected_widget) # selected widget self.selected_widget = QListWidget(self) self._set_list_widget_defaults(self.selected_widget) selected_label = QLabel() selected_label.setText('Selected') selected_label.setAlignment(Qt.AlignCenter) selected_label.setFont(italic_font) selected_v_layout = QVBoxLayout() selected_v_layout.addWidget(selected_label) selected_v_layout.addWidget(self.selected_widget) # buttons self.buttons_vertical_layout = QVBoxLayout() self.buttons_vertical_layout.setContentsMargins(0, -1, 0, -1) self.select_all_btn = SmallQPushButton('>>') self.deselect_all_btn = SmallQPushButton('<<') self.select_btn = SmallQPushButton('>') self.deselect_btn = SmallQPushButton('<') self.select_btn.setToolTip('Add the selected items') self.deselect_btn.setToolTip('Remove the selected items') self.select_all_btn.setToolTip('Add all') self.deselect_all_btn.setToolTip('Remove all') # add buttons spacer_label = QLabel() # pragmatic way to create a spacer with # the same height of the labels on top # of the lists, in order to align the # buttons with the lists. self.buttons_vertical_layout.addWidget(spacer_label) self.buttons_vertical_layout.addWidget(self.select_btn) self.buttons_vertical_layout.addWidget(self.deselect_btn) self.buttons_vertical_layout.addWidget(self.select_all_btn) self.buttons_vertical_layout.addWidget(self.deselect_all_btn) # add sub widgets self.main_horizontal_layout.addLayout(deselected_v_layout) self.main_horizontal_layout.addLayout(self.buttons_vertical_layout) self.main_horizontal_layout.addLayout(selected_v_layout)
class QvConstants: '''Classe amb mètodes i "constants" estàtiques pel qVista Nota: No canviar el valor de les constants. No són constants ''' # Fonts del qVista NOMFONT = 'Arial' NOMFONTTITOLS = 'Segoe UI Light' MIDAFONTTITOLS = 18 MIDAFONTSUBTITOLS = 14 MIDAFONTCAPCALERES = 12 MIDAFONTTEXT = 10 FONTCAPCALERES = QFont(NOMFONT, MIDAFONTCAPCALERES, QFont.Bold) FONTTITOLS = QFont(NOMFONTTITOLS, MIDAFONTTITOLS) FONTSUBTITOLS = QFont(NOMFONTTITOLS, MIDAFONTSUBTITOLS) FONTTEXT = QFont(NOMFONT, MIDAFONTTEXT) # Colors del qVista, utilitzant el seu codi HTML COLORFOSCHTML = '#38474F' COLORMIGHTML = '#465A63' COLORCLARHTML = '#79909B' COLORGRISHTML = '#DDDDDD' COLORGRISCLARHTML = '#F0F0F0' COLORBLANCHTML = '#F9F9F9' COLORDESTACATHTML = '#FF6215' # COLOROMBRAHTML = '#666666DD' COLOROMBRAHTML = '#66000000' COLORCERCADORHTML = '#B6C2C9' COLORTEXTHINTHTML = '#A0A0A0' # Colors del qVista, utilitzant QColor COLORFOSC = QColor(COLORFOSCHTML) COLORMIG = QColor(COLORMIGHTML) COLORCLAR = QColor(COLORCLARHTML) COLORCLARSEMITRANS = QColor(121, 144, 155, 70) COLORGRIS = QColor(COLORGRISHTML) COLORGRISCLAR = QColor(COLORGRISCLARHTML) COLORBLANC = QColor(COLORBLANCHTML) COLORDESTACAT = QColor(COLORDESTACATHTML) COLOROMBRA = QColor(COLOROMBRAHTML) COLORCERCADOR = QColor(COLORCERCADORHTML) COLORTEXTHINT = QColor(COLORTEXTHINTHTML) #No podem crear una QPixMap sense CURSORFLETXA = Qt.ArrowCursor CURSORCLICK = Qt.PointingHandCursor CURSORZOOMIN = None CURSORZOOMOUT = None CURSORDIT = None CURSOROCUPAT = Qt.WaitCursor @staticmethod def afegeixOmbraWidget(widget: QWidget): """Afegeix una ombra de widget (offset x=3, y=3) al widget rebut Arguments: widget{QWidget} -- Widget al que afegim la ombra """ return QvConstants.aplicaOmbra(widget, QvConstants.ombraWidget(widget)) def afegeixOmbraWidgetSeleccionat(widget: QWidget): return QvConstants.aplicaOmbra( widget, QvConstants.ombraWidgetSeleccionat(widget)) @staticmethod def afegeixOmbraHeader(widget: QWidget): """Afegeix una ombra de header (offset x=0, y=3) al widget rebut Per afegir ombra a un layout, s'ha de fer una cosa així: widget=QWidget() widget.setLayout(layout) QvConstants.afegeixOmbraHeader(widget) Arguments: widget{QWidget} -- Widget al que afegim la ombra """ return QvConstants.aplicaOmbra(widget, QvConstants.ombraHeader(widget)) # FUNCIONS "PRIVADES" # Cap funció de les de sota hauria de ser cridada des de fora de la classe # La funció que crea la ombra. Totes les altres tiren d'aquesta @staticmethod def ombra(parent: QWidget = None, offset: Sequence[int] = (3, 3), radius: int = 15, color: QColor = COLOROMBRA) -> QGraphicsDropShadowEffect: ombra = QGraphicsDropShadowEffect(parent) ombra.setBlurRadius(radius) ombra.setOffset(*offset) ombra.setColor(color) return ombra # Funcions per retornar ombres # Nota: No assignar un mateix objecte ombra a més d'un widget. Només es conservarà a l'últim @staticmethod def ombraWidget(parent: QWidget = None) -> QGraphicsDropShadowEffect: """Retorna una ombra pensada per posar a un widget (amb un offset de x=3 i y=3) Keyword Arguments: parent{QWidget} -- Pare de l'ombra (default: {None}) Returns: ombra{QGraphicsDropShadowEffect} - Ombra amb l'offset indicat""" return QvConstants.ombra(parent) def ombraWidgetSeleccionat( parent: QWidget = None) -> QGraphicsDropShadowEffect: return QvConstants.ombra(parent, offset=(0, 0), radius=20, color=QColor('#444444')) @staticmethod def ombraHeader(parent: QWidget = None) -> QGraphicsDropShadowEffect: """Retorna una ombra pensada per posar a un header (amb un offset de x=0 i y=3) Keyword Arguments: parent{QWidget} -- Pare de l'ombra (default: {None}) Returns: ombra{QGraphicsDropShadowEffect} - Ombra amb l'offset indicat""" return QvConstants.ombra(parent, offset=(0, 3)) # Aplica la ombra al Widget @staticmethod def aplicaOmbra(widget: QWidget, ombra: QGraphicsDropShadowEffect): widget.setGraphicsEffect(ombra) return ombra @staticmethod def cursorZoomIn(): if QvConstants.CURSORZOOMIN is None: QvConstants.CURSORZOOMIN = QCursor( QPixmap(os.path.join(imatgesDir, 'zoom_in.cur'))) return QvConstants.CURSORZOOMIN @staticmethod def cursorZoomOut(): if QvConstants.CURSORZOOMOUT is None: QvConstants.CURSORZOOMOUT = QCursor( QPixmap(os.path.join(imatgesDir, 'zoom_out.cur'))) return QvConstants.CURSORZOOMOUT @staticmethod def cursorDit(): if QvConstants.CURSORDIT is None: QvConstants.CURSORDIT = QCursor( QPixmap(os.path.join(imatgesDir, 'dedo.cur'))) return QvConstants.CURSORDIT @staticmethod def cursorFletxa(): return QvConstants.CURSORFLETXA @staticmethod def cursorClick(): return QvConstants.CURSORCLICK @staticmethod def cursorOcupat(): return QvConstants.CURSOROCUPAT # No s'ha d'instanciar la classe, de manera que si fem un init es queixa def __init__(self): raise TypeError('No es poden crear instàncies de QvConstants')
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setWrapMode(QsciScintilla.WrapWord) self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor(QColor('#2e3436')) self.setSelectionBackgroundColor(QColor('#babdb6')) # Show line numbers self.setMarginWidth(1, '000') self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor('#2e3436')) self.setMarginsBackgroundColor(QColor('#babdb6')) # Highlight current line self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor('#d3d7cf')) # Folding self.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf')) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor('#eeeeec')) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) # Autocomletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setAutoCompletionCaseSensitivity(False) # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', 10)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) self.defaultFont.setStretch(QFont.SemiCondensed) self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0) self.defaultFont.setBold(False) self.boldFont = QFont(self.defaultFont) self.boldFont.setBold(True) self.italicFont = QFont(self.defaultFont) self.italicFont.setItalic(True) self.setFont(self.defaultFont) self.setMarginsFont(self.defaultFont) self.initLexer()
def update_available_layers(self): self.trw_layers.setUpdatesEnabled(False) # Don't render until we're ready # Grab some context data show_domains = self.chk_show_domains.isChecked() show_structures = self.chk_show_structures.isChecked() show_associations = self.chk_show_associations.isChecked() top_level_items_expanded_info = [] for i in range(self.trw_layers.topLevelItemCount()): top_level_items_expanded_info.append(self.trw_layers.topLevelItem(i).isExpanded()) # Save selection self.update_selected_items() # Iterate models adding children self.trw_layers.blockSignals(True) # We don't want to get itemSelectionChanged here self.trw_layers.clear() self.trw_layers.blockSignals(False) sorted_models = sorted(self.models_tree.keys()) for model in sorted_models: children = [] model_item = QTreeWidgetItem([model]) # Filter by search text list_tables = self.filter_tables_by_search_text(self.models_tree[model].keys(), self.txt_search_text.text()) sorted_tables = sorted(list_tables) for table in sorted_tables: current_table_info = self.models_tree[model][table] if current_table_info[KIND_SETTINGS] == TABLE_PROP_DOMAIN and not show_domains \ or current_table_info[KIND_SETTINGS] == TABLE_PROP_STRUCTURE and not show_structures \ or current_table_info[KIND_SETTINGS] == TABLE_PROP_ASSOCIATION and not show_associations: continue table_item = QTreeWidgetItem([table]) table_item.setData(0, Qt.UserRole, self.models_tree[model][table]) geometry_type = QgsWkbTypes().geometryType(QgsWkbTypes().parseType(current_table_info[GEOMETRY_TYPE])) if current_table_info[GEOMETRY_TYPE] else None icon_name = self.icon_names[3 if geometry_type is None else geometry_type] # Is the layer already loaded? if self.qgis_utils.get_layer_from_layer_tree(self._db, current_table_info[TABLE_NAME], geometry_type) is not None: table_item.setText(0, table + QCoreApplication.translate("LoadLayersDialog", " [already loaded]")) table_item.setData(0, Qt.ForegroundRole, QBrush(Qt.lightGray)) table_item.setFlags(Qt.ItemIsEnabled) # Not selectable else: # Laye not in QGIS Layer Tree if not current_table_info[KIND_SETTINGS]: # This is a class font = QFont() font.setBold(True) table_item.setData(0, Qt.FontRole, font) if current_table_info[KIND_SETTINGS] == TABLE_PROP_DOMAIN: icon_name = self.icon_names[4] elif current_table_info[KIND_SETTINGS] == TABLE_PROP_STRUCTURE: icon_name = self.icon_names[5] elif current_table_info[KIND_SETTINGS] == TABLE_PROP_ASSOCIATION: icon_name = self.icon_names[6] icon = QIcon(":/Asistente-LADM_COL/resources/images/{}.png".format(icon_name)) table_item.setData(0, Qt.DecorationRole, icon) children.append(table_item) model_item.addChildren(children) self.trw_layers.addTopLevelItem(model_item) # Set selection iterator = QTreeWidgetItemIterator(self.trw_layers, QTreeWidgetItemIterator.Selectable) self.trw_layers.blockSignals(True) # We don't want to get itemSelectionChanged here while iterator.value(): item = iterator.value() if item.text(0) in self.selected_items_dict: item.setSelected(True) iterator += 1 self.trw_layers.blockSignals(False) # Make model items non selectable # Set expand taking previous states into account for i in range(self.trw_layers.topLevelItemCount()): self.trw_layers.topLevelItem(i).setFlags(Qt.ItemIsEnabled) # Not selectable self.trw_layers.topLevelItem(i).setExpanded(top_level_items_expanded_info[i] if top_level_items_expanded_info else True) self.trw_layers.setUpdatesEnabled(True) # Now render!
def getTestFont(cls): return QFont(cls._TestFont)
def __init__(self, parent): self.parent = parent super().__init__("Marxes exploratòries") self.setContextMenuPolicy(Qt.PreventContextMenu) fMarxes = QFrame() # fMarxes.setStyleSheet("QFrame {background-image: url('c:/qvistaProd/imatges/pavim.jpg');}") lytMarxes = QVBoxLayout(fMarxes) lytMarxes.setAlignment(Qt.AlignTop) fMarxes.setLayout(lytMarxes) self.setMaximumWidth(500) self.setMinimumWidth(500) lDocuments = QLabel('1.- Documents generals del projecte') lDocuments.setAlignment(Qt.AlignCenter) f = QFont() f.setBold(True) lDocuments.setFont(f) lBarris = QLabel('2.- Documents de cada marxa') lBarris.setAlignment(Qt.AlignCenter) f = QFont() f.setBold(True) lBarris.setFont(f) lBarris2 = QLabel('2.1- Recull informatiu de cada marxa') lBarris2.setAlignment(Qt.AlignLeft) f = QFont() f.setBold(True) lBarris2.setFont(f) lBarris3 = QLabel('2.2- Informe de resultats de cada marxa') lBarris3.setAlignment(Qt.AlignLeft) f = QFont() f.setBold(True) lBarris3.setFont(f) lBarris4 = QLabel('2.3- Document de retorn') lBarris4.setAlignment(Qt.AlignLeft) f = QFont() f.setBold(True) lBarris4.setFont(f) bGuia = QvPushButton( '1.1 Mapificació marxes exploratòries: Qué és el projecte?', flat=True) bGuia.setStyleSheet("Text-align: left") # bMarxes = QvPushButton('Recull marxes exploratòries dones 2017-18',flat=True) # bMarxes.setStyleSheet("Text-align: left") bMapa = QvPushButton( '1.2 Mapa de Barcelona identificant les marxes realitzades', flat=True) bMapa.setStyleSheet("Text-align: left") bDocGen = QvPushButton( '1.3 Document general (guia lectura, info de cada marxa, annexos barri', flat=True) bDocGen.setStyleSheet("Text-align: left") bMapaXarxa = QvPushButton('Xarxa quotidiana', flat=True) bMapaXarxa.setStyleSheet("Text-align: left") bMapaXarxa.hide() lytMarxes.addWidget(lDocuments) lytMarxes.addWidget(bGuia) lytMarxes.addWidget(bMapa) lytMarxes.addWidget(bDocGen) # lytMarxes.addWidget(bMarxes) lytMarxes.addWidget(bMapaXarxa) spacer = QSpacerItem(50, 50, QSizePolicy.Expanding, QSizePolicy.Maximum) lytMarxes.addItem(spacer) lytMarxes.addWidget(lBarris) lytMarxes.addWidget(lBarris2) bMarxes1 = QvPushButton(' el Coll', flat=True) bMarxes1.setStyleSheet("Text-align: left") bMarxes2 = QvPushButton(' la Salut', flat=True) bMarxes2.setStyleSheet("Text-align: left") bMarxes3 = QvPushButton(' el Besós i el Maresme', flat=True) bMarxes3.setStyleSheet("Text-align: left") bMarxes4 = QvPushButton(' el Bon Pastor', flat=True) bMarxes4.setStyleSheet("Text-align: left") bMarxes5 = QvPushButton(' la Trinitat Nova', flat=True) bMarxes5.setStyleSheet("Text-align: left") bMarxes6 = QvPushButton(' la Trinitat Vella', flat=True) bMarxes6.setStyleSheet("Text-align: left") bMarxes7 = QvPushButton(' la Vila de Gràcia', flat=True) bMarxes7.setStyleSheet("Text-align: left") bMarxes8 = QvPushButton(' Vallcarca', flat=True) bMarxes8.setStyleSheet("Text-align: left") bMarxes9 = QvPushButton(' la Marina del Prat Vermell', flat=True) bMarxes9.setStyleSheet("Text-align: left") bMarxes10 = QvPushButton(' el Camp del Grassot', flat=True) bMarxes10.setStyleSheet("Text-align: left") bMarxes11 = QvPushButton(' la Verneda i la Pau', flat=True) bMarxes11.setStyleSheet("Text-align: left") bMarxes1_1 = QvPushButton('Districte de Gràcia (totes les marxes)', flat=True) bMarxes1_1.setStyleSheet("Text-align: left") bMarxes1_2 = QvPushButton('la Trinitat Nova', flat=True) bMarxes1_2.setStyleSheet("Text-align: left") bMarxes1_3 = QvPushButton('la Trinitat Vella', flat=True) bMarxes1_3.setStyleSheet("Text-align: left") bMarxes1_4 = QvPushButton('el Bon Pastor', flat=True) bMarxes1_4.setStyleSheet("Text-align: left") bMarxes1_5 = QvPushButton('la Verneda i la Pau', flat=True) bMarxes1_5.setStyleSheet("Text-align: left") bMarxes1_6 = QvPushButton('el Besós i el Maresme', flat=True) bMarxes1_6.setStyleSheet("Text-align: left") bMarxes1_7 = QvPushButton('la Marina del Prat Vermell', flat=True) bMarxes1_7.setStyleSheet("Text-align: left") # Retorns bMarxes2_1 = QvPushButton('la Trinittat Vella', flat=True) bMarxes2_1.setStyleSheet("Text-align: left") bMarxes2_2 = QvPushButton('el Bon Pastor', flat=True) bMarxes2_2.setStyleSheet("Text-align: left") lytMarxes.addWidget(lBarris2) lytMarxes.addWidget(bMarxes1) lytMarxes.addWidget(bMarxes2) lytMarxes.addWidget(bMarxes7) lytMarxes.addWidget(bMarxes10) lytMarxes.addWidget(bMarxes8) lytMarxes.addWidget(bMarxes5) lytMarxes.addWidget(bMarxes6) lytMarxes.addWidget(bMarxes4) lytMarxes.addWidget(bMarxes11) lytMarxes.addWidget(bMarxes3) lytMarxes.addWidget(bMarxes9) lytMarxes.addItem(spacer) lytMarxes.addWidget(lBarris3) lytMarxes.addWidget(bMarxes1_1) lytMarxes.addWidget(bMarxes1_2) lytMarxes.addWidget(bMarxes1_3) lytMarxes.addWidget(bMarxes1_4) lytMarxes.addWidget(bMarxes1_5) lytMarxes.addWidget(bMarxes1_6) lytMarxes.addWidget(bMarxes1_7) lytMarxes.addItem(spacer) lytMarxes.addWidget(lBarris4) lytMarxes.addWidget(bMarxes2_1) lytMarxes.addWidget(bMarxes2_2) bGuia.clicked.connect(self.mostrarGuia) # bMarxes.clicked.connect(self.mostrarInstruccions) bMapa.clicked.connect(self.mostrarMapa) bDocGen.clicked.connect(self.mostrarDocGen) bMapaXarxa.clicked.connect(self.mostrarMapaXarxa) bMarxes1.clicked.connect(self.mostrarColl) bMarxes2.clicked.connect(self.mostrarSalut) bMarxes3.clicked.connect(self.mostrarBesos) bMarxes4.clicked.connect(self.mostrarBonPastor) bMarxes5.clicked.connect(self.mostrarTNova) bMarxes6.clicked.connect(self.mostrarTVella) bMarxes7.clicked.connect(self.mostrarGracia) bMarxes8.clicked.connect(self.mostrarVallcarca) bMarxes9.clicked.connect(self.mostrarMarina) bMarxes10.clicked.connect(self.mostrarGrassot) bMarxes11.clicked.connect(self.mostrarVerneda) bMarxes1_1.clicked.connect(self.mostrarInformeG) bMarxes1_2.clicked.connect(self.mostrarInformeTN) bMarxes1_3.clicked.connect(self.mostrarInformeTV) bMarxes1_4.clicked.connect(self.mostrarInformeBP) bMarxes1_5.clicked.connect(self.mostrarInformeVP) bMarxes1_6.clicked.connect(self.mostrarInformeBM) bMarxes1_7.clicked.connect(self.mostrarInformeMPV) bMarxes2_1.clicked.connect(self.mostrarRetornTrinitatVella) bMarxes2_2.clicked.connect(self.mostrarRetornBonPastor) # self.browserMarxes = QWebView() # self.browserMarxes.settings().setAttribute(QWebSettings.PluginsEnabled, True) # self.browserMarxes.settings().setAttribute(QWebSettings.JavascriptEnabled, True) # self.browserMarxes.settings().setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True) # self.browserMarxes.show() # # browserPavim.setUrl(QUrl('CatalegPavim.pdf')) # # QDesktopServices().openUrl(QUrl('CatalegPavim.pdf')) # lytMarxes.addWidget(self.browserMarxes) self.setAllowedAreas(Qt.RightDockWidgetArea | Qt.LeftDockWidgetArea) self.setWidget(fMarxes) self.setContentsMargins(0, 0, 0, 0) self.show() """