def data(self, index, role): if role not in [Qt.DisplayRole, Qt.EditRole, Qt.FontRole]: return None val = self.getData(index.row(), index.column()) if role == Qt.EditRole: return val if role == Qt.FontRole: # draw NULL in italic if val is not None: return None f = QFont() f.setItalic(True) return f if val is None: return "NULL" elif isinstance(val, memoryview): # hide binary data return None elif isinstance(val, str) and len(val) > 300: # too much data to display, elide the string val = val[:300] try: return str(val) # convert to Unicode except UnicodeDecodeError: return str(val, 'utf-8', 'replace') # convert from utf8 and replace errors (if any)
def test_letter_spacing(self): # Modified letter spacing font = QFont(self._TestFont) font.setLetterSpacing(QFont.AbsoluteSpacing, 3.5) font.setPointSizeF(30) self.lyr.textFont = font self.checkTest()
def test_word_spacing(self): # Modified word spacing font = QFont(self._TestFont) font.setPointSizeF(30) font.setWordSpacing(20.5) self.lyr.textFont = font self.checkTest()
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) # unselected widget self.unselected_widget = QListWidget(self) self._set_list_widget_defaults(self.unselected_widget) unselected_label = QLabel() unselected_label.setText("Unselected") unselected_label.setAlignment(Qt.AlignCenter) unselected_label.setFont(italic_font) unselected_v_layout = QVBoxLayout() unselected_v_layout.addWidget(unselected_label) unselected_v_layout.addWidget(self.unselected_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(unselected_v_layout) self.main_horizontal_layout.addLayout(self.buttons_vertical_layout) self.main_horizontal_layout.addLayout(selected_v_layout)
def test_partials_labels_disabled(self): # Set Big font size font = QFont(self._TestFont) font.setPointSizeF(84) self.lyr.textFont = font # Disable partials labels self._Pal.setShowingPartialsLabels(False) self._Pal.saveEngineSettings() self.checkTest()
def test_text_size_map_unit(self): # Label text size in map units self.lyr.fontSizeInMapUnits = True font = QFont(self._TestFont) font.setPointSizeF(460) self.lyr.textFont = font self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest()
def test_letter_spacing(self): # Modified letter spacing format = self.lyr.format() font = QFont(self._TestFont) font.setLetterSpacing(QFont.AbsoluteSpacing, 3.5) format.setFont(font) format.setSize(30) self.lyr.setFormat(format) self.checkTest()
def test_word_spacing(self): # Modified word spacing format = self.lyr.format() font = QFont(self._TestFont) font.setWordSpacing(20.5) format.setFont(font) format.setSize(30) self.lyr.setFormat(format) self.checkTest()
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 commitClicked(self): feature = self.listWidget.currentItem().feature geom = None self.attributesTable.setRowCount(len(feature)) for idx, attrname in enumerate(feature): value = feature[attrname] font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(attrname) item.setFont(font) self.attributesTable.setItem(idx, 0, item); self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value))); if geom is None: try: geom = QgsGeometry.fromWkt(value) except: pass self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True) settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') types = ["Point", "LineString", "Polygon"] layers = [] if geom is not None: geomtype = types[int(geom.type())] layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp", "memory") pr = layer.dataProvider() feat = QgsFeature() feat.setGeometry(geom) pr.addFeatures([feat]) layer.updateExtents() layer.selectAll() layer.setExtent(layer.boundingBoxOfSelected()) layer.invertSelection() symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(Qt.green) symbol.setAlpha(0.5) if QGis.QGIS_VERSION_INT < 29900: layer.setRendererV2(QgsSingleSymbolRendererV2(symbol)) else: layer.setRenderer(QgsSingleSymbolRenderer(symbol)) self.mapCanvas.setRenderFlag(False) self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)]) QgsMapLayerRegistry.instance().addMapLayer(layer, False) self.mapCanvas.setExtent(layer.extent()) self.mapCanvas.setRenderFlag(True) layers.append(layer) else: self.mapCanvas.setLayerSet([]) settings.setValue('/Projections/defaultBehaviour', prjSetting)
def test_partials_labels_enabled(self): # Set Big font size font = QFont(self._TestFont) font.setPointSizeF(84) self.lyr.textFont = font # Enable partials labels self._Pal.setShowingPartialsLabels(True) self._Pal.saveEngineSettings() self._Mismatches['TestCanvasPoint'] = 779 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest()
def getAdjustedText(self, text): font = QFont('Verdana', 8) font.setPixelSize(12) fm = QFontMetricsF(font) w = fm.width(text) if w < self.BOX_WIDTH - 25 - FlatButtonGraphicItem.WIDTH: return text text = text[0:-3] + '…' w = fm.width(text) while w > self.BOX_WIDTH - 25 - FlatButtonGraphicItem.WIDTH: text = text[0:-4] + '…' w = fm.width(text) return text
def getLinkPointForParameter(self, paramIndex): offsetX = 25 if isinstance(self.element, Algorithm) and self.element.paramsFolded: paramIndex = -1 offsetX = 17 font = QFont('Verdana', 8) font.setPixelSize(12) fm = QFontMetricsF(font) if isinstance(self.element, Algorithm): h = -(fm.height() * 1.2) * (paramIndex + 2) - fm.height() / 2.0 + 8 h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 else: h = 0 return QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + offsetX, h)
def getLinkPointForOutput(self, outputIndex): if isinstance(self.element, Algorithm) and self.element.algorithm.outputs: outputIndex = (outputIndex if not self.element.outputsFolded else -1) text = self.getAdjustedText(self.element.algorithm.outputs[outputIndex].description) font = QFont('Verdana', 8) font.setPixelSize(12) fm = QFontMetricsF(font) w = fm.width(text) h = fm.height() * 1.2 * (outputIndex + 1) + fm.height() / 2.0 y = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 x = (-ModelerGraphicItem.BOX_WIDTH / 2 + 33 + w + 5 if not self.element.outputsFolded else 10) return QPointF(x, y) else: return QPointF(0, 0)
def boundingRect(self): font = QFont('Verdana', 8) font.setPixelSize(12) fm = QFontMetricsF(font) unfolded = isinstance(self.element, Algorithm) and not self.element.paramsFolded numParams = len(self.element.algorithm.parameters) if unfolded else 0 unfolded = isinstance(self.element, Algorithm) and not self.element.outputsFolded numOutputs = len(self.element.algorithm.outputs) if unfolded else 0 hUp = fm.height() * 1.2 * (numParams + 2) hDown = fm.height() * 1.2 * (numOutputs + 2) rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp, ModelerGraphicItem.BOX_WIDTH + 2, ModelerGraphicItem.BOX_HEIGHT + hDown + hUp) return rect
def boundingRect(self): font = QFont('Verdana', 8) font.setPixelSize(12) fm = QFontMetricsF(font) unfolded = isinstance(self.element, QgsProcessingModelChildAlgorithm) and not self.element.parametersCollapsed() numParams = len([a for a in self.element.algorithm().parameterDefinitions() if not a.isDestination()]) if unfolded else 0 unfolded = isinstance(self.element, QgsProcessingModelChildAlgorithm) and not self.element.outputsCollapsed() numOutputs = len(self.element.algorithm().outputDefinitions()) if unfolded else 0 hUp = fm.height() * 1.2 * (numParams + 2) hDown = fm.height() * 1.2 * (numOutputs + 2) rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp, ModelerGraphicItem.BOX_WIDTH + 2, ModelerGraphicItem.BOX_HEIGHT + hDown + hUp) return rect
def list_compatible_canvas_layers(self): """Fill the list widget with compatible layers. :returns: Metadata of found layers. :rtype: list of dicts """ italic_font = QFont() italic_font.setItalic(True) list_widget = self.lstCanvasExpLayers # Add compatible layers list_widget.clear() for layer in self.parent.get_compatible_canvas_layers('exposure'): item = QListWidgetItem(layer['name'], list_widget) item.setData(Qt.UserRole, layer['id']) if not layer['keywords']: item.setFont(italic_font) list_widget.addItem(item)
def test_background_svg(self): # Label SVG background self.lyr.fontSizeInMapUnits = True font = QFont(self._TestFont) font.setPointSizeF(460) self.lyr.textFont = font self.lyr.shapeDraw = True self.lyr.shapeType = QgsPalLayerSettings.ShapeSVG svg = os.path.join(svgSymbolsPath(), "backgrounds", "background_square.svg") self.lyr.shapeSVGFile = svg self.lyr.shapeSizeUnits = QgsPalLayerSettings.MapUnits self.lyr.shapeSizeType = QgsPalLayerSettings.SizeBuffer self.lyr.shapeSize = QPointF(100.0, 0.0) self._Mismatches["TestComposerPdfVsComposerPoint"] = 580 self._Mismatches["TestCanvasPoint"] = 776 self._ColorTols["TestComposerPdfPoint"] = 2 self.checkTest()
def polygon(self): font = QFont('Verdana', 8) font.setPixelSize(12) fm = QFontMetricsF(font) hUp = fm.height() * 1.2 * (len(self.element.parameters) + 2) hDown = fm.height() * 1.2 * (len(self.element.outputs) + 2) pol = QPolygonF([ QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp), QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, (ModelerGraphicItem.BOX_HEIGHT + 2) / 2 + hDown), QPointF((ModelerGraphicItem.BOX_WIDTH + 2) / 2, (ModelerGraphicItem.BOX_HEIGHT + 2) / 2 + hDown), QPointF((ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp), QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp) ]) return pol
def test_background_rect_w_offset(self): # Label rectangular background self._Mismatches['TestComposerImageVsCanvasPoint'] = 800 self._Mismatches['TestComposerImagePoint'] = 800 # verify fix for issues # http://hub.qgis.org/issues/9057 # http://gis.stackexchange.com/questions/86900 self.lyr.fontSizeInMapUnits = True font = QFont(self._TestFont) font.setPointSizeF(460) self.lyr.textFont = font self.lyr.shapeDraw = True self.lyr.shapeOffsetUnits = QgsPalLayerSettings.MapUnits self.lyr.shapeOffset = QPointF(-2900.0, -450.0) self._Mismatches['TestCanvasPoint'] = 774 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest()
def setFonts(self, size): # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', size)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) 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)
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(20) self.setFont(font) self.setMarginsFont(font) self.initLexer() 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.setFonts(10)
def setFonts(self, size): # Load font from Python console settings settings = QSettings() fontName = settings.value("pythonConsole/fontfamilytext", "Monospace") fontSize = int(settings.value("pythonConsole/fontsize", size)) 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)
def __init__(self, data=None): """Constructor.""" super(ProfileWidget, self).__init__() # Attributes self.widget_items = [] # Set data if data: self.data = data # Set header self.header_tree_widget = QTreeWidgetItem( [tr('Classification'), tr('Affected'), tr('Displacement Rate')]) header_font = QFont() header_font.setBold(True) header_font.setPointSize(14) self.header_tree_widget.setFont(0, header_font) self.header_tree_widget.setFont(1, header_font) self.header_tree_widget.setFont(2, header_font) self.setHeaderItem(self.header_tree_widget) self.header().setSectionResizeMode(0, QHeaderView.Stretch) self.header().setSectionResizeMode(1, QHeaderView.Fixed) self.header().setSectionResizeMode(2, QHeaderView.ResizeToContents) self.header().setSectionsMovable(False)
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)
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 _setMinimumHeight(self): fnt = self.settings.value("pythonConsole/fontfamilytext", "Monospace") fntSize = self.settings.value("pythonConsole/fontsize", 10, type=int) fm = QFontMetrics(QFont(fnt, fntSize)) self.setMinimumHeight(fm.height() + 10)
class ScaleBarItem(QGraphicsItem): def __init__(self, canvas, parent=None): super(ScaleBarItem, self).__init__(parent) self.canvas = canvas self.realsize = 100 black = QColor(Qt.black) black.setAlpha(150) white = QColor(Qt.white) white.setAlpha(150) blackpen = QPen(black, 4) whitepen = QPen(white, 8) self.pens = [whitepen, blackpen] self.whitepen = QPen(white, 1) self.blackbrush = QBrush(black) self.ticksize = 10 self.fontsize = 15 self.font = QFont() self.font.setPointSize(self.fontsize) self.font.setStyleHint(QFont.Times, QFont.PreferAntialias) self.font.setBold(True) self.metrics = QFontMetrics(self.font) def boundingRect(self): try: width, realsize, label, fontsize = self._calc_size() halfheight = (self.ticksize + fontsize[1]) / 2 halfwidth = (width + fontsize[0]) / 2 return QRectF(-halfwidth, -halfheight, halfwidth, halfheight) except ZeroDivisionError: return QRectF() def paint(self, painter, styleoptions, widget=None): try: width, realsize, label, fontsize = self._calc_size() except ZeroDivisionError: return mapunits = self.canvas.mapUnits() # painter.drawRect(self.boundingRect()) array = QPolygon() canvasheight = self.canvas.height() canvaswidth = self.canvas.width() margin = 20 originy = 0 originx = 0 self.setPos(margin, canvasheight - margin) x1, y1 = originx, originy x2, y2 = originx, originy + self.ticksize x3, y3 = originx + width, originy + self.ticksize midx, midy = originx + width / 2, originy + self.ticksize / 2 x4, y4 = originx + width, originy for pen in self.pens: painter.setPen(pen) # Drwa the scale bar painter.drawLine(x1, y1, x2, y2) painter.drawLine(x2, y2, x3, y3) painter.drawLine(x3, y3, x4, y4) painter.drawLine(midx, midy, midx, y1) # Draw the text fontwidth = self.metrics.width("0") fontheight = self.metrics.height() fontheight /= 2 fontwidth /= 2 path = QPainterPath() point = QPointF(x1 - fontwidth, y1 - fontheight) path.addText(point, self.font, "0") painter.setPen(self.whitepen) painter.setBrush(self.blackbrush) painter.setRenderHints(QPainter.Antialiasing) painter.setFont(self.font) painter.drawPath(path) fontwidth = self.metrics.width(label) fontheight = self.metrics.height() fontheight /= 2 fontwidth /= 2 point = QPointF(x4 - fontwidth, y4 - fontheight) path.addText(point, self.font, label) painter.drawPath(path) def _calc_size(self): realSize = self.realsize canvaswidth = self.canvas.width() mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel()) mapunits = self.canvas.mapUnits() prefered_units = roam.config.settings.get("prefer_units", "meters") newunits = Qgis.fromLiteral(prefered_units, Qgis.Meters) mapunitsperpixel *= Qgis.fromUnitToUnitFactor(mapunits, newunits) mapunits = newunits # Convert the real distance into pixels barwidth = realSize / mapunitsperpixel if barwidth < 30: barwidth = canvaswidth / 4 while barwidth > canvaswidth / 3: barwidth /= 3 realSize = barwidth * mapunitsperpixel # Round powerof10 = math.floor(math.log10(realSize)) scaler = math.pow(10.0, powerof10) realSize = round(realSize / scaler) * scaler barwidth = realSize / mapunitsperpixel label, realSize = self._label_size(mapunits, realSize) metrics = QFontMetrics(self.font) fontwidth = metrics.width(label) fontheight = metrics.height() sizelabel = QLocale.system().toString(realSize) sizelabel = "{} {}".format(sizelabel, label) barwidth = self._adjust_bar_size(barwidth, mapunits) barwidth = barwidth + fontwidth return barwidth, realSize, sizelabel, (fontwidth, fontheight) def _label_size(self, unit, currentsize): if unit == Qgis.Meters: if currentsize > 1000: return "km", currentsize / 1000 elif currentsize < 0.01: return "mm", currentsize * 1000 elif currentsize < 0.1: return "cm", currentsize * 100 else: return "m", currentsize elif unit == Qgis.Feet: print(currentsize) if currentsize > 5280.0: return "miles", currentsize / 5000 elif currentsize == 5280.0: return "mile", currentsize / 5000 elif currentsize < 1: return "inches", currentsize * 10 elif currentsize == 1.0: return "foot", currentsize else: return "feet", currentsize elif unit == Qgis.Degrees: if currentsize == 1.0: return "degree", currentsize else: return "degrees", currentsize else: return str(unit), currentsize def _adjust_bar_size(self, barsize, unit): if unit == Qgis.Feet: if barsize > 5280.0 or barsize == 5280.0: return (barsize * 5290) / 5000 elif barsize < 1: return (barsize * 10) / 12 return barsize
class EnforceAttributeRulesAlgorithm(QgsProcessingAlgorithm): """ Algorithm for applying user-defined attribute rules to verify the filling of database attributes. """ RULES_SET = "RULES_SET" SELECTED = "SELECTED" POINT_FLAGS = "POINT_FLAGS" LINE_FLAGS = "LINE_FLAGS" POLYGON_FLAGS = "POLYGON_FLAGS" def __init__(self): """ Constructor. """ super().__init__() self.valAlg = ValidationAlgorithm() self.flagFields = self.valAlg.getFlagFields() self.font = QFont() self.font.setBold(True) self.conditionalStyle = QgsConditionalStyle() def initAlgorithm(self, config): """ Parameter setting. """ attributeRulesSetter = ParameterAttributeRulesSet( self.RULES_SET, description=self.tr("Attribute Rules Set") ) attributeRulesSetter.setMetadata({ "widget_wrapper": "DsgTools.gui.ProcessingUI.enforceAttributeRulesWrapper.EnforceAttributeRulesWrapper" }) self.addParameter(attributeRulesSetter) self.addParameter( QgsProcessingParameterBoolean( self.SELECTED, self.tr("Process only selected features") ) ) self.addParameter( QgsProcessingParameterFeatureSink( self.POINT_FLAGS, self.tr("Point flags") ) ) self.addParameter( QgsProcessingParameterFeatureSink( self.LINE_FLAGS, self.tr("Linestring flags") ) ) self.addParameter( QgsProcessingParameterFeatureSink( self.POLYGON_FLAGS, self.tr("Polygon flags") ) ) def parameterAsAttributeRulesSet(self, parameters, name, context): """ Adds data from wrapper to algorithm parameters. :param parameters: (QgsProcessingParameter) a set of algorithm parameters; :param name: (json) JSON formatted attribute rules; :param context: (QgsProcessingContext) context in which processing was run; :return: (dict) parameters dictionary. """ return parameters[name] def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. :param parameters: (QgsProcessingParameter) a set of algorithm parameters. :param context: (QgsProcessingContext) context in which processing was run. :param feedback: (QgsProcessingFeedback) QGIS progress tracking component. :return: (dict) filled flag layers. """ rules = self.parameterAsAttributeRulesSet( parameters, self.RULES_SET, context ) if not rules: raise QgsProcessingException( self.invalidSourceError(parameters, self.RULES_SET) ) onlySelected = self.parameterAsBool( parameters, self.SELECTED, context) crs = QgsProject.instance().crs() pointFlags, ptId = self.parameterAsSink( parameters, self.POINT_FLAGS, context, self.flagFields, QgsWkbTypes.Point, crs) if not pointFlags: raise QgsProcessingException( self.invalidSourceError(parameters, self.POINT_FLAGS)) lineFlags, lId = self.parameterAsSink( parameters, self.LINE_FLAGS, context, self.flagFields, QgsWkbTypes.LineString, crs) if not lineFlags: raise QgsProcessingException( self.invalidSourceError(parameters, self.LINE_FLAGS)) polygonFlags, polId = self.parameterAsSink( parameters, self.POLYGON_FLAGS, context, self.flagFields, QgsWkbTypes.Polygon, crs) if not polygonFlags: raise QgsProcessingException( self.invalidSourceError(parameters, self.POLYGON_FLAGS)) failedFeatures = self.applyAttrRules(rules, onlySelected) self.flagsFromFailedList(failedFeatures, pointFlags, lineFlags, polygonFlags, feedback) return { self.POINT_FLAGS: ptId, self.LINE_FLAGS: lId, self.POLYGON_FLAGS: polId} def applyAttrRules(self, attrRulesMap, onlySelected): """ Filters a layer or a set of selected features as from conditional rules, and the result is added to a list in a dictionary. :param attrRulesMap: (dict) dictionary with conditional rules; :param onlySelected: (boolean) indicates whether the attribute rules should be applied exclusively on selected features of each verified layer; :return: (dict) modified attrRulesMap with filtered features. """ proj = QgsProject.instance() for ruleOrder, ruleParam in attrRulesMap.items(): if onlySelected: lyr = proj.mapLayersByName(ruleParam["layerField"][0])[0] request = QgsFeatureRequest().setFilterExpression( ruleParam["expression"]) selectedFeatures = lyr.getSelectedFeatures(request) ruleParam["features"] = [ feature for feature in selectedFeatures] else: lyr = proj.mapLayersByName(ruleParam["layerField"][0])[0] ruleParam["features"] = [ feature for feature in lyr.getFeatures(ruleParam["expression"])] self.applyConditionalStyle(proj.mapLayersByName( ruleParam["layerField"][0])[0], ruleParam) return attrRulesMap def flagsFromFailedList(self, attrRulesMap, ptLayer, lLayer, polLayer, feedback): """ Creates new features from a failed conditional rules dictionary. :param attrRulesMap: (dict) dictionary with conditional rules; :param ptLayer: (QgsVectorLayer) output point vector layer; :param lLayer: (QgsVectorLayer) output line vector layer; :param polLayer: (QgsVectorLayer) output polygon vector layer; :param feedback: (QgsProcessingFeedback) QGIS progress tracking component; :return: (tuple-of-QgsVectorLayer) filled flag layers. """ layerMap = { QgsWkbTypes.PointGeometry: ptLayer, QgsWkbTypes.LineGeometry: lLayer, QgsWkbTypes.PolygonGeometry: polLayer } for ruleParam in attrRulesMap.values(): flagText = "{name}".format(name=ruleParam["description"]) for flag in ruleParam["features"]: geom = flag.geometry() newFeature = QgsFeature(self.flagFields) newFeature["reason"] = flagText newFeature.setGeometry(geom) layerMap[geom.type()].addFeature( newFeature, QgsFeatureSink.FastInsert ) self.logResult(attrRulesMap, feedback) return (ptLayer, lLayer, polLayer) def applyConditionalStyle(self, lyr, values): """ Applies a conditional style for each wrong attribute in the attribute table. :param lyr: (QgsVectorLayer) vector layer; :param values: (dict) dictionary with conditional rules. """ self.conditionalStyle.setRule(values["expression"]) self.conditionalStyle.setFont(self.font) self.conditionalStyle.setTextColor(QColor(255, 255, 255)) for field in lyr.fields(): if field.name() in values["layerField"]: if isinstance(values["color"], (list, tuple)): self.conditionalStyle.setBackgroundColor( QColor( values["color"][0], values["color"][1], values["color"][2])) else: self.conditionalStyle.setBackgroundColor( QColor(values["color"])) lyr.conditionalStyles().setFieldStyles( field.name(), [self.conditionalStyle]) def logResult(self, attrRulesMap, feedback): """ Creates a statistics text log from each layer and your respectively wrong attribute. :param attrRulesMap: (dict) dictionary with conditional rules; :param feedback: (QgsProcessingFeedback) QGIS progress tracking component. """ feedback.pushInfo("{0} {1} {0}\n".format( "===" * 5, self.tr("LOG START"))) for ruleParam in attrRulesMap.values(): if len(ruleParam["features"]) > 0: row = self.tr("[RULE]") + ": {0} - {1}\n{2}: {3} {4}\n".format( ruleParam["layerField"][1], ruleParam["errorType"], ruleParam["layerField"][0], len(ruleParam["features"]), self.tr("features") if len(ruleParam["features"]) > 1 else self.tr("feature")) feedback.pushInfo(row) else: pass feedback.pushInfo("{0} {1} {0}\n".format( "===" * 5, self.tr("LOG END"))) def name(self): """ Returns the algorithm name, used for identifying the algorithm. This string should be fixed for the algorithm, and must not be localised. The name should be unique within each provider. Names should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return "enforceattributerulesalgorithm" def displayName(self): """ Returns the translated algorithm name, which should be used for any user-visible display of the algorithm name. """ return self.tr("Enforce Attribute Rules") def group(self): """ Returns the name of the group this algorithm belongs to. This string should be localised. """ return self.tr("Quality Assurance Tools (Identification Processes)") def groupId(self): """ Returns the unique ID of the group this algorithm belongs to. This string should be fixed for the algorithm, and must not be localised. The group id should be unique within each provider. Group id should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return "DSGTools: Quality Assurance Tools (Identification Processes)" def tr(self, string): """ Returns a translatable string with the self.tr() function. """ return QCoreApplication.translate("EnforceAttributeRulesAlgorithm", string) def createInstance(self): """ Must return a new copy of your algorithm. """ return EnforceAttributeRulesAlgorithm()
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 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 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, QgsProcessingModelParameter): color = QColor(238, 242, 131) stroke = QColor(234, 226, 118) selected = QColor(116, 113, 68) elif isinstance(self.element, QgsProcessingModelChildAlgorithm): 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, QgsProcessingModelChildAlgorithm) 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, QgsProcessingModelChildAlgorithm): 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 restoreSettings(self): settings = QSettings() self.spinBox.setValue( settings.value("pythonConsole/fontsize", 10, type=int)) self.spinBoxEditor.setValue( settings.value("pythonConsole/fontsizeEditor", 10, type=int)) self.fontComboBox.setCurrentFont( QFont(settings.value("pythonConsole/fontfamilytext", "Monospace"))) self.fontComboBoxEditor.setCurrentFont( QFont( settings.value("pythonConsole/fontfamilytextEditor", "Monospace"))) 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)))
class ScriptEdit(QsciScintilla): DEFAULT_COLOR = "#4d4d4c" KEYWORD_COLOR = "#8959a8" CLASS_COLOR = "#4271ae" METHOD_COLOR = "#4271ae" DECORATION_COLOR = "#3e999f" NUMBER_COLOR = "#c82829" COMMENT_COLOR = "#8e908c" COMMENT_BLOCK_COLOR = "#8e908c" BACKGROUND_COLOR = "#ffffff" CURSOR_COLOR = "#636363" CARET_LINE_COLOR = "#efefef" SINGLE_QUOTE_COLOR = "#718c00" DOUBLE_QUOTE_COLOR = "#718c00" TRIPLE_SINGLE_QUOTE_COLOR = "#eab700" TRIPLE_DOUBLE_QUOTE_COLOR = "#eab700" MARGIN_BACKGROUND_COLOR = "#efefef" MARGIN_FOREGROUND_COLOR = "#636363" SELECTION_BACKGROUND_COLOR = "#d7d7d7" SELECTION_FOREGROUND_COLOR = "#303030" MATCHED_BRACE_BACKGROUND_COLOR = "#b7f907" MATCHED_BRACE_FOREGROUND_COLOR = "#303030" EDGE_COLOR = "#efefef" FOLD_COLOR = "#efefef" def __init__(self, parent=None): QsciScintilla.__init__(self, parent) self.lexer = None self.api = None self.setCommonOptions() self.initShortcuts() def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) settings = QgsSettings() # Default font font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setMatchedBraceBackgroundColor( QColor( settings.value( "pythonConsole/matchedBraceBackgroundColorEditor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR)))) self.setMatchedBraceForegroundColor( QColor( settings.value( "pythonConsole/matchedBraceForegroundColorEditor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR)))) #self.setWrapMode(QsciScintilla.WrapWord) #self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, # QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor( QColor( settings.value("pythonConsole/selectionForegroundColorEditor", QColor(self.SELECTION_FOREGROUND_COLOR)))) self.setSelectionBackgroundColor( QColor( settings.value("pythonConsole/selectionBackgroundColorEditor", QColor(self.SELECTION_BACKGROUND_COLOR)))) # Show line numbers fontmetrics = QFontMetrics(font) self.setMarginWidth(1, fontmetrics.width("0000") + 5) self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor( QColor( settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setMarginsBackgroundColor( QColor( settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) self.setIndentationGuidesForegroundColor( QColor( settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setIndentationGuidesBackgroundColor( QColor( settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) # Highlight current line caretLineColorEditor = settings.value( "pythonConsole/caretLineColorEditor", QColor(self.CARET_LINE_COLOR)) cursorColorEditor = settings.value("pythonConsole/cursorColorEditor", QColor(self.CURSOR_COLOR)) self.setCaretLineVisible(True) self.setCaretWidth(2) self.setCaretLineBackgroundColor(caretLineColorEditor) self.setCaretForegroundColor(cursorColorEditor) # Folding self.setFolding(QsciScintilla.PlainFoldStyle) foldColor = QColor( settings.value("pythonConsole/foldColorEditor", QColor(self.FOLD_COLOR))) self.setFoldMarginColors(foldColor, foldColor) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor( QColor( settings.value("pythonConsole/edgeColorEditor", QColor(self.EDGE_COLOR)))) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) self.setIndentationGuides(True) # Autocomletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setFonts(10) self.initLexer() def setFonts(self, size): # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', size)) 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) def initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut( QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def initLexer(self): settings = QgsSettings() self.lexer = QsciLexerPython() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) loadFont = settings.value("pythonConsole/fontfamilytextEditor") if loadFont: font.setFamily(loadFont) fontSize = settings.value("pythonConsole/fontsizeEditor", type=int) if fontSize: font.setPointSize(fontSize) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR)))) self.lexer.setColor( QColor( settings.value("pythonConsole/commentFontColorEditor", QColor(self.COMMENT_COLOR))), 1) self.lexer.setColor( QColor( settings.value("pythonConsole/numberFontColorEditor", QColor(self.NUMBER_COLOR))), 2) self.lexer.setColor( QColor( settings.value("pythonConsole/keywordFontColorEditor", QColor(self.KEYWORD_COLOR))), 5) self.lexer.setColor( QColor( settings.value("pythonConsole/classFontColorEditor", QColor(self.CLASS_COLOR))), 8) self.lexer.setColor( QColor( settings.value("pythonConsole/methodFontColorEditor", QColor(self.METHOD_COLOR))), 9) self.lexer.setColor( QColor( settings.value("pythonConsole/decorFontColorEditor", QColor(self.DECORATION_COLOR))), 15) self.lexer.setColor( QColor( settings.value("pythonConsole/commentBlockFontColorEditor", QColor(self.COMMENT_BLOCK_COLOR))), 12) self.lexer.setColor( QColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(self.SINGLE_QUOTE_COLOR))), 4) self.lexer.setColor( QColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(self.DOUBLE_QUOTE_COLOR))), 3) self.lexer.setColor( QColor( settings.value( "pythonConsole/tripleSingleQuoteFontColorEditor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6) self.lexer.setColor( QColor( settings.value( "pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7) self.lexer.setColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))), 13) self.lexer.setFont(font, 1) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) self.lexer.setFont(font, QsciLexerPython.UnclosedString) for style in range(0, 33): paperColor = QColor( settings.value("pythonConsole/paperBackgroundColorEditor", QColor(self.BACKGROUND_COLOR))) self.lexer.setPaper(paperColor, style) self.api = QsciAPIs(self.lexer) useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer)
def getTestFont(cls): return QFont(cls._TestFont)
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 = dict() for i in range(self.trw_layers.topLevelItemCount()): top_level_items_expanded_info[self.trw_layers.topLevelItem(i).text( 0)] = 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[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN and not show_domains \ or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE and not show_structures \ or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.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[ QueryNames.GEOMETRY_TYPE_MODEL_BAKER]) ) if current_table_info[ QueryNames.GEOMETRY_TYPE_MODEL_BAKER] else None icon_name = self.icon_names[ 3 if geometry_type is None else geometry_type] # Is the layer already loaded in canvas? if self.app.core.get_ladm_layer_from_qgis( self._db, current_table_info[QueryNames.TABLE_NAME_MODEL_BAKER], EnumLayerRegistryType.IN_LAYER_TREE) 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[ QueryNames. KIND_SETTINGS_MODEL_BAKER]: # This is a class font = QFont() font.setBold(True) table_item.setData(0, Qt.FontRole, font) if current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN: icon_name = self.icon_names[4] elif current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE: if geometry_type is None: icon_name = self.icon_names[5] elif current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION: icon_name = self.icon_names[6] icon = QIcon(":/Asistente-LADM-COL/resources/images/{}".format( icon_name)) table_item.setData(0, Qt.DecorationRole, icon) children.append(table_item) if children: 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.get( self.trw_layers.topLevelItem(i).text(0), True)) self.trw_layers.setUpdatesEnabled(True) # Now render!
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.setFont(font, 1) 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.api = QsciAPIs(self.lexer) checkBoxAPI = self.settings.value("pythonConsole/preloadAPI", True, type=bool) checkBoxPreparedAPI = self.settings.value( "pythonConsole/usePreparedAPIFile", False, type=bool) if checkBoxAPI: pap = os.path.join(QgsApplication.pkgDataPath(), "python", "qsci_apis", "pyqgis.pap") self.api.loadPrepared(pap) elif checkBoxPreparedAPI: self.api.loadPrepared( self.settings.value("pythonConsole/preparedAPIFile")) else: apiPath = self.settings.value("pythonConsole/userAPI", []) for i in range(0, len(apiPath)): self.api.load(apiPath[i]) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer)
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)
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)
class ScriptEdit(QsciScintilla): LEXER_PYTHON = 0 LEXER_R = 1 def __init__(self, parent=None): QsciScintilla.__init__(self, parent) self.lexer = None self.api = None self.lexerType = -1 self.setCommonOptions() self.initShortcuts() def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(20) self.setFont(font) self.setMarginsFont(font) self.initLexer() 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.setFonts(10) def setFonts(self, size): # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', size)) 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) def initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut( QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def setLexerType(self, lexerType): self.lexerType = lexerType self.initLexer() def initLexer(self): if self.lexerType == self.LEXER_PYTHON: self.lexer = QsciLexerPython() colorDefault = QColor('#2e3436') colorComment = QColor('#c00') colorCommentBlock = QColor('#3465a4') colorNumber = QColor('#4e9a06') colorType = QColor('#4e9a06') colorKeyword = QColor('#204a87') colorString = QColor('#ce5c00') self.lexer.setDefaultFont(self.defaultFont) self.lexer.setDefaultColor(colorDefault) self.lexer.setColor(colorComment, 1) self.lexer.setColor(colorNumber, 2) self.lexer.setColor(colorString, 3) self.lexer.setColor(colorString, 4) self.lexer.setColor(colorKeyword, 5) self.lexer.setColor(colorString, 6) self.lexer.setColor(colorString, 7) self.lexer.setColor(colorType, 8) self.lexer.setColor(colorCommentBlock, 12) self.lexer.setColor(colorString, 15) self.lexer.setFont(self.italicFont, 1) self.lexer.setFont(self.boldFont, 5) self.lexer.setFont(self.boldFont, 8) self.lexer.setFont(self.italicFont, 12) self.api = QsciAPIs(self.lexer) settings = QgsSettings() useDefaultAPI = bool( settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer)
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)
class ScriptEdit(QsciScintilla): LEXER_PYTHON = 0 LEXER_R = 1 def __init__(self, parent=None): QsciScintilla.__init__(self, parent) self.lexer = None self.api = None self.lexerType = -1 self.setCommonOptions() self.initShortcuts() def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(20) self.setFont(font) self.setMarginsFont(font) self.initLexer() 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.setFonts(10) def setFonts(self, size): # Load font from Python console settings settings = QSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', size)) 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) def initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def setLexerType(self, lexerType): self.lexerType = lexerType self.initLexer() def initLexer(self): if self.lexerType == self.LEXER_PYTHON: self.lexer = QsciLexerPython() colorDefault = QColor('#2e3436') colorComment = QColor('#c00') colorCommentBlock = QColor('#3465a4') colorNumber = QColor('#4e9a06') colorType = QColor('#4e9a06') colorKeyword = QColor('#204a87') colorString = QColor('#ce5c00') self.lexer.setDefaultFont(self.defaultFont) self.lexer.setDefaultColor(colorDefault) self.lexer.setColor(colorComment, 1) self.lexer.setColor(colorNumber, 2) self.lexer.setColor(colorString, 3) self.lexer.setColor(colorString, 4) self.lexer.setColor(colorKeyword, 5) self.lexer.setColor(colorString, 6) self.lexer.setColor(colorString, 7) self.lexer.setColor(colorType, 8) self.lexer.setColor(colorCommentBlock, 12) self.lexer.setColor(colorString, 15) self.lexer.setFont(self.italicFont, 1) self.lexer.setFont(self.boldFont, 5) self.lexer.setFont(self.boldFont, 8) self.lexer.setFont(self.italicFont, 12) self.api = QsciAPIs(self.lexer) settings = QSettings() useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) elif self.lexerType == self.LEXER_R: # R lexer self.lexer = LexerR() self.setLexer(self.lexer)
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 __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 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()
class SqlEdit(QsciScintilla): LEXER_PYTHON = 0 LEXER_R = 1 def __init__(self, parent=None): QsciScintilla.__init__(self, parent) self.mylexer = None self.api = None self.setCommonOptions() self.initShortcuts() 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.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 initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut( QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def initLexer(self): self.mylexer = QsciLexerSQL() colorDefault = QColor('#2e3436') colorComment = QColor('#c00') colorCommentBlock = QColor('#3465a4') colorNumber = QColor('#4e9a06') colorType = QColor('#4e9a06') colorKeyword = QColor('#204a87') colorString = QColor('#ce5c00') self.mylexer.setDefaultFont(self.defaultFont) self.mylexer.setDefaultColor(colorDefault) self.mylexer.setColor(colorComment, 1) self.mylexer.setColor(colorNumber, 2) self.mylexer.setColor(colorString, 3) self.mylexer.setColor(colorString, 4) self.mylexer.setColor(colorKeyword, 5) self.mylexer.setColor(colorString, 6) self.mylexer.setColor(colorString, 7) self.mylexer.setColor(colorType, 8) self.mylexer.setColor(colorCommentBlock, 12) self.mylexer.setColor(colorString, 15) self.mylexer.setFont(self.italicFont, 1) self.mylexer.setFont(self.boldFont, 5) self.mylexer.setFont(self.boldFont, 8) self.mylexer.setFont(self.italicFont, 12) self.setLexer(self.mylexer) def lexer(self): return self.mylexer def setMarginVisible(self, visible): pass
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 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] = ''
class SqlEdit(QsciScintilla): LEXER_PYTHON = 0 LEXER_R = 1 def __init__(self, parent=None): QsciScintilla.__init__(self, parent) self.mylexer = None self.api = None self.setCommonOptions() self.initShortcuts() 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 initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def initLexer(self): self.mylexer = QsciLexerSQL() colorDefault = QColor('#2e3436') colorComment = QColor('#c00') colorCommentBlock = QColor('#3465a4') colorNumber = QColor('#4e9a06') colorType = QColor('#4e9a06') colorKeyword = QColor('#204a87') colorString = QColor('#ce5c00') self.mylexer.setDefaultFont(self.defaultFont) self.mylexer.setDefaultColor(colorDefault) self.mylexer.setColor(colorComment, 1) self.mylexer.setColor(colorNumber, 2) self.mylexer.setColor(colorString, 3) self.mylexer.setColor(colorString, 4) self.mylexer.setColor(colorKeyword, 5) self.mylexer.setColor(colorString, 6) self.mylexer.setColor(colorString, 7) self.mylexer.setColor(colorType, 8) self.mylexer.setColor(colorCommentBlock, 12) self.mylexer.setColor(colorString, 15) self.mylexer.setFont(self.italicFont, 1) self.mylexer.setFont(self.boldFont, 5) self.mylexer.setFont(self.boldFont, 8) self.mylexer.setFont(self.italicFont, 12) self.setLexer(self.mylexer) def lexer(self): return self.mylexer def setMarginVisible(self, visible): pass
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 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.setFont(font, 1) 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.api = QsciAPIs(self.lexer) chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True, type=bool) chekBoxPreparedAPI = self.settings.value("pythonConsole/usePreparedAPIFile", False, type=bool) if chekBoxAPI: pap = os.path.join(QgsApplication.pkgDataPath(), "python", "qsci_apis", "pyqgis.pap") self.api.loadPrepared(pap) elif chekBoxPreparedAPI: self.api.loadPrepared(self.settings.value("pythonConsole/preparedAPIFile")) else: apiPath = self.settings.value("pythonConsole/userAPI", []) for i in range(0, len(apiPath)): self.api.load(apiPath[i]) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer)
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)
class ScriptEdit(QsciScintilla): DEFAULT_COLOR = "#4d4d4c" KEYWORD_COLOR = "#8959a8" CLASS_COLOR = "#4271ae" METHOD_COLOR = "#4271ae" DECORATION_COLOR = "#3e999f" NUMBER_COLOR = "#c82829" COMMENT_COLOR = "#8e908c" COMMENT_BLOCK_COLOR = "#8e908c" BACKGROUND_COLOR = "#ffffff" CURSOR_COLOR = "#636363" CARET_LINE_COLOR = "#efefef" SINGLE_QUOTE_COLOR = "#718c00" DOUBLE_QUOTE_COLOR = "#718c00" TRIPLE_SINGLE_QUOTE_COLOR = "#eab700" TRIPLE_DOUBLE_QUOTE_COLOR = "#eab700" MARGIN_BACKGROUND_COLOR = "#efefef" MARGIN_FOREGROUND_COLOR = "#636363" SELECTION_BACKGROUND_COLOR = "#d7d7d7" SELECTION_FOREGROUND_COLOR = "#303030" MATCHED_BRACE_BACKGROUND_COLOR = "#b7f907" MATCHED_BRACE_FOREGROUND_COLOR = "#303030" EDGE_COLOR = "#efefef" FOLD_COLOR = "#efefef" def __init__(self, parent=None): super().__init__(parent) self.lexer = None self.api = None self.setCommonOptions() self.initShortcuts() def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) settings = QgsSettings() # Default font font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setMatchedBraceBackgroundColor(QColor(settings.value("pythonConsole/matchedBraceBackgroundColorEditor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR)))) self.setMatchedBraceForegroundColor(QColor(settings.value("pythonConsole/matchedBraceForegroundColorEditor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR)))) #self.setWrapMode(QsciScintilla.WrapWord) #self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, # QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor(QColor(settings.value("pythonConsole/selectionForegroundColorEditor", QColor(self.SELECTION_FOREGROUND_COLOR)))) self.setSelectionBackgroundColor(QColor(settings.value("pythonConsole/selectionBackgroundColorEditor", QColor(self.SELECTION_BACKGROUND_COLOR)))) # Show line numbers fontmetrics = QFontMetrics(font) self.setMarginWidth(1, fontmetrics.width("0000") + 5) self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor(settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setMarginsBackgroundColor(QColor(settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) self.setIndentationGuidesForegroundColor(QColor(settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setIndentationGuidesBackgroundColor(QColor(settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) # Highlight current line caretLineColorEditor = settings.value("pythonConsole/caretLineColorEditor", QColor(self.CARET_LINE_COLOR)) cursorColorEditor = settings.value("pythonConsole/cursorColorEditor", QColor(self.CURSOR_COLOR)) self.setCaretLineVisible(True) self.setCaretWidth(2) self.setCaretLineBackgroundColor(caretLineColorEditor) self.setCaretForegroundColor(cursorColorEditor) # Folding self.setFolding(QsciScintilla.PlainFoldStyle) foldColor = QColor(settings.value("pythonConsole/foldColorEditor", QColor(self.FOLD_COLOR))) self.setFoldMarginColors(foldColor, foldColor) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor(settings.value("pythonConsole/edgeColorEditor", QColor(self.EDGE_COLOR)))) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) self.setIndentationGuides(True) # Autocompletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setFonts(10) self.initLexer() def setFonts(self, size): # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', size)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) 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) def initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) # self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def initLexer(self): settings = QgsSettings() self.lexer = QsciLexerPython() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) loadFont = settings.value("pythonConsole/fontfamilytextEditor") if loadFont: font.setFamily(loadFont) fontSize = settings.value("pythonConsole/fontsizeEditor", type=int) if fontSize: font.setPointSize(fontSize) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor(QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR)))) self.lexer.setColor(QColor(settings.value("pythonConsole/commentFontColorEditor", QColor(self.COMMENT_COLOR))), 1) self.lexer.setColor(QColor(settings.value("pythonConsole/numberFontColorEditor", QColor(self.NUMBER_COLOR))), 2) self.lexer.setColor(QColor(settings.value("pythonConsole/keywordFontColorEditor", QColor(self.KEYWORD_COLOR))), 5) self.lexer.setColor(QColor(settings.value("pythonConsole/classFontColorEditor", QColor(self.CLASS_COLOR))), 8) self.lexer.setColor(QColor(settings.value("pythonConsole/methodFontColorEditor", QColor(self.METHOD_COLOR))), 9) self.lexer.setColor(QColor(settings.value("pythonConsole/decorFontColorEditor", QColor(self.DECORATION_COLOR))), 15) self.lexer.setColor(QColor(settings.value("pythonConsole/commentBlockFontColorEditor", QColor(self.COMMENT_BLOCK_COLOR))), 12) self.lexer.setColor(QColor(settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(self.SINGLE_QUOTE_COLOR))), 4) self.lexer.setColor(QColor(settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(self.DOUBLE_QUOTE_COLOR))), 3) self.lexer.setColor(QColor(settings.value("pythonConsole/tripleSingleQuoteFontColorEditor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6) self.lexer.setColor(QColor(settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7) self.lexer.setColor(QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))), 13) self.lexer.setFont(font, 1) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) self.lexer.setFont(font, QsciLexerPython.UnclosedString) for style in range(0, 33): paperColor = QColor(settings.value("pythonConsole/paperBackgroundColorEditor", QColor(self.BACKGROUND_COLOR))) self.lexer.setPaper(paperColor, style) self.api = QsciAPIs(self.lexer) useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) 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 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 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 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, QgsProcessingModelParameter): color = QColor(238, 242, 131) stroke = QColor(234, 226, 118) selected = QColor(116, 113, 68) elif isinstance(self.element, QgsProcessingModelChildAlgorithm): 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, QgsProcessingModelChildAlgorithm ) 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, QgsProcessingModelChildAlgorithm): 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 __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;}')
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; }')