def displayPlot(self): QGraphicsScene.clear(self) self.sceneRect() fm = QFontMetrics(QFont()) # display lines fitting in sceneRect last = None for z1, z2, text in self.data: brush = QBrush( QColor.fromHsl(z2 / (self.zMax - self.zMin) * 360.0, 128, 128) ) self.addRect( self.xOffset + self.legendWidth, z1 * self.zScale + self.yOffset, self.barWidth, (z2 - z1) * self.zScale, QPen(), brush, ) if last is None: legend_item = self.addSimpleText("{}".format(z1)) legend_item.setPos(self.xOffset, z1 * self.zScale + self.yOffset) legend_item = self.addSimpleText("{}".format(z2)) legend_item.setPos(self.xOffset, z2 * self.zScale + self.yOffset) last = z2 text_item = self.addSimpleText(text) text_item.setPos( self.xOffset * 2 + self.legendWidth + self.barWidth, (z1 + z2) / 2.0 * self.zScale - fm.height() / 2.0 + self.yOffset, )
def __init__(self, lexer=None): super(EditorWidget, self).__init__() font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) fontmetrics = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width("00000") + 6) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QColor("#cccccc")) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor("#ffe4e4")) if lexer is not None: lexer.setDefaultFont(font) self.setLexer(lexer) self.setReadOnly(True) self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier'.encode())
def __init__( self, iface, # pylint: disable=unused-argument service_type: str, parent=None): """Constructor.""" super().__init__(parent) self.setupUi(self) fm = QFontMetrics(self.url_edit.font()) self.url_edit.setMaximumHeight(fm.lineSpacing() * 6) self.output_table_options_button.clicked.connect( self._output_table_options) self.import_file_button.clicked.connect(self._import_from_file) if service_type == SERVICE_MANAGER.FDSNSTATION: self.label_import_file.setText( self.tr('Or import a local StationXML file')) self.service_type = None self.service_id = None self.set_service_type(service_type) self.output_fields = None self.service_config = {} self.url_edit.textChanged.connect(self.changed)
def __init__(self, iface, # pylint: disable=unused-argument service_type: str, parent=None): """Constructor.""" QWidget.__init__(self, parent) self.setupUi(self) self.scroll_area.setStyleSheet(""" QScrollArea { background: transparent; } QScrollArea > QWidget > QWidget { background: transparent; } QScrollArea > QWidget > QScrollBar { background: 1; } """) fm = QFontMetrics(self.url_edit.font()) self.url_edit.setMaximumHeight(fm.lineSpacing() * 6) self.import_file_button.clicked.connect(self._import_from_file) if service_type == SERVICE_MANAGER.FDSNSTATION: self.label_import_file.setText(self.tr('Or import a local StationXML file')) self.service_type = None self.service_id = None self.set_service_type(service_type) self.service_config = {} self.url_edit.textChanged.connect(self.changed) self.output_table_options_widget.enable_basic_option(False)
def eventFilter(self, obj, event): if (event.type() == QEvent.ToolTip): view = obj.parent() if not view: return False pos = event.pos() index = view.indexAt(pos) if not index.isValid(): return False itemText = view.model().data(index) itemTooltip = view.model().data(index, Qt.ToolTipRole) fm = QFontMetrics(view.font()) itemTextWidth = fm.width(itemText) rect = view.visualRect(index) rectWidth = rect.width() if (itemTextWidth > rectWidth) and itemTooltip: QtWidgets.QToolTip.showText(event.globalPos(), itemTooltip, view, rect) else: QtWidgets.QToolTip.hideText() return True return False
def scale_icon_size(standard_size: int) -> int: """ Scales an icon size accounting for device DPI """ fm = QFontMetrics((QFont())) scale = 1.1 * standard_size / 24.0 return int(math.floor(max(Qgis.UI_SCALE_FACTOR * fm.height() * scale, float(standard_size))))
def updateDisplayText(self, items): if len(items) == 0: text = self.defaultText else: text = self.separator.join(items) rect = self.lineEdit().rect() fontMetrics = QFontMetrics(self.font()) text = fontMetrics.elidedText(text, Qt.ElideRight, rect.width()) self.setEditText(text)
def displayPlot(self): QGraphicsScene.clear(self) self.marker.clear() self.sceneRect() # display lines fitting in sceneRect poly = QPolygonF() for x, y, _ in self.data: poly.append(QPointF(self.xToScene(x), self.yToScene(y))) # close the polygon x2 = self.xToScene(self.xMax) y2 = self.sceneRect().height() poly.append(QPointF(x2, y2)) x2 = self.barWidth poly.append(QPointF(x2, y2)) x2 = self.xToScene(self.xMin) y2 = self.yToScene(0) poly.append(QPointF(x2, y2)) brush = QBrush(QColor("#DCF1F7")) pen = QPen() pen.setWidth(0) self.addPolygon(poly, pen, brush) # horizontal line on ymin and ymax self.addLine( self.barWidth - 5, self.yToScene(self.yMin), self.barWidth + 5, self.yToScene(self.yMin), ) self.addLine( self.barWidth - 5, self.yToScene(self.yMax), self.barWidth + 5, self.yToScene(self.yMax), ) # display scale self.addLine(self.barWidth, 0, self.barWidth, self.sceneRect().height()) font = QFont() fm = QFontMetrics(font) t1 = self.addText("%.1f" % self.yMin) t1.setPos(0, self.yToScene(self.yMin) - fm.ascent()) t2 = self.addText("%.1f" % self.yMax) t2.setPos(0, self.yToScene(self.yMax) - fm.ascent()) # Z(m) t3 = self.addText(self.yTitle) t3.setPos(0, 0)
def init_gui(self): """ Initializes form widgets """ source_names = self.prefix_source_names() self.populate_source_cbo(source_names) self.populate_leading_zero() self.populate_separator(self.separator_cbo) self.populate_columns_list() column_header = QApplication.translate('CodeProperty', 'Columns') separator_header = QApplication.translate('CodeProperty', 'Separator') self.column_code_view.model().setHorizontalHeaderLabels( [column_header, separator_header]) header = self.column_code_view.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.Stretch) header.setSectionResizeMode(1, QHeaderView.ResizeToContents) if self._source: self.prefix_source_cbo.setCurrentIndex( self.prefix_source_cbo.findText(self._source)) if self._columns: self.set_columns() self.set_disable_auto_increment() self.set_enable_editing() self.set_hide_prefix() if self._leading_zero: self.leading_zero_cbo.setCurrentIndex( self.leading_zero_cbo.findData(self._leading_zero)) if self._separator: self.separator_cbo.setCurrentIndex( self.separator_cbo.findData(self._separator)) longest_item = max(source_names, key=len) font_meter = QFontMetrics(self.fontMetrics()) item_width = font_meter.width(longest_item) + 18 self.prefix_source_cbo.setStyleSheet('''* QComboBox QAbstractItemView{ min-width: 150px; width: %spx; } ''' % item_width) # Link checkbox and label self.disable_auto_increment_lbl.setBuddy( self.disable_auto_increment_chk) self.enable_editing_lbl.setBuddy(self.enable_editing_chk) self.hide_prefix_lbl.setBuddy(self.hide_prefix_chk)
def _adjust_layer_drop_down_width(self): """ Adjusts the layers combobox drop down to expand based on the layer name. """ if len(self._profile_spatial_layers) > 0: longest_item = max(self._profile_spatial_layers, key=len) font_meter = QFontMetrics(self.fontMetrics()) item_width = font_meter.width(longest_item) + 80 self.stdm_layers_combo.setStyleSheet('''* QComboBox QAbstractItemView{ min-width: 60px; width: %s px; } ''' % item_width)
def __init__(self, yTitle, parent): QGraphicsScene.__init__(self, parent) # width of the scale bar fm = QFontMetrics(QFont()) # width = size of "100.0" with the default font + 10% self.yTitle = yTitle self.barWidth = max(fm.width(yTitle), fm.width("000.00")) self.xOffset = self.barWidth self.yOffset = fm.height() * 2 # define the transformation between distance, altitude and scene coordinates self.xRatio = 1.0 self.yRatio = 1.0 self.marker = PointMarker(self) self.clear()
def setText(self, text): if not self.text: font = QFont() font.setPointSize(10) self.rect = self.scene.addRect(QRectF(0, 0, 0, 0), QPen(), QBrush(QColor("white"))) self.text = self.scene.addText("", font) self.text.setPlainText(text) self.textWidth = 0.0 self.textHeight = 0.0 for line in text.split("\n"): fm = QFontMetrics(self.text.font()) fw = fm.width(line) self.textHeight += fm.height() if fw > self.textWidth: self.textWidth = fw
def initGui(self): """Creates application GUI widgets""" self.initProcessing() self.dock = VertexDockWidget(self.iface.mapCanvas()) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock) self.dock.setUserVisible(False) self.toolbar = QToolBar(self.tr('Vertex Compare Toolbar')) self.toolbar.setObjectName('vertexCompareToolbar') self.iface.addToolBar(self.toolbar) self.layer_combo = QgsMapLayerComboBox() self.layer_combo.setAllowEmptyLayer(True, self.tr('Disabled')) self.layer_combo.setFilters(QgsMapLayerProxyModel.PolygonLayer | QgsMapLayerProxyModel.LineLayer) self.layer_combo.setMinimumWidth( QFontMetrics(self.layer_combo.font()).width('x') * 40) self.layer_combo.setCurrentIndex(0) self.layer_combo.layerChanged.connect(self._set_layer) self.toolbar.addWidget(self.layer_combo) self.show_vertices_action = QAction(self.tr("Show Vertex Numbers"), self) self.show_vertices_action.setIcon( GuiUtils.get_icon('show_vertex_numbers.svg')) self.show_vertices_action.setCheckable(True) self.show_vertices_action.setEnabled(False) self.actions.append(self.show_vertices_action) self.toolbar.addAction(self.show_vertices_action) self.show_vertices_action.toggled.connect( self.vertex_highlighter.set_visible) self.show_topology_action = QAction(self.tr("Compare Vertices"), self) self.show_topology_action.setIcon(GuiUtils.get_icon('topology.svg')) self.show_topology_action.setCheckable(True) self.actions.append(self.show_topology_action) self.toolbar.addAction(self.show_topology_action) self.show_topology_action.toggled.connect( self.vertex_highlighter.set_topological) self.show_dock_action = QAction(self.tr('Show Vertices'), parent=self.toolbar) self.show_dock_action.setIcon(GuiUtils.get_icon('vertex_table.svg')) self.toolbar.addAction(self.show_dock_action) self.actions.append(self.show_dock_action) self.dock.setToggleVisibilityAction(self.show_dock_action) self.selection_handler.selection_changed.connect( self._selection_changed) self.dock.label_filter_changed.connect(self.vertex_highlighter.redraw) self.dock.vertex_symbol_changed.connect(self.vertex_highlighter.redraw) self.dock.vertex_text_format_changed.connect( self.vertex_highlighter.redraw) self.dock.selected_vertex_changed.connect( self.vertex_highlighter.set_selected_vertex)
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 __init__(self, iface, service_type, parent=None): """Constructor.""" super().__init__(parent) self.setupUi(self) fm = QFontMetrics(self.url_edit.font()) self.url_edit.setMaximumHeight(fm.lineSpacing() * 6) self.output_table_options_button.clicked.connect( self._output_table_options) self.import_file_button.clicked.connect(self._import_from_file) self.service_type = None self.service_id = None self.set_service_type(service_type) self.output_fields = None self.service_config = {} self.url_edit.textChanged.connect(self.changed)
def setData(self, data): fm = QFontMetrics(QFont()) self.data = data self.zMin = None self.zMax = None self.width = None for z1, z2, text in self.data: if self.zMin is None or z1 < self.zMin: self.zMin = z1 if self.zMax is None or z2 > self.zMax: self.zMax = z2 tw = fm.width(text) if self.width is None or tw > self.width: self.width = tw tw1 = fm.width("{}".format(z1)) tw2 = fm.width("{}".format(z2)) tw = max(tw1, tw2) if tw > self.legendWidth: self.legendWidth = tw # update ratio and offset self.setSceneRect(self.sceneRect())
def __init__(self, width, title, min_value=None, max_value=None, unit_of_measure=None, is_vertical=False, parent=None): LogItem.__init__(self, parent) self.__width = width self.__title = title self.__min_value = min_value self.__max_value = max_value self.__uom = unit_of_measure self.__is_vertical = is_vertical self.__selected = False # title font self.__font1 = QFont() self.__font1.setBold(True) self.__font1.setPointSize(10) # value font self.__font2 = QFont() self.__font2.setPointSize(9) fm1 = QFontMetrics(self.__font1) fm2 = QFontMetrics(self.__font2) self.__height = self.LEGEND_LINE_MARGIN * 3 + fm1.height( ) + fm2.height() + 10 + self.LEGEND_ITEM_MARGIN
def __init__(self, show_marker_count=False, show_orientation=False, show_placement=False, parent=None): super(MarkerSettingsWidget, self).__init__(parent) self.setupUi(self) self.code_combo.setEditable(True) self.code_combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred) self.code_combo.setMinimumWidth(QFontMetrics(self.font()).width('X') * 40) self.field_code_combo.setAllowEmptyFieldName(True) self.field_rotation_combo.setFilters(QgsFieldProxyModel.Numeric) self.field_rotation_combo.setAllowEmptyFieldName(True) self.setFocusProxy(self.field_code_combo) self.field_code_combo.fieldChanged.connect(self.field_code_changed) self.field_rotation_combo.fieldChanged.connect(self.field_rotation_changed) self.code_combo.currentTextChanged.connect(self.on_code_changed) self.marker_count_spin.valueChanged.connect(self.marker_count_changed) self.marker_distance_spin.valueChanged.connect(self.marker_distance_changed) if not show_marker_count: self.marker_count_label.setVisible(False) self.marker_count_spin.setVisible(False) self.spacing_label.setVisible(False) self.spacing_combo.setVisible(False) self.spacing_stacked_widget.setVisible(False) if not show_orientation: self.orientation_label.setVisible(False) self.orientation_combo.setVisible(False) if not show_placement: self.placement_label.setVisible(False) self.placement_combo.setVisible(False) self.orientation_combo.addItem("0°", 0.0) self.orientation_combo.addItem("90°", 90.0) self.orientation_combo.addItem("180°", 180.0) self.orientation_combo.addItem("270°", 270.0) self.placement_combo.addItem(GuiUtils.get_icon('include_endpoints.svg'), self.tr('Include Endpoints'), True) self.placement_combo.addItem(GuiUtils.get_icon('exclude_endpoints.svg'), self.tr('Exclude Endpoints'), False) self.spacing_combo.addItem(self.tr('Via Count'), 0) self.spacing_combo.addItem(self.tr('Via Distance'), 1) self.orientation_combo.currentIndexChanged.connect(self.on_orientation_changed) self.placement_combo.currentIndexChanged.connect(self.on_placement_changed) self.spacing_combo.currentIndexChanged.connect(self.on_spacing_changed) self.marker_count_spin.setMinimum(2) self.layer = None
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 createWidgets(self): dist_type_sheet = PropertySheetWidget(self) dist_type_sheet.newSection("Distance modes and radii") radius_edit_max_width = QFontMetrics( QApplication.font()).width("8888888888") for dt in self.DIST_MODES: edit = QLineEdit() edit.setAlignment(Qt.AlignRight) edit.setFixedWidth(radius_edit_max_width) unit = QLabel(dt[2]) checkbox = WidgetEnableCheckBox(dt[0], [edit, unit]) self.regProp(dt[3] + "_enabled", WizProp(checkbox, False)) self.regProp(dt[3], WizPropFloat(edit, dt[1], 0)) dist_type_sheet.add(checkbox, edit, unit) func_sheet = PropertySheetWidget(self) func_sheet.newSection("Weight function") func_sheet.addComboProp("f(x)", [("1-x^C", "pow"), ("1-(4x^C)/2 <0.5< ((2-2x)^C)/2", "curve"), ("(x+1)^-C", "divide")], "pow", "weight_func") func_sheet.addNumberProp("C", 1, 2, None, "weight_func_constant") enable_checkbox = WidgetEnableCheckBox("Enable distance weight mode", [dist_type_sheet, func_sheet]) self.regProp("weight_enabled", WizProp(enable_checkbox, False)) #prop_sheet = PropertySheetWidget(self) #prop_sheet.newSection("Weight mode") #radio = QRadioButton("No weight") #radio.setChecked(True) #prop_sheet.add(radio) #weight_mode_radio = WidgetEnableRadioButton("Weigh by distance", [dist_type_sheet, func_sheet]) #self.regProp("weight_enabled", WizProp(weight_mode_radio, False)) #prop_sheet.add(weight_mode_radio) glayout = QGridLayout() #glayout.addWidget(prop_sheet, 0, 0) glayout.addWidget(enable_checkbox, 0, 0) glayout.setRowMinimumHeight(1, 10) glayout.addWidget(dist_type_sheet, 2, 0, 2, 1) glayout.addWidget(func_sheet, 2, 1) glayout.setRowStretch(4, 1) self.setLayout(glayout)
def paint_preview(self): rect = self.rect() painter = QPainter(self) painter.fillRect(rect, self.plugIn.canvas.canvasColor()) painter.setRenderHint(QPainter.Antialiasing) foregroundColor = QColor( QadVariables.get( QadMsg.translate("Environment variables", "DYNEDITFORECOLOR"))) backGroundColor = QColor( QadVariables.get( QadMsg.translate("Environment variables", "DYNEDITBACKCOLOR"))) borderColor = QColor( QadVariables.get( QadMsg.translate("Environment variables", "DYNEDITBORDERCOLOR"))) opacity = 100 - self.transparency font_size = 8 + self.size height = font_size + 15 selectionColor = QColor(Qt.white) selectionBackGroundColor = QColor(51, 153, 255) # azzurro (R=51 G=153 B=255) self.setEdit(self.edit1, foregroundColor, backGroundColor, borderColor, selectionColor, selectionBackGroundColor, opacity) fm = QFontMetrics(self.edit1.currentFont()) width1 = fm.width(self.edit1.toPlainText() + "__") + 2 self.edit1.resize(width1, height) self.edit1.selectAll() # seleziono tutto il testo self.setEdit(self.edit2, foregroundColor, backGroundColor, borderColor, backGroundColor, foregroundColor, opacity) fm = QFontMetrics(self.edit2.currentFont()) width2 = fm.width(self.edit2.toPlainText() + "__") + 2 self.edit2.resize(width2, height) offset = height / 3 x = (rect.width() - (width1 + offset + width2)) / 2 y = (rect.height() - height) / 2 self.edit1.move(x, y) self.edit2.move(x + width1 + offset, y)
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 _setMinimumHeight(self): font = self.lexer.defaultFont(0) fm = QFontMetrics(font) self.setMinimumHeight(fm.height() + 10)
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 _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)
def __init__(self, parent=None): super().__init__(parent=parent) scale_factor = QApplication.instance().primaryScreen() \ .logicalDotsPerInch() / 96 def create_editable_combobox(text): combo = QComboBox() combo.setEditable(True) combo.setEditText(text) return combo cols = lambda cx, lx: \ (QCheckBox(cx), create_editable_combobox(lx), FramedLabel(), PrecisionEdit()) self.rowXcoord = cols(self.tr('X Coordinate'), 'xcoord') self.rowYcoord = cols(self.tr('Y Coordinate'), 'ycoord') self.rowZcoord = cols(self.tr('Z Coordinate'), 'zcoord') self.rowMvalue = cols(self.tr('M Value'), 'mvalue') unit = QgsUnitTypes.DistanceDegrees self.rowXcoord[2].setText(QgsUnitTypes.toString(unit).title()) self.rowYcoord[2].setText(QgsUnitTypes.toString(unit).title()) unit = QgsUnitTypes.DistanceMeters self.rowZcoord[2].setText(QgsUnitTypes.toString(unit).title()) self.rowMvalue[2].setText(QgsUnitTypes.toString(unit).title()) cols = lambda cx, lx: \ (QCheckBox(cx), create_editable_combobox(lx), QComboBox(), PrecisionEdit()) self.rowLength = cols(self.tr('Length'), 'length') for unit in distance_units: self.rowLength[2].addItem(QgsUnitTypes.toString(unit).title(), unit) self.rowLength[2].setItemText(self.rowLength[2].count() - 1, self.tr('Map Units')) self.rowArea = cols(self.tr('Area'), 'area') for unit in area_units: self.rowArea[2].addItem(QgsUnitTypes.toString(unit).title(), unit) self.rowArea[2].setItemText(self.rowArea[2].count() - 1, self.tr('Map Units')) self.rowPerimeter = cols(self.tr('Perimeter'), 'perimeter') for i in range(self.rowLength[2].count()): self.rowPerimeter[2].addItem(self.rowLength[2].itemText(i), self.rowLength[2].itemData(i)) grid = QGridLayout() grid.addWidget(QLabel(self.tr('Field')), 0, 1) grid.addWidget(QLabel(self.tr('Units')), 0, 2) label_prec = QLabel(self.tr('Precision')) grid.addWidget(label_prec, 0, 3) grid.itemAtPosition(0, 3).widget().show() width = int(QFontMetrics(QFont()).height() * scale_factor * 3) self.rows = (self.rowXcoord, self.rowYcoord, self.rowZcoord, self.rowMvalue, self.rowLength, self.rowArea, self.rowPerimeter,) for row, w in enumerate(self.rows): w[0].setChecked(True) w[1].setMinimumWidth(width * 2) w[3].setMaximumWidth(max(width, label_prec.width())) for col in range(len(w)): grid.addWidget(w[col], row + 1, col) for col in (1, 2): grid.setColumnStretch(col, 1) groupProp = QGroupBox(self.tr('Properties')) groupProp.setLayout(grid) self.radio1 = QRadioButton( self.tr('Cartesian calculation with following CRS')) self.radio1.setChecked(True) self.radio2 = QRadioButton( self.tr('Ellipsoidal calculation with following ellipsoid')) self.radios = QButtonGroup() self.radios.addButton(self.radio1) self.radios.addButton(self.radio2) self.selectorCrs = QgsProjectionSelectionWidget() self.selectorCrs.setMinimumWidth(width * 8) self.selectorCrs.setOptionVisible( QgsProjectionSelectionWidget.CurrentCrs, False) self.selectorCrs.setLayerCrs(QgsCoordinateReferenceSystem('EPSG:4326')) self.comboCrs = self.selectorCrs.layout().itemAt(0).widget() self.comboCrs.setCurrentIndex( self.comboCrs.findData(QgsProjectionSelectionWidget.LayerCrs)) self.labelEllips = FramedLabel() grid = QGridLayout() grid.addWidget(self.radio1, 0, 0, 1, 0) grid.addWidget(self.selectorCrs, 1, 1) grid.addWidget(self.radio2, 2, 0, 1, 0) grid.addWidget(self.labelEllips, 3, 1) grid.setColumnMinimumWidth(0, QRadioButton().sizeHint().width()) grid.setRowMinimumHeight(3, QLineEdit().sizeHint().height()) groupSystem = QGroupBox(self.tr('Calculation System')) groupSystem.setLayout(grid) self.checkSelected = QCheckBox(self.tr('Selected features only')) self.checkDefault = QCheckBox(self.tr('Set expression to default value')) self.checkVirtual = QCheckBox(self.tr('Use virtual field for new field')) self.checks = QButtonGroup() self.checks.setExclusive(False) self.checks.addButton(self.checkSelected) self.checks.addButton(self.checkDefault) self.checks.addButton(self.checkVirtual) form = QFormLayout() form.addRow(groupProp) form.addRow(groupSystem) form.addRow(self.checkSelected) form.addRow(self.checkDefault) form.addRow(self.checkVirtual) self.buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, accepted=self.accept, rejected=self.reject) vbox = QVBoxLayout() vbox.addLayout(form) vbox.addWidget(self.buttonBox) self.setLayout(vbox) self.setMaximumSize(QWIDGETSIZE_MAX, 0)
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