def data(self, index, role=Qt.DisplayRole): column = index.column() if role == Qt.DisplayRole: field = self._mapping[index.row()] column_def = self.columns[column] value = field[column_def['name']] fieldType = column_def['type'] if fieldType == QVariant.Type: if value == QVariant.Invalid: return '' return self.fieldTypes[value] return value if role == Qt.EditRole: field = self._mapping[index.row()] column_def = self.columns[column] value = field[column_def['name']] return value if role == Qt.TextAlignmentRole: fieldType = self.columns[column]['type'] if fieldType in [QVariant.Int]: hAlign = Qt.AlignRight else: hAlign = Qt.AlignLeft return hAlign + Qt.AlignVCenter if role == Qt.ForegroundRole: column_def = self.columns[column] if column_def['name'] == 'expression': brush = QBrush() if self._errors[index.row()]: brush.setColor(Qt.red) else: brush.setColor(Qt.black) return brush if role == Qt.ToolTipRole: column_def = self.columns[column] if column_def['name'] == 'expression': return self._errors[index.row()]
def populate_function_table_1(self): """Populate the tblFunctions1 table with available functions.""" hazards = deepcopy(hazard_all) exposures = exposure_all self.lblAvailableFunctions1.clear() self.tblFunctions1.clear() self.tblFunctions1.setColumnCount(len(hazards)) self.tblFunctions1.setRowCount(len(exposures)) for i in range(len(hazards)): hazard = hazards[i] item = QTableWidgetItem() item.setIcon(QIcon(get_image_path(hazard))) item.setText(hazard['name'].capitalize()) item.setTextAlignment(Qt.AlignLeft) self.tblFunctions1.setHorizontalHeaderItem(i, item) for i in range(len(exposures)): exposure = exposures[i] item = QTableWidgetItem() item.setIcon(QIcon(get_image_path(exposure))) item.setText(exposure['name'].capitalize()) self.tblFunctions1.setVerticalHeaderItem(i, item) developer_mode = setting('developer_mode', False, bool) for hazard in hazards: for exposure in exposures: item = QTableWidgetItem() if (exposure in hazard['disabled_exposures'] and not developer_mode): background_colour = unavailable_option_color # Set it disable and un-selectable item.setFlags(item.flags() & ~Qt.ItemIsEnabled & ~Qt.ItemIsSelectable) else: background_colour = available_option_color item.setBackground(QBrush(background_colour)) item.setFont(big_font) item.setTextAlignment(Qt.AlignCenter | Qt.AlignHCenter) item.setData(RoleHazard, hazard) item.setData(RoleExposure, exposure) self.tblFunctions1.setItem(exposures.index(exposure), hazards.index(hazard), item) self.parent.pbnNext.setEnabled(False)
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 update_listitem(self): disp_id = str( getattr(self.obj, "obj_id", getattr(self.obj, "value_en", "?")) ) # some elements may not have obj_id, such as value_lists self.listitem.setText(0, getattr(self.obj, "identifier", disp_id)) self.listitem.setToolTip(0, disp_id) self.listitem.setText(1, self.status) self.listitem.setText(2, self.validity) if self.status == Editor.EXISTING: color = "lightgray" elif self.validity == Editor.INVALID: color = "red" elif self.validity == Editor.WARNING: color = "orange" elif self.validity == Editor.VALID: color = "lightgreen" else: color = "lightgray" self.listitem.setBackground(2, QBrush(QColor(color)))
def data(self, index, role=Qt.DisplayRole): field = self._mapping[index.row()] column_def = self.columns[index.column()] if role == Qt.DisplayRole: value = field[column_def['name']] if column_def[ 'name'] in field else QVariant() if column_def['type'] == QVariant.Type: if value == QVariant.Invalid: return '' return self.fieldTypes[value] elif column_def['name'] == 'constraints' and value: return self.tr("Constraints active") return value if role == Qt.EditRole: return field[column_def['name']] if role == Qt.TextAlignmentRole: if column_def['type'] in [QVariant.Int]: hAlign = Qt.AlignRight else: hAlign = Qt.AlignLeft return hAlign + Qt.AlignVCenter if role == Qt.BackgroundRole: return QBrush( QColor(255, 224, 178) ) if 'constraints' in field and field['constraints'] else QVariant( ) if role == Qt.ToolTipRole: if column_def['name'] == 'constraints' and 'constraints' in field: return "<br>".join([ self.constraints[constraint] for constraint in field['constraints'] ])
def data(self, index, role): """ Return the data of this node, used to style the items :param index: :param role: :return: """ if not index.isValid(): return item = index.internalPointer() if role == Qt.DisplayRole: return item.text(index.column()) elif role == Qt.ToolTipRole: return item.tooltip(index.column()) elif role == STATUS_ROLE: return item.status elif role == Qt.ForegroundRole: if isinstance(item, RequestParentItem) and item.ssl_errors \ or isinstance(item, SslErrorsItem) \ or isinstance(index.parent().internalPointer(), SslErrorsItem): color = QColor(180, 65, 210) elif item.status in (PENDING, CANCELED): color = QColor(0, 0, 0, 100) elif item.status == ERROR: color = QColor(235, 10, 10) elif item.status == TIMEOUT: color = QColor(235, 10, 10) else: color = QColor(0, 0, 0) return QBrush(color) elif role == Qt.FontRole: f = QFont() if item.status == CANCELED: f.setStrikeOut(True) return f
def paint(self, painter, option, widget): """ painter é un QPainter """ pen = QPen(QColor(self.borderColor)) pen.setWidth(1) painter.setPen(pen) painter.rotate(self.__rot) if self.__iconType == QadGripIconTypeEnum.NONE: pass elif self.__iconType == QadGripIconTypeEnum.BOX: # un quadrato painter.fillRect(-self.iconSize, -self.iconSize, self.iconSize * 2, self.iconSize * 2, QBrush(QColor(self.fillColor))); painter.drawRect(-self.iconSize, -self.iconSize, self.iconSize * 2, self.iconSize * 2) elif self.__iconType == QadGripIconTypeEnum.CIRCLE: # cerchio painter.setBrush(QBrush(QColor(self.fillColor))) painter.drawEllipse(QPointF(0, 0), self.iconSize, self.iconSize) elif self.__iconType == QadGripIconTypeEnum.RECTANGLE: # un rettangolo painter.fillRect(-self.iconSize, -self.iconSize / 2, self.iconSize * 2, self.iconSize, QBrush(QColor(self.fillColor))); painter.drawRect(-self.iconSize, -self.iconSize / 2, self.iconSize * 2, self.iconSize)
def __init__(self, commit,parent): QTreeWidgetItem.__init__(self,parent) self.commit = commit self.ref = commit.commitid self.setupToolTip() self.setText(1, commit.message.splitlines()[0]) self.setText(2, commit.author) timestamp = commit.timestamp / 1000 self.setText(3, datetime.fromtimestamp(timestamp).strftime(" %m/%d/%y %H:%M")) self.setText(4, commit.commitid) font = self.font(0) if self.commit.getImportance() == COMMIT_IMPORTANT: color = QColor("#000000") font.setBold(True) elif self.commit.getImportance() == COMMIT_UNIMPORTANT: color = QColor("#909090") font.setItalic(True) else: color = QColor("#000000") for i in range(5): self.setForeground(i, QBrush(color)) self.setFont(i, font)
def data(self, index, role=Qt.DisplayRole): if not index.isValid() or not (0 <= index.row() < self.rowCount() \ and 0 <= index.column() < self.columnCount()): return QVariant() row = self._dataframe.index[index.row()] col = self._dataframe.columns[index.column()] dt = self._dataframe[col].dtype val = self._dataframe.iloc[row][col] if role == Qt.DisplayRole: if index.column() == 0: return QVariant() else: return str(val) elif role == Qt.FontRole: font = QFont() font.setPointSize(11) return font elif role == Qt.ForegroundRole: if index.row() == self.tv.currentIndex().row(): return QColor(Qt.white) else: return QColor(Qt.black) elif role == Qt.BackgroundRole: if index.row() == self.tv.currentIndex().row(): gradient = QLinearGradient(0, 0, 66, 0) gradient.setColorAt(0, QColor(0, 0, 0, 128)) gradient.setColorAt(1, QColor(0, 0, 0, 0)) if index.column() == 0: return QColor(0, 0, 0, 128) else: return QBrush(gradient) if role == ValueRole: return val if role == DataFrameModel.DtypeRole: return dt return QVariant()
def draw(self, renderContext): self.renderContext = renderContext extent = renderContext.extent() if extent.isEmpty() or extent.width() == float("inf"): qDebug("Drawing is skipped because map extent is empty or inf.") return True mapSettings = self.iface.mapCanvas().mapSettings() painter = renderContext.painter() isDpiEqualToCanvas = painter.device().logicalDpiX( ) == mapSettings.outputDpi() if isDpiEqualToCanvas or not self.useLastZoomForPrint: # calculate zoom level tile_mpp1 = self.layerDef.tsize1 / self.layerDef.TILE_SIZE # should be attribute, not method call.. viewport_mpp = extent.width() / painter.viewport().width() lg = math.log(float(tile_mpp1) / float(viewport_mpp), 2) zoom = int(math.modf( lg)[1]) + 1 * (math.modf(lg)[0] > self.CHANGE_SCALE_VALUE) + 1 zoom = max(0, min(zoom, self.layerDef.zmax)) # zoom = max(self.layerDef.zmin, zoom) else: # for print composer output image, use last zoom level of map item on print composer (or map canvas) zoom = self.canvasLastZoom # zoom limit if zoom < self.layerDef.zmin: msg = self.tr( "Current zoom level ({0}) is smaller than zmin ({1}): {2}" ).format(zoom, self.layerDef.zmin, self.layerDef.title) self.emitShowBarMessage(msg, QGisMessageBarLevel.Info, 2) return True while True: # calculate tile range (yOrigin is top) size = self.layerDef.tsize1 / 2**(zoom - 1) if self.layerDef.tile_ranges is None: # should add xOffset & yOffset in first part of conditional matrixSize = 2**zoom ulx = max( 0, int((extent.xMinimum() + self.layerDef.tsize1) / size)) uly = max( 0, int((self.layerDef.tsize1 - extent.yMaximum()) / size)) lrx = min( int((extent.xMaximum() + self.layerDef.tsize1) / size), matrixSize - 1) lry = min( int((self.layerDef.tsize1 - extent.yMinimum()) / size), matrixSize - 1) else: # for tile_ranges xmin, xmax, ymin, ymax = self.layerDef.tile_ranges[zoom] ulx = max( int((extent.xMinimum() - self.layerDef.originX) / size), xmin) uly = max( int((self.layerDef.originY - extent.yMaximum()) / size), ymin) lrx = min( int((extent.xMaximum() - self.layerDef.originX) / size), xmax) lry = min( int((self.layerDef.originY - extent.yMinimum()) / size), ymax) # bounding box limit if self.layerDef.bbox: trange = self.layerDef.bboxDegreesToTileRange( zoom, self.layerDef.bbox) ulx = max(ulx, trange.xmin) uly = max(uly, trange.ymin) lrx = min(lrx, trange.xmax) lry = min(lry, trange.ymax) if lrx < ulx or lry < uly: # tile range is out of the bounding box return True # tile count limit tileCount = (lrx - ulx + 1) * (lry - uly + 1) if tileCount > self.MAX_TILE_COUNT: # as tile count is over the limit, decrease zoom level zoom -= 1 # if the zoom level is less than the minimum, do not draw if zoom < self.layerDef.zmin: msg = self.tr( "Tile count is over limit ({0}, max={1})").format( tileCount, self.MAX_TILE_COUNT) self.emitShowBarMessage(msg, QGisMessageBarLevel.Warning, 4) return True continue # zoom level has been determined break self.logT("TileLayer.draw: {0} {1} {2} {3} {4}".format( zoom, ulx, uly, lrx, lry)) # save painter state painter.save() # set pen and font painter.setPen(Qt.black) font = QFont(painter.font()) font.setPointSize(10) painter.setFont(font) if self.layerDef.serviceUrl[0] == ":": painter.setBrush(QBrush(Qt.NoBrush)) self.drawDebugInfo(renderContext, zoom, ulx, uly, lrx, lry) else: # create Tiles class object and throw url into it tiles = Tiles(zoom, ulx, uly, lrx, lry, self.layerDef) urls = [] cacheHits = 0 for ty in range(uly, lry + 1): for tx in range(ulx, lrx + 1): data = None url = self.layerDef.tileUrl(zoom, tx, ty) if self.tiles and zoom == self.tiles.zoom and url in self.tiles.tiles: data = self.tiles.tiles[url].data tiles.addTile(url, Tile(zoom, tx, ty, data)) if data is None: urls.append(url) elif data: # memory cache exists cacheHits += 1 # else: # tile was not found (Downloader.NOT_FOUND=0) self.tiles = tiles if len(urls) > 0: # fetch tile data files = self.fetchFiles(urls) for url in files.keys(): self.tiles.setImageData(url, files[url]) if self.iface: cacheHits += self.downloader.cacheHits downloadedCount = self.downloader.fetchSuccesses - self.downloader.cacheHits msg = self.tr( "{0} files downloaded. {1} cache hits.").format( downloadedCount, cacheHits) barmsg = None if self.downloader.errorStatus != Downloader.NO_ERROR: if self.downloader.errorStatus == Downloader.TIMEOUT_ERROR: barmsg = self.tr("Download Timeout - {}").format( self.name()) else: msg += self.tr(" {} files failed.").format( self.downloader.fetchErrors) if self.downloader.fetchSuccesses == 0: barmsg = self.tr( "Failed to download all {0} files. - {1}" ).format(self.downloader.fetchErrors, self.name()) self.showStatusMessage(msg, 5000) if barmsg: self.emitShowBarMessage(barmsg, QGisMessageBarLevel.Warning, 4) # apply layer style oldOpacity = painter.opacity() painter.setOpacity(0.01 * (100 - self.transparency)) oldSmoothRenderHint = painter.testRenderHint( QPainter.SmoothPixmapTransform) if self.smoothRender: painter.setRenderHint(QPainter.SmoothPixmapTransform) # draw tiles if not renderContext.coordinateTransform(): # no need to reproject tiles self.drawTiles(renderContext, self.tiles) # self.drawTilesDirectly(renderContext, self.tiles) else: # reproject tiles self.drawTilesOnTheFly(renderContext, self.tiles) # restore layer style painter.setOpacity(oldOpacity) if self.smoothRender: painter.setRenderHint(QPainter.SmoothPixmapTransform, oldSmoothRenderHint) # draw credit on the bottom right corner if self.creditVisibility and self.layerDef.credit: margin, paddingH, paddingV = (3, 4, 3) # scale scaleX, scaleY = self.getScaleToVisibleExtent(renderContext) scale = max(scaleX, scaleY) painter.scale(scale, scale) visibleSWidth = painter.viewport().width() * scaleX / scale visibleSHeight = painter.viewport().height() * scaleY / scale rect = QRect(0, 0, visibleSWidth - margin, visibleSHeight - margin) textRect = painter.boundingRect(rect, Qt.AlignBottom | Qt.AlignRight, self.layerDef.credit) bgRect = QRect(textRect.left() - paddingH, textRect.top() - paddingV, textRect.width() + 2 * paddingH, textRect.height() + 2 * paddingV) painter.fillRect(bgRect, QColor(240, 240, 240, 150)) # 197, 234, 243, 150)) painter.drawText(rect, Qt.AlignBottom | Qt.AlignRight, self.layerDef.credit) # restore painter state painter.restore() if isDpiEqualToCanvas: # save zoom level for printing (output with different dpi from map canvas) self.canvasLastZoom = zoom return True
from QGIS_FMV.video.QgsVideoUtils import VideoUtils as vut try: from pydevd import * except ImportError: None RulerTotalMeasure = 0.0 MAX_MAGNIFIER = 250 MAX_FACTOR = 2 TYPE_MAGNIFIER = 1 # Polygon Draw PolyWidth = 3 PolyPen = QPen(QColor(252, 215, 108), PolyWidth) PolyBrush = QBrush(QColor(252, 215, 108, 100)) # Point Draw PointWidth = 10 PointPen = QPen(QColor(220, 20, 60), PointWidth, cap=Qt.RoundCap) # Line Draw LineWidth = 3 LinePen = QPen(QColor(252, 215, 108), LineWidth) # Measure Draw MeasureWidth = 3 MeasurePen = QPen(QColor(185, 224, 175), MeasureWidth, cap=Qt.RoundCap, join=Qt.RoundJoin)
def paint(self, painter, option, index): if index.column() != 0: QStyledItemDelegate.paint(self, painter, option, index) return model: Any[PlanetSearchResultsModel | QAbstractItemModel] = \ index.model() node: PlanetNode = model.get_node(index) # TODO: Style these, too? # if node.node_type() in [NodeT.LOADING, NodeT.LOAD_MORE]: # QStyledItemDelegate.paint(self, painter, option, index) # return option_vi = QStyleOptionViewItem(option) self.initStyleOption(option_vi, index) # noinspection PyUnusedLocal style = QApplication.style() \ if option_vi.widget is None else option_vi.widget.style() # style = self.parent().style() opt_rect = option_vi.rect doc = QTextDocument() doc.setHtml(option_vi.text) #print(option_vi.text) option_vi.text = '' style.drawControl(QStyle.CE_ItemViewItem, option_vi, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected # if option_vi.state & QStyle.State_Selected: # ctx.palette.setColor( # QPalette.Text, # option_vi.palette.color( # QPalette.Active, QPalette.HighlightedText)) text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option_vi) painter.save() painter.translate(text_rect.topLeft()) painter.setClipRect(text_rect.translated(-text_rect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore() if option.state & QStyle.State_MouseOver: if node.has_footprint() or node.has_group_footprint(): painter.save() painter.setPen( QPen(QBrush(QColor.fromRgb(0, 157, 165, 245)), 1.5)) painter.setBrush(Qt.NoBrush) painter.drawRect(opt_rect.marginsRemoved(QMargins(1, 1, 1, 1))) painter.restore() if node.has_footprint() or node.has_group_footprint(): # noinspection PyUnresolvedReferences self.previewFootprint.emit(node) else: # noinspection PyUnresolvedReferences self.clearFootprint.emit() if not node.can_be_downloaded(): # Note: Needs to come last, so it covers checkbox control # TODO: Figure out way of having checkbox not drawn, but still # set Node's unchecked state # opt_btn = QStyleOptionButton() # opt_btn.operator = option ci_rect: QRect = style.subElementRect( QStyle.SE_ViewItemCheckIndicator, option_vi) # opt_btn.rect = ci_rect # but_opt = QStyleOptionButton(option) # opt_btn.state = QStyle.State_Off # style.drawControl(QStyle.CE_CheckBox, opt_btn, painter) painter.save() painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor.fromRgb(250, 250, 250, 255))) painter.drawRoundedRect(ci_rect, ci_rect.height() / 6, ci_rect.height() / 6) LOCK_ICON.paint(painter, ci_rect, Qt.AlignCenter, QIcon.Normal) painter.restore()
def setSkipped(self, layer_id, category): item, subitem = self.getItem(layer_id, category, True) subitem.setForeground(1, QBrush(Qt.gray)) subitem.setText(1, "Skipped") self.setMetadata(item, category) QCoreApplication.processEvents()
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 paintEvent(self, event): # based on # http://qt.gitorious.org/qt/qt/blobs/master/src/gui/widgets/qslider.cpp painter = QPainter(self) style = self.style() opt = QStyleOptionSlider() self.initStyleOption(opt) groove_rect = style.subControlRect(style.CC_Slider, opt, QStyle.SC_SliderGroove, self) handle_rect = style.subControlRect(style.CC_Slider, opt, QStyle.SC_SliderHandle, self) slider_space = style.pixelMetric(style.PM_SliderSpaceAvailable, opt) range_x1 = style.sliderPositionFromValue(self.minimum(), self.maximum(), self._low, slider_space) range_x2 = style.sliderPositionFromValue(self.minimum(), self.maximum(), self._high, slider_space) range_height = 4 groove_rect = QRectF( groove_rect.x(), handle_rect.center().y() - (range_height / 2), groove_rect.width(), range_height, ) range_rect = QRectF( groove_rect.x() + (handle_rect.width() / 2) + range_x1, handle_rect.center().y() - (range_height / 2), range_x2 - range_x1, range_height, ) if style.metaObject().className() != "QMacStyle": # Paint groove for Fusion and Windows styles cur_brush = painter.brush() cur_pen = painter.pen() painter.setBrush(QBrush(QColor(169, 169, 169))) painter.setPen(Qt.NoPen) # painter.drawRect(groove_rect) painter.drawRoundedRect(groove_rect, groove_rect.height() / 2, groove_rect.height() / 2) painter.setBrush(cur_brush) painter.setPen(cur_pen) cur_brush = painter.brush() cur_pen = painter.pen() # painter.setBrush(QBrush(QColor(18, 141, 148))) # painter.setPen(Qt.NoPen) painter.drawRect(range_rect) painter.setBrush(cur_brush) painter.setPen(cur_pen) for i, value in enumerate([self._low, self._high]): opt = QStyleOptionSlider() self.initStyleOption(opt) # Only draw the groove for the first slider so it doesn't get drawn # on top of the existing ones every time # if i == 0: # opt.subControls = QStyle.SC_SliderGroove | \ # QStyle.SC_SliderHandle # else: opt.subControls = QStyle.SC_SliderHandle if self.tickPosition() != self.NoTicks: opt.subControls |= QStyle.SC_SliderTickmarks if self.isSliderDown(): opt.state |= QStyle.State_Sunken else: opt.state |= QStyle.State_Active if self.pressed_control: opt.activeSubControls = self.pressed_control else: opt.activeSubControls = self.hover_control opt.sliderPosition = value opt.sliderValue = value style.drawComplexControl(QStyle.CC_Slider, opt, painter, self)
def update_available_layers(self): self.trw_layers.setUpdatesEnabled( False) # Don't render until we're ready # Grab some context data show_domains = self.chk_show_domains.isChecked() show_structures = self.chk_show_structures.isChecked() show_associations = self.chk_show_associations.isChecked() top_level_items_expanded_info = [] for i in range(self.trw_layers.topLevelItemCount()): top_level_items_expanded_info.append( self.trw_layers.topLevelItem(i).isExpanded()) # Save selection self.update_selected_items() # Iterate models adding children self.trw_layers.blockSignals( True) # We don't want to get itemSelectionChanged here self.trw_layers.clear() self.trw_layers.blockSignals(False) sorted_models = sorted(self.models_tree.keys()) for model in sorted_models: children = [] model_item = QTreeWidgetItem([model]) # Filter by search text list_tables = self.filter_tables_by_search_text( self.models_tree[model].keys(), self.txt_search_text.text()) sorted_tables = sorted(list_tables) for table in sorted_tables: current_table_info = self.models_tree[model][table] if current_table_info[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) model_item.addChildren(children) self.trw_layers.addTopLevelItem(model_item) # Set selection iterator = QTreeWidgetItemIterator(self.trw_layers, QTreeWidgetItemIterator.Selectable) self.trw_layers.blockSignals( True) # We don't want to get itemSelectionChanged here while iterator.value(): item = iterator.value() if item.text(0) in self.selected_items_dict: item.setSelected(True) iterator += 1 self.trw_layers.blockSignals(False) # Make model items non selectable # Set expand taking previous states into account for i in range(self.trw_layers.topLevelItemCount()): self.trw_layers.topLevelItem(i).setFlags( Qt.ItemIsEnabled) # Not selectable self.trw_layers.topLevelItem(i).setExpanded( top_level_items_expanded_info[i] if top_level_items_expanded_info else True) self.trw_layers.setUpdatesEnabled(True) # Now render!
def 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 _recurse_tree(self, bl_el=None, proj_el=None, parent: QStandardItem = None): if self.business_logic is None: return if bl_el is None: bl_el = self.business_logic.find('Node') is_root = proj_el is None bl_attr = bl_el.attrib if proj_el is None: proj_el = self.project new_proj_el = proj_el if 'xpath' in bl_el.attrib: new_proj_el = xpathone_withref(self.project, proj_el, bl_el.attrib['xpath']) if new_proj_el is None: # We just ignore layers we can't find. Log them though return # The label is either explicit or it's an xpath lookup curr_label = '<unknown>' if 'label' in bl_el.attrib: curr_label = bl_el.attrib['label'] elif 'xpathlabel' in bl_el.attrib: found = new_proj_el.xpath(bl_el.attrib['xpathlabel']) curr_label = found[0].text if found is not None and len( found) > 0 else '<unknown>' curr_item = QStandardItem() curr_item.setText(curr_label) children_container = bl_el.find('Children') # If there are children then this is a branch if children_container: curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/BrowseFolder.png')) if is_root is True: curr_item.setData( ProjectTreeData(QRaveTreeTypes.PROJECT_ROOT, project=self, data=dict(children_container.attrib)), Qt.UserRole), else: curr_item.setData( ProjectTreeData(QRaveTreeTypes.PROJECT_FOLDER, project=self, data=dict(children_container.attrib)), Qt.UserRole), for child_node in children_container.xpath('*'): # Handle any explicit <Node> children if child_node.tag == 'Node': self._recurse_tree(child_node, new_proj_el, curr_item) # Repeaters are a separate case elif child_node.tag == 'Repeater': qrepeater = QStandardItem( QIcon(':/plugins/qrave_toolbar/BrowseFolder.png'), child_node.attrib['label']) qrepeater.setData( ProjectTreeData(QRaveTreeTypes.PROJECT_REPEATER_FOLDER, project=self, data=dict(children_container.attrib)), Qt.UserRole), curr_item.appendRow(qrepeater) repeat_xpath = child_node.attrib['xpath'] repeat_node = child_node.find('Node') if repeat_node is not None: for repeater_el in new_proj_el.xpath(repeat_xpath): self._recurse_tree(repeat_node, repeater_el, qrepeater) # Otherwise this is a leaf else: bl_type = bl_el.attrib['type'] if bl_type == 'polygon': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/Polygon.png')) elif bl_type == 'line': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/Polyline.png')) elif bl_type == 'point': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/MultiDot.png')) elif bl_type == 'raster': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/Raster.png')) else: curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/RaveAddIn_16px.png')) # Couldn't find this node. Ignore it. meta = { meta.attrib['name']: meta.text for meta in new_proj_el.findall('MetaData/Meta') } new_proj_el.find('Path') layer_name = None layer_uri = os.path.join(self.project_dir, new_proj_el.find('Path').text) # If this is a geopackage it's special if new_proj_el.getparent().tag == 'Layers': layer_name = new_proj_el.find('Path').text layer_uri = os.path.join( self.project_dir, new_proj_el.getparent().getparent().find('Path').text) layer_type = bl_attr['type'] if 'type' in bl_attr else 'unknown' map_layer = QRaveMapLayer(curr_label, layer_type, layer_uri, bl_attr, meta, layer_name) curr_item.setData( ProjectTreeData(QRaveTreeTypes.LEAF, project=self, data=map_layer), Qt.UserRole) if not map_layer.exists: curr_item.setData(QBrush(Qt.red), Qt.ForegroundRole) curr_item_font = curr_item.font() curr_item_font.setItalic(True) curr_item.setFont(curr_item_font) curr_item.setToolTip('File not found: {}'.format( map_layer.layer_uri)) elif map_layer.layer_uri: curr_item.setToolTip(map_layer.layer_uri) if parent: parent.appendRow(curr_item) return curr_item
def setStyle(self): self.Style = QPen(QBrush(self.color), self.width, style=self.lineStyle) self.profile.update({'style': self.Style})
def fill_model(self, record, parent): """ Fill data in the treeview depending on the structure. It expects JSON data. The JSON data may contain LADM-COL object collections in the form: "ladm_col_table_name" : [{"id": 5, "attributes":{k,v pairs}}, {"id": 8, "attributes":{k,v pairs}}, ...] """ plural = LayerConfig.get_dict_plural(self.names) icons = LayerConfig.get_dict_package_icon() dict_table_package = LayerConfig.get_dict_table_package(self.names) for key, values in record.items(): # either tuple or dict if type(values) is list: if not len(values): # Empty object kv_item = self._create_new_item(parent) kv_item.setData( 0, "{} (0)".format(plural[key] if key in plural else key)) kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) kv_item.setData(0, {"type": key}, Qt.UserRole) kv_item.setData( 0, QIcon(icons[dict_table_package[key]]) if key in dict_table_package else None, Qt.DecorationRole) continue for value in values: if type(value) is dict: if len( value ) == 2 and 'id' in value and 'attributes' in value: # We have a list of LADM-COL model objects, we deal differently with them... self.fill_collection(key, values, parent, plural, icons) break elif type(values) is dict: if key == 'attributes': # Dict of key-value pairs, reuse the function self.fill_model(values, parent) else: # Non-LADM object (e.g., external boundaries) kv_item = self._create_new_item(parent) kv_item.setData(0, "{}:".format(key)) self.fill_model(values, kv_item) else: # Simple key-value pair kv_item = self._create_new_item(parent) kv_text = "{}: {}".format(key, values) kv_item.setData(0, kv_text) value_user_role = {"value": values} if key.startswith("Archivo fuente"): value_user_role.update({'url': values}) kv_item.setData(0, value_user_role, Qt.UserRole) if values is None: kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) else: kv_item.setData(0, kv_text, Qt.ToolTipRole) # Additional item for a file preview if key.startswith("Archivo fuente"): if values: if values.startswith(DEFAULT_ENDPOINT_SOURCE_SERVICE ): # We want the thumbnail kv_subitem = self._create_new_item(kv_item) kv_subitem.setData(0, { 'type': 'img', 'url': values }, Qt.UserRole)
def fill_model(self, record, parent): """ Fill data in the treeview depending on the structure. It expects JSON data. The JSON data may contain LADM_COL object collections in the form: "ladm_col_table_name" : [{"id": 5, "records":{k,v pairs}}, {"id": 8, "records":{k,v pairs}}, ...] """ for key, values in record.items(): # either tuple or dict if type(values) is list: if not len(values): # Empty object parent.insertChildren(parent.childCount(), 1, self.rootItem.columnCount()) kv_item = parent.child(parent.childCount() - 1) kv_item.setData( 0, "{} (0)".format(DICT_PLURAL[key] if key in DICT_PLURAL else key)) kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) kv_item.setData(0, {"type": key}, Qt.UserRole) kv_item.setData( 0, QIcon(DICT_PACKAGE_ICON[DICT_TABLE_PACKAGE[key]]) if key in DICT_TABLE_PACKAGE else None, Qt.DecorationRole) continue for value in values: if type(value) is dict: if len( value ) == 2 and 'id' in value and 'attributes' in value: # We have a list of LADM_COL model objects, we deal differently with them... self.fill_collection(key, values, parent) break elif type(values) is dict: if key == 'attributes': # Dict of key-value pairs, reuse the function self.fill_model(values, parent) else: # Non-LADM object (e.g., external boundaries) parent.insertChildren(parent.childCount(), 1, self.rootItem.columnCount()) kv_item = parent.child(parent.childCount() - 1) kv_item.setData(0, "{}:".format(key)) self.fill_model(values, kv_item) else: # Simple key-value pair parent.insertChildren(parent.childCount(), 1, self.rootItem.columnCount()) kv_item = parent.child(parent.childCount() - 1) kv_item.setData(0, "{}: {}".format(key, values)) value_user_role = {"value": values} if key.startswith("Archivo fuente"): value_user_role.update({'url': values}) kv_item.setData(0, value_user_role, Qt.UserRole) if values is None: kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) # Additional item for a file preview if key.startswith("Archivo fuente"): if values: if values.startswith(DEFAULT_ENDPOINT_SOURCE_SERVICE ): # We want the thumbnail kv_item.insertChildren(kv_item.childCount(), 1, self.rootItem.columnCount()) kv_subitem = kv_item.child(kv_item.childCount() - 1) kv_subitem.setData(0, { 'type': 'img', 'url': values }, Qt.UserRole)
def setupUi_plot(self): # plot self.plotLibSelector.setVisible(False) self.enableStatistics.setVisible(False) # stats by default because estimated are fast self.enableStatistics.setChecked(True) plot_count = 0 self.mplLine = None # make sure to invalidate when layers change if self.hasqwt: # Page 2 - qwt self.plotLibSelector.addItem('Qwt') plot_count += 1 # Setup Qwt Plot Area in Widget self.qwtPlot = QwtPlot(self.stackedWidget) self.qwtPlot.setAutoFillBackground(False) self.qwtPlot.setObjectName("qwtPlot") self.curve = QwtPlotCurve() self.curve.setSymbol( QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.white), QPen(Qt.red, 2), QSize(9, 9))) self.curve.attach(self.qwtPlot) # Size Policy ??? sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.qwtPlot.sizePolicy().hasHeightForWidth()) self.qwtPlot.setSizePolicy(sizePolicy) # Size Policy ??? self.qwtPlot.updateGeometry() self.stackedWidget.addWidget(self.qwtPlot) self.qwt_widgetnumber = self.stackedWidget.indexOf(self.qwtPlot) if self.hasmpl: # Page 3 - setup matplotlib self.plotLibSelector.addItem('matplotlib') # If matplotlib is the only one self.toggleInterpolation.setEnabled(True) self.toggleInterpolation.setVisible(True) plot_count += 1 self.mplBackground = None # http://www.scipy.org/Cookbook/Matplotlib/Animations self.mplFig = plt.Figure(facecolor='w', edgecolor='g', linewidth=0.0) self.mpl_subplot = self.mplFig.add_subplot(111) self.pltCanvas = FigureCanvasQTAgg(self.mplFig) self.pltCanvas.setParent(self.stackedWidget) self.pltCanvas.setAutoFillBackground(False) self.pltCanvas.setObjectName("mplPlot") self.mplPlot = self.pltCanvas self.mplPlot.updateGeometry() self.stackedWidget.addWidget(self.mplPlot) self.mpl_widgetnumber = self.stackedWidget.indexOf(self.mplPlot) if self.haspqg: # Page 3 - setup PyQtGraph self.plotLibSelector.addItem('PyQtGraph') plot_count += 1 # Setup PyQtGraph stuff pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') self.pqg_axis = DateTimeAxis(orientation='bottom') self.pqg_plot_widget = pg.PlotWidget( parent=self.stackedWidget, axisItems={'bottom': self.pqg_axis}) self.pqg_plot_item = self.pqg_plot_widget.getPlotItem() self.pqg_plot_widget.updateGeometry() self.stackedWidget.addWidget(self.pqg_plot_widget) self.pqg_widgetnumber = self.stackedWidget.indexOf( self.pqg_plot_widget) # on zoom change do: self.pqg_plot_item.sigXRangeChanged.connect(self.refresh_ticks) if plot_count > 1: self.plotLibSelector.setEnabled(True) self.plotLibSelector.setVisible(True) self.plotLibSelector.setCurrentIndex(0) if self.hasqwt: self.plotLibSelector.setCurrentIndex(self.qwt_widgetnumber) elif self.hasmpl: self.plotLibSelector.setCurrentIndex(self.mpl_widgetnumber) else: self.plotLibSelector.setCurrentIndex(self.pqg_widgetnumber) self.change_plot() elif plot_count == 1: self.plotLibSelector.setCurrentIndex(0) self.change_plot() else: # can only be 0 if nothing else matched message_text = "Mutant cannot find any graphiclibrary for " \ "creating plots. Please install either Qwt >= 5.0 " \ ",matplotlib >= 1.0 or PyQtGraph >= 0.9.8!" self.plot_message = QLabel(message_text) self.plot_message.setWordWrap(True) self.stackedWidget.addWidget(self.plot_message) self.pop_messagebar(message_text)
class DrawToolBar(object): NameSpace = getNameSpace() small_pt = 5 white_pen = QPen(Qt.white, small_pt) white_pen.setCapStyle(Qt.RoundCap) black_pen = QPen(Qt.black, small_pt) black_pen.setCapStyle(Qt.RoundCap) glass_pen = QPen(QColor(192, 192, 192, 128), 3) transparent_brush = QBrush(Qt.transparent) black_brush = QBrush(Qt.black) bold_12 = QFont("Arial", 12, QFont.Bold) # Stamp Image confidential = QPixmap.fromImage( QImage(":/imgFMV/images/stamp/confidential.png")) @staticmethod def setValues(options=None): ''' Function to set Drawing Values ''' s = QSettings() ####### Magnifier Glass ####### shape_type = s.value(DrawToolBar.NameSpace + "/Options/magnifier/shape") if shape_type is not None: global TYPE_MAGNIFIER TYPE_MAGNIFIER = shape_type if options is not None: if TYPE_MAGNIFIER == 0: # Square options.rB_Square_m.setChecked(True) else: # Circle options.rB_Circle_m.setChecked(True) mFactor = s.value(DrawToolBar.NameSpace + "/Options/magnifier/factor") if mFactor is not None: global MAX_FACTOR MAX_FACTOR = int(mFactor) if options is not None: options.sb_factor.setValue(MAX_FACTOR) mSize = s.value(DrawToolBar.NameSpace + "/Options/magnifier/size") if mSize is not None: global MAX_MAGNIFIER MAX_MAGNIFIER = int(mSize) if options is not None: options.sl_Size.setValue(MAX_MAGNIFIER) ####### Drawings ####### poly_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/width") if poly_w is not None: global PolyWidth PolyWidth = int(poly_w) if options is not None: options.poly_width.setValue(PolyWidth) poly_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/pen") if poly_p is not None: global PolyPen PolyPen = QPen(QColor(poly_p)) PolyPen.setCapStyle(Qt.RoundCap) PolyPen.setWidth(PolyWidth) if options is not None: options.poly_pen.setColor(QColor(poly_p)) poly_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/brush") if poly_b is not None: global PolyBrush PolyBrush = QBrush(QColor(poly_b)) if options is not None: options.poly_brush.setColor(QColor(poly_b)) point_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/width") if point_w is not None: global PointWidth PointWidth = int(point_w) if options is not None: options.point_width.setValue(PointWidth) point_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/pen") if point_p is not None: global PointPen PointPen = QPen(QColor(point_p)) PointPen.setCapStyle(Qt.RoundCap) PointPen.setWidth(PointWidth) if options is not None: options.point_pen.setColor(QColor(point_p)) line_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/width") if line_w is not None: global LineWidth LineWidth = int(line_w) if options is not None: options.lines_width.setValue(LineWidth) line_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/pen") if line_p is not None: global LinePen LinePen = QPen(QColor(line_p)) LinePen.setCapStyle(Qt.RoundCap) LinePen.setWidth(LineWidth) if options is not None: options.lines_pen.setColor(QColor(line_p)) measure_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/width") if measure_w is not None: global MeasureWidth MeasureWidth = int(measure_w) if options is not None: options.measures_width.setValue(MeasureWidth) measure_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/pen") if measure_p is not None: global MeasurePen MeasurePen = QPen(QColor(measure_p)) MeasurePen.setCapStyle(Qt.RoundCap) MeasurePen.setWidth(MeasureWidth) if options is not None: options.measures_pen.setColor(QColor(measure_p)) measure_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/brush") if measure_b is not None: global MeasureBrush MeasureBrush = QBrush(QColor(measure_b)) if options is not None: options.measures_brush.setColor(QColor(measure_b)) return @staticmethod def drawOnVideo(drawPtPos, drawLines, drawPolygon, drawMDistance, drawMArea, drawCesure, painter, surface, gt): ''' Function to paint over the video ''' # Draw clicked points on video for position, pt in enumerate(drawPtPos): DrawToolBar.drawPointOnVideo(position + 1, pt, painter, surface, gt) # Draw clicked lines on video if len(drawLines) > 1: for idx, pt in enumerate(drawLines): if pt[0] is None: continue else: DrawToolBar.drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines) # Draw clicked Polygons on video if len(drawPolygon) > 1: poly = [] if any(None == x[1] for x in drawPolygon): for pt in drawPolygon: if pt[0] is None: DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len(drawPolygon) - drawPolygon[::-1].index( [None, None, None]) poly = [] for pt in range(last_occurence, len(drawPolygon)): poly.append(drawPolygon[pt]) if len(poly) > 1: DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt) else: DrawToolBar.drawPolygonOnVideo(drawPolygon, painter, surface, gt) # Draw Measure Distance on video # the measures don't persist in the video if len(drawMDistance) > 1: DrawToolBar.resetMeasureDistance() for idx, pt in enumerate(drawMDistance): if pt[0] is None: DrawToolBar.resetMeasureDistance() continue else: DrawToolBar.drawMeasureDistanceOnVideo( pt, idx, painter, surface, gt, drawMDistance) # Draw Measure Area on video # the measures don't persist in the video if len(drawMArea) > 1: poly = [] if any(None == x[1] for x in drawMArea): for pt in drawMArea: if pt[0] is None: DrawToolBar.drawMeasureAreaOnVideo( poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len(drawMArea) - drawMArea[::-1].index( [None, None, None]) poly = [] for pt in range(last_occurence, len(drawMArea)): poly.append(drawMArea[pt]) if len(poly) > 1: DrawToolBar.drawMeasureAreaOnVideo(poly, painter, surface, gt) else: DrawToolBar.drawMeasureAreaOnVideo(drawMArea, painter, surface, gt) # Draw Censure if drawCesure: DrawToolBar.drawCensuredOnVideo(painter, drawCesure) return return @staticmethod def drawPointOnVideo(number, pt, painter, surface, gt): ''' Draw Points on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) # don't draw something outside the screen. if scr_x < vut.GetXBlackZone(surface) or scr_y < vut.GetYBlackZone( surface): return if scr_x > vut.GetXBlackZone(surface) + vut.GetNormalizedWidth( surface) or scr_y > vut.GetYBlackZone( surface) + vut.GetNormalizedHeight(surface): return center = QPoint(scr_x, scr_y) painter.setPen(PointPen) painter.drawPoint(center) painter.setFont(DrawToolBar.bold_12) painter.drawText(center + QPoint(5, -5), str(number)) return @staticmethod def drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines): ''' Draw Lines on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) painter.setPen(LinePen) if len(drawLines) > 1: try: pt = drawLines[idx + 1] if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) # Draw Start/End Points painter.setPen(DrawToolBar.white_pen) painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawPolygonOnVideo(values, painter, surface, gt): ''' Draw Polygons on Video ''' poly = [] for pt in values: if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setPen(PolyPen) painter.drawPolygon(polygon) painter.fillPath(path, PolyBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) return @staticmethod def resetMeasureDistance(): global RulerTotalMeasure RulerTotalMeasure = 0.0 @staticmethod def drawMeasureDistanceOnVideo(pt, idx, painter, surface, gt, drawMDistance): ''' Draw Measure Distance on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) if len(drawMDistance) > 1: try: painter.setPen(MeasurePen) end_pt = drawMDistance[idx + 1] if hasElevationModel(): end_pt = GetLine3DIntersectionWithPlane( GetSensor(), end_pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(end_pt[1], end_pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) painter.setFont(DrawToolBar.bold_12) distance = round( sphere.distance((pt[0], pt[1]), (end_pt[0], end_pt[1])), 2) text = str(distance) + " m" global RulerTotalMeasure RulerTotalMeasure += distance # Line lenght painter.setPen(MeasurePen) painter.drawText(end + QPoint(5, -10), text) painter.setPen(DrawToolBar.white_pen) # Total lenght painter.drawText(end + QPoint(5, 10), str(round(RulerTotalMeasure, 2)) + " m") # Draw Start/End Points painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawMeasureAreaOnVideo(values, painter, surface, gt): ''' Draw Measure Area on Video ''' a_value = sphere.polygon_area([values]) poly = [] lat = [] long = [] for pt in values: if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) lat.append(pt[0]) long.append(pt[1]) lat = list(dict.fromkeys(lat)) long = list(dict.fromkeys(long)) # Calculate Centroid Position scr_x, scr_y = vut.GetInverseMatrix( sum(long) / len(long), sum(lat) / len(lat), gt, surface) centroid = QPoint(scr_x, scr_y) # Create Poligon polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setFont(DrawToolBar.bold_12) painter.setPen(MeasurePen) painter.drawPolygon(polygon) painter.fillPath(path, MeasureBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) # Area if a_value >= 10000: painter.drawText(centroid, str(round(a_value / 1000000, 2)) + " km²") else: painter.drawText(centroid, str(round(a_value, 2)) + " m²") return @staticmethod def drawCensuredOnVideo(painter, drawCesure): ''' Draw Censure on Video ''' try: for geom in drawCesure: painter.setPen(DrawToolBar.black_pen) painter.setBrush(DrawToolBar.black_brush) painter.drawRect(geom[0].x(), geom[0].y(), geom[0].width(), geom[0].height()) except Exception: None return @staticmethod def drawMagnifierOnVideo(widget, dragPos, source, painter): ''' Draw Magnifier on Video ''' oldTransform = painter.transform() painter.setTransform(oldTransform) painter.setBrush(DrawToolBar.transparent_brush) dim = min(widget.width(), widget.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) center = dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * MAX_FACTOR - QPoint(radius, radius) # only set the dimension to the magnified portion zoomPixmap = QPixmap(box) zoomPixmap.fill(Qt.black) painter_p = QPainter(zoomPixmap) painter_p.setRenderHint(QPainter.HighQualityAntialiasing) painter_p.translate(-xy) painter_p.scale(MAX_FACTOR, MAX_FACTOR) painter_p.drawImage(widget.surface.videoRect(), source, widget.surface.sourceRect()) painter_p.end() clipPath = QPainterPath() center = QPointF(center) # Shape Type if TYPE_MAGNIFIER == 0: # Square clipPath.addRect(center.x(), center.y(), magnifierSize, magnifierSize) clipPath.translate(-radius, -radius) else: # Circle clipPath.addEllipse(center, ring, ring) painter.setClipPath(clipPath) painter.drawPixmap(corner, zoomPixmap) painter.setPen(DrawToolBar.glass_pen) painter.drawPath(clipPath) return @staticmethod def drawStampOnVideo(widget, painter): ''' Draw Stamp Confidential on Video ''' painter.drawPixmap(widget.surface.videoRect(), DrawToolBar.confidential, widget.surface.sourceRect())
def __init__(self, parent=None): ''' Constructor ''' super().__init__(parent) self.surface = VideoWidgetSurface(self) self.setAttribute(Qt.WA_OpaquePaintEvent) self.Tracking_Video_RubberBand = QRubberBand(QRubberBand.Rectangle, self) self.Censure_RubberBand = QRubberBand(QRubberBand.Rectangle, self) color_blue = QColor(Qt.blue) color_black = QColor(Qt.black) color_amber = QColor(252, 215, 108) pal_blue = QPalette() pal_blue.setBrush(QPalette.Highlight, QBrush(color_blue)) self.Tracking_Video_RubberBand.setPalette(pal_blue) pal_black = QPalette() pal_black.setBrush(QPalette.Highlight, QBrush(color_black)) self.Censure_RubberBand.setPalette(pal_black) self._interaction = InteractionState() self._filterSatate = FilterState() self._isinit = False self._MGRS = False self.gt = None self.drawCesure = [] self.poly_coordinates, self.drawPtPos, self.drawLines, self.drawMeasureDistance, self.drawMeasureArea, self.drawPolygon = [], [], [], [], [], [] # Draw Polygon Canvas Rubberband self.poly_Canvas_RubberBand = QgsRubberBand( iface.mapCanvas(), True) # Polygon type # set rubber band style self.poly_Canvas_RubberBand.setColor(color_amber) self.poly_Canvas_RubberBand.setWidth(3) # Tracking Canvas Rubberband self.Track_Canvas_RubberBand = QgsRubberBand( iface.mapCanvas(), QgsWkbTypes.LineGeometry) # set rubber band style self.Track_Canvas_RubberBand.setColor(color_blue) self.Track_Canvas_RubberBand.setWidth(5) # Cursor Canvas Rubberband self.Cursor_Canvas_RubberBand = QgsRubberBand( iface.mapCanvas(), QgsWkbTypes.PointGeometry) self.Cursor_Canvas_RubberBand.setWidth(4) self.Cursor_Canvas_RubberBand.setColor(QColor(255, 100, 100, 250)) self.Cursor_Canvas_RubberBand.setIcon(QgsRubberBand.ICON_FULL_DIAMOND) self.parent = parent.parent() palette = self.palette() palette.setColor(QPalette.Background, Qt.transparent) self.setPalette(palette) self.origin, self.dragPos = QPoint(), QPoint() self.tapTimer = QBasicTimer() self.brush = QBrush(color_black) self.blue_Pen = QPen(color_blue, 3)
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
def drawHistogram(self): #if self.inputlayer is None: # return self.showInfo("Drawing histogram...") viewprect = QRectF(self.histoGraphicsView.viewport().rect()) self.histoGraphicsView.setSceneRect(viewprect) self.setupScene.clear() self.setupScene.update() histbottom = self.histoGraphicsView.sceneRect().bottom() histtop = self.histoGraphicsView.sceneRect().top() left = self.histoGraphicsView.sceneRect().left() + self.histopadding right = self.histoGraphicsView.sceneRect().right() - self.histopadding histheight = histbottom - histtop histwidth = right - left step = 1.0 * histwidth / self.histobins maxlength = histheight padding = 1 ll = QPoint(self.histopadding - 1, histheight - padding) start = QPointF(self.histoGraphicsView.mapToScene(ll)) # Check if there is only one value #myrange = (self.minValueSpinBox.value(),self.maxValueSpinBox.value()) if self.histogramAvailable: maxvalue = 0.0 for i in range(len(self.histo[0])): if self.histo[0][i] > maxvalue: maxvalue = self.histo[0][i] if maxvalue == 0: return self.maxBinNumber.setText(str(maxvalue)) # Create the histogram: #self.showInfo("maxvalue: " + str(maxvalue)) #self.showInfo("maxlength: " + str(maxlength)) #self.showInfo("step: " + str(step)) for i in range(self.histobins): binnumber = self.histo[0][i] if binnumber == 0: continue height = (1.0 * self.histo[0][i] / maxvalue * (maxlength - padding)) rectangle = QGraphicsRectItem(start.x() + step * i, start.y(), step, -height) rectangle.setPen(QPen(QColor(102, 102, 102))) rectangle.setBrush(QBrush(QColor(240, 240, 240))) self.setupScene.addItem(rectangle) #self.showInfo(str(i) + ": " + str(height)) #if self.levelsListView.model().rowCount() > 0: # Add lines for the levels minvalue = float(self.histMinValue.text()) maxvalue = float(self.histMaxValue.text()) datarange = maxvalue - minvalue if datarange == 0: return i = 0 while self.levelsListView.model().item(i): #self.showInfo("Element: " + # str(self.levelsListView.model().item(i).text())) #continue value = float(self.levelsListView.model().item(i).text()) xvalue = start.x() + histwidth * (value - minvalue) / datarange line = QGraphicsLineItem(xvalue, 0, xvalue, histheight) if i == 0 or i == (self.levelsListView.model().rowCount() - 1): line.setPen(QPen(QColor(204, 0, 0))) else: line.setPen(QPen(QColor(0, 204, 0))) self.setupScene.addItem(line) i = i + 1
def paint(self, painter, option, widget): self.draw_background(painter) painter.setClipRect(0, 0, self.__width - 1, self.__height - 1) context = qgis_render_context(painter, self.__width, self.__height) context.setExtent(QgsRectangle(0, 0, self.__width, self.__height)) fields = self.__layer.fields() has_formation_code = "formation_code_column" in self.__column_mapping \ and self.__column_mapping["formation_code_column"] is not None # need to set fields in context so they can be evaluated in expression. # if not QgsExpressionNodeColumnRef prepareNode methods will fail when # checking that variable EXPR_FIELDS is defined (this variable is set # by setFields method context.expressionContext().setFields(fields) self.__renderer.startRender(context, fields) try: for i, f in enumerate(self.__data): depth_from = float(self.__field_value(f, "depth_from_column")) depth_to = float(self.__field_value(f, "depth_to_column")) if abs((self.__max_z - self.__min_z) * self.__height) > 0: y1 = (depth_from - self.__min_z) / ( self.__max_z - self.__min_z) * self.__height y2 = (depth_to - self.__min_z) / ( self.__max_z - self.__min_z) * self.__height painter.setPen(QPen()) painter.setBrush(QBrush()) if i == 0: painter.drawLine(0, y1, self.__width - 1, y1) painter.drawLine(0, y2, self.__width - 1, y2) if has_formation_code: # legend text formation_code = str( self.__field_value(f, "formation_code_column")) if formation_code: fm = painter.fontMetrics() w = fm.width(formation_code) x = (self.__width / 2 - w) / 2 + self.__width / 2 y = (y1 + y2) / 2 if y - fm.ascent() > y1 and y + fm.descent() < y2: painter.drawText(x, y, formation_code) geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.__height - y1, self.__width / 2, y1 - y2))) else: geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.__height - y1, self.__width, y1 - y2))) feature = QgsFeature(fields, 1) for field in fields: feature[field.name()] = f[field.name()] feature.setGeometry(geom) self.__renderer.renderFeature(feature, context) finally: self.__renderer.stopRender(context)
def paint(self, painter, option, widget): if not painter: return painter.save() painter.setRenderHint(QPainter.Antialiasing, True) # do a bit of trigonometry to find out how to transform a rotated item such # that the center point is at the point feature x = 0.0 y = 0.0 if self.pixmap.width() > 0 and self.pixmap.height() > 0: half_item_diagonal = math.sqrt( self.pixmap.width() * self.pixmap.width() + self.pixmap.height() * self.pixmap.height()) / 2 diagonal_angle = math.acos( self.pixmap.width() / (half_item_diagonal * 2)) * 180 / math.pi x = half_item_diagonal * math.cos( (self.rotation - diagonal_angle) * math.pi / 180) y = half_item_diagonal * math.sin( (self.rotation - diagonal_angle) * math.pi / 180) painter.rotate(self.rotation) painter.translate(x - self.pixmap.width() / 2.0, -y - self.pixmap.height() / 2.0) painter.drawPixmap(0, 0, self.pixmap) # draw arrow, using a red line over a thicker white line so that the arrow is visible # against a range of backgrounds pen = QPen() pen.setWidth(GuiUtils.scale_icon_size(4)) pen.setColor(QColor(Qt.white)) painter.setPen(pen) painter.drawPath(self.arrow_path) pen.setWidth(GuiUtils.scale_icon_size(1)) pen.setColor(QColor(Qt.red)) painter.setPen(pen) painter.drawPath(self.arrow_path) painter.restore() # draw numeric value beside the symbol painter.save() painter.setRenderHint(QPainter.Antialiasing, True) buffer_pen = QPen() buffer_pen.setColor(Qt.white) buffer_pen.setWidthF(GuiUtils.scale_icon_size(4)) fm = QFontMetricsF(self.marker_font) label = QPainterPath() label.addText(self.pixmap.width(), self.pixmap.height() / 2.0 + fm.height() / 2.0, self.marker_font, str(round(self.rotation, 1))) painter.setPen(buffer_pen) painter.setBrush(Qt.NoBrush) painter.drawPath(label) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(Qt.black)) painter.drawPath(label) painter.restore()
def on_btnAdd_clicked(self): item = QTreeWidgetItem() item.setText(0, '0.00') item.setText(1, '0.00') item.setBackground(2, QBrush(QColor(127, 127, 127))) self.reliefClassTree.addTopLevelItem(item)
def _getPenAndBrush(self): """Get the pen and brush""" pen = QPen() blackBrush = QBrush(QColor("black")) whiteBrush = QBrush(QColor("white")) return pen, blackBrush, whiteBrush