def testSelection(self, data): """ Given a Parameters ---------- data : (N, 2) array Point coordinates """ if len(data) == 0: return numpy.zeros(0, dtype=bool) def contained(a, left, top, right, bottom): assert left <= right and bottom <= top x, y = a.T return (x >= left) & (x <= right) & (y <= top) & (y >= bottom) data = numpy.asarray(data) selected = numpy.zeros(len(data), dtype=bool) for p1, p2 in self.selection: r = QRectF(p1, p2).normalized() # Note the inverted top/bottom (Qt coordinate system) selected |= contained(data, r.left(), r.bottom(), r.right(), r.top()) return selected
def paintEvent(self, event): crect = self.rect() painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QBrush(Qt.white)) painter.setPen(QPen(Qt.lightGray, 1.2)) painter.drawRoundedRect(QRectF(crect).adjusted(2, 2, -2, -2), 2, 2, Qt.AbsoluteSize) if self._selected: painter.setPen(QPen(QBrush(Qt.red), 2)) if self._highlighted: painter.setBrush(QBrush(Qt.gray, Qt.FDiagPattern)) else: painter.setBrush(Qt.NoBrush) painter.drawRoundedRect(QRectF(crect).adjusted(2, 2, -2, -2), 2, 2, Qt.AbsoluteSize) defsize = self.renderer().defaultSize() margin = 5 bound = QSize(defsize) bound.scale(crect.width() - margin, crect.height() - margin, Qt.KeepAspectRatio) svgrect = QRectF(0, 0, bound.width(), bound.height()) svgrect.moveCenter(crect.center()) self.renderer().render(painter, svgrect)
def visible_bounding_rect(items): """ Returns the bounding rectangle of all visible items. """ # initialize with min_x = float_info.max min_y = float_info.max max_x = -float_info.max max_y = -float_info.max for item in items: if item.isVisible(): itemBounds = item.boundingRect() itemTopLeft = item.mapToScene(itemBounds.topLeft()) itemBottomRight = item.mapToScene(itemBounds.bottomRight()) if itemTopLeft.x() < min_x: min_x = itemTopLeft.x() if itemTopLeft.y() < min_y: min_y = itemTopLeft.y() if itemBottomRight.x() > max_x: max_x = itemBottomRight.x() if itemBottomRight.y() > max_y: max_y = itemBottomRight.y() margin = 10 rect = QRectF(QPointF(min_x, min_y), QPointF(max_x, max_y)) rect.adjust(-margin, -margin, margin, margin) return rect
def __init__( self, screen, num_particles, pos, pos_irange, vel, vel_irange, duration, duration_irange, color_seq, quad_sz, img_path, ): self.screen = screen self.num_particles = num_particles self.setup_texture(img_path) # self.setup_display_list(quad_sz) self.particles = set() rect = QRectF(0.0, 0.0, quad_sz, quad_sz) rect.moveCenter(QPointF(0.0, 0.0)) for i in xrange(self.num_particles): pos = apply_irange(pos, pos_irange) vel = apply_irange(vel, vel_irange) duration = duration + uniform(*duration_irange) # p = Particle(pos, vel, color_seq, self.display_list, duration) p = Particle(pos, vel, color_seq, (self.texture, rect, self.screen.qpainter), duration) self.particles.add(p)
def paintEvent(self, paint_event): QFrame.paintEvent(self, paint_event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) w = self.width() h = self.height() if self.horizontal: self.min_marker = QRectF(w * self.min_value, 4, self.size, self.size) self.max_marker = QRectF(w * self.max_value - self.size - 1, 4, self.size, self.size) else: self.min_marker = QRectF(4, h - h * self.min_value - self.size - 1, self.size, self.size) self.max_marker = QRectF(4, h - h * self.max_value, self.size, self.size) pen = painter.pen() pen.setWidth(0) pen.setColor(QApplication.palette().background().color().dark()) painter.setPen(pen) painter.setBrush(self.min_marker_brush) painter.drawPie(self.min_marker, self.tilt * 16, 180 * 16) painter.setBrush(self.max_marker_brush) painter.drawPie(self.max_marker, self.tilt * 16, -180 * 16)
def __init__(self, eNodeHandle): QGraphicsObject.__init__(self) self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setAcceptsHoverEvents(True) self.__isDefaultPen = False self.__pen = None self.__pens = {0: EDraw.EColor.DefaultLeaveHoverPen, 1: EDraw.EColor.DefaultEnterHoverPen} self.setPen(self.__pens[self.__isDefaultPen]) self.__font = EDraw.DefaultNodeFont self.__nodeHandle = eNodeHandle self.__nodeHandle.Message.connect(self.__messageFilter) self.__name = self.__nodeHandle.__class__.__name__ self.__attrRect = QRectF(0, 0, 15, 15) self.__titleRect = QRectF(0, 0, 135, 20) self.__textSpace = QRectF(self.__attrRect.width() + self.pen().width(), 0.0, (self.__titleRect.width() - self.__attrRect.width() * 2 - self.pen().width() * 2) / 2, self.__attrRect.height()) self.buildAttributes() self.__height = max([self.__in_attr_step, self.__out_attr_step])
def showMoveHelper(self, visible=True): """show help text In empty HandBoards""" if visible: if not self.__moveHelper: splitter = QGraphicsRectItem(self) hbCenter = self.rect().center() splitter.setRect(hbCenter.x() * 0.5, hbCenter.y(), hbCenter.x() * 1, 1) helpItems = [splitter] for name, yFactor in [(m18n('Move Exposed Tiles Here'), 0.5), (m18n('Move Concealed Tiles Here'), 1.5)]: helper = QGraphicsSimpleTextItem(name, self) helper.setScale(3) nameRect = QRectF() nameRect.setSize(helper.mapToParent(helper.boundingRect()).boundingRect().size()) center = QPointF(hbCenter) center.setY(center.y() * yFactor) helper.setPos(center - nameRect.center()) if self.sceneRotation() == 180: rotateCenter(helper, 180) helpItems.append(helper) self.__moveHelper = self.scene().createItemGroup(helpItems) self.__moveHelper.setVisible(True) else: if self.__moveHelper: self.__moveHelper.setVisible(False)
def drawRow(row, sx, sy, last_end=False): x = sx y = sy keys = row rw = w - sx i = 0 for k in keys: rect = QRectF(x, y, kw, kw) if i == len(keys) - 1 and last_end: rect.setWidth(rw) p.drawRoundedRect(rect, rx, rx) p.setPen(Qt.black) rect.adjust(5, 1, 0, 0) p.setFont(self.lowerFont) p.drawText(rect, Qt.AlignLeft | Qt.AlignBottom, self.regular_text(k)) p.setFont(self.upperFont) p.drawText(rect, Qt.AlignLeft | Qt.AlignTop, self.shift_text(k)) rw = rw - space - kw x = x + space + kw i = i + 1 p.setPen(pen) return (x, rw)
def __activeControlMoved(self, pos): # The active control point has moved, update the control # rectangle control = self.__activeControl pos = control.pos() rect = QRectF(self.__rect) margins = self.__margins # TODO: keyboard modifiers and constraints. anchor = control.anchor() if anchor & ControlPoint.Top: rect.setTop(pos.y() + margins.top()) elif anchor & ControlPoint.Bottom: rect.setBottom(pos.y() - margins.bottom()) if anchor & ControlPoint.Left: rect.setLeft(pos.x() + margins.left()) elif anchor & ControlPoint.Right: rect.setRight(pos.x() - margins.right()) changed = self.__rect != rect self.blockSignals(True) self.setRect(rect) self.blockSignals(False) if changed: self.rectEdited.emit(rect.normalized())
def resize_scene_rect(self): # Check if we are QGraphicsItem and if we are on scene if(not callable(self.scene) or self.scene() == None): return # TODO: A place for optimization? rect = QRectF(self.scene().sceneRect()) self.scene().setSceneRect(rect.united(self.globalBoundingRect()))
def boundingRect(self): extra = (SfLine.ARROW_WIDTH + SfLine.ARROW_HEAD_LENGTH)/2.0 + 5 size = QSizeF(self.line().p2().x() - self.line().p1().x(), self.line().p2().y() - self.line().p1().y()) rect = QRectF(self.line().p1(), size) rect = rect.normalized() rect.adjust(-extra, -extra, extra, extra) return rect
def _fetch_tile_layer(self, timestamp, ims, transform, tile_nr, stack_id, ims_req, cache): """ Fetch a single tile from a layer (ImageSource). Parameters ---------- timestamp The timestamp at which ims_req was created ims The layer (image source) we're fetching from transform The transform to apply to the fetched data, before storing it in the cache tile_nr The ID of the fetched tile stack_id The stack ID of the tile we're fetching (e.g. which T-slice and Z-slice this tile belongs to) ims_req A request object (e.g. GrayscaleImageRequest) with a wait() method that produces an item of the appropriate type for the layer (i.e. either a QImage or a QGraphicsItem) cache The value of self._cache at the time the ims_req was created. (The cache can be replaced occasionally. See TileProvider._onSizeChanged().) """ try: try: with cache: layerTimestamp = cache.layerTimestamp(stack_id, ims, tile_nr) except KeyError: # May not be a timestamp yet (especially when prefetching) layerTimestamp = 0 tile_rect = QRectF( self.tiling.imageRects[tile_nr] ) if timestamp > layerTimestamp: img = ims_req.wait() if isinstance(img, QImage): img = img.transformed(transform) elif isinstance(img, QGraphicsItem): # FIXME: It *seems* like applying the same transform to QImages and QGraphicsItems # makes sense here, but for some strange reason it isn't right. # For QGraphicsItems, it seems obvious that this is the correct transform. # I do not understand the formula that produces 'transform', which is used for QImage tiles. img.setTransform(QTransform.fromTranslate(tile_rect.left(), tile_rect.top()), combine=True) img.setTransform(self.tiling.data2scene, combine=True) else: assert False, "Unexpected image type: {}".format( type(img) ) with cache: try: cache.updateTileIfNecessary(stack_id, ims, tile_nr, timestamp, img) except KeyError: pass if stack_id == self._current_stack_id \ and cache is self._cache: self.sceneRectChanged.emit( tile_rect ) except BaseException: sys.excepthook( *sys.exc_info() )
def boundingRect(self): if self._line is None: if self._orientation == Qt.Vertical: self._line = QLineF(0, self._value, self._length, self._value) else: self._line = QLineF(self._value, 0, self._value, self._length) r = QRectF(self._line.p1(), self._line.p2()) penw = self.pen().width() return r.adjusted(-penw, -penw, penw, penw)
def set_orientation(self, orientation): return if self.orientation == orientation: return self.orientation = orientation if self.orientation == Qt.Vertical: height = max(item.boundingRect().height() for item in self.label_items) total_height = height * max(5, len(self.label_items)) interval = (total_height - self.label_items[-1].boundingRect().height() ) / (len(self.label_items) - 1) self.gradient_item.setRect(10, 0, self.gradient_width, total_height) self.gradient.setStart(10, 0) self.gradient.setFinalStop(10, total_height) self.gradient_item.setBrush(QBrush(self.gradient)) self.gradient_item.setPen(QPen(Qt.NoPen)) y = -20 # hja, no; dela --> pri boundingRect() zato pristejem +20 x = 0 move_item_xy(self.title, x, y, False) y = 10 x = 30 for item in self.label_items: move_item_xy(item, x, y, False) # self.parent.graph.animate_plot) y += interval self.rect = QRectF(10, 0, self.gradient_width + max(item.boundingRect().width() for item in self.label_items), self.label_items[0].boundingRect().height() * max(5, len(self.label_items))) else: # za horizontalno orientacijo nisem dodajal title-a width = 50 height = max(item.boundingRect().height() for item in self.label_items) total_width = width * max(5, len(self.label_items)) interval = (total_width - self.label_items[-1].boundingRect().width() ) / (len(self.label_items) - 1) self.gradient_item.setRect(0, 0, total_width, self.gradient_width) self.gradient.setStart(0, 0) self.gradient.setFinalStop(total_width, 0) self.gradient_item.setBrush(QBrush(self.gradient)) self.gradient_item.setPen(QPen(Qt.NoPen)) x = 0 y = 30 for item in self.label_items: move_item_xy(item, x, y, False) # self.parent.graph.animate_plot) x += interval self.rect = QRectF(0, 0, total_width, self.gradient_width + height)
def setSceneRect(self, *args): if len(args) == 1: rect = args[0] else: left, top, width, height = args rect = QRectF(left, top, width, height) for item in self._listaItens: item.setTamanho(QRectF(0,0,rect.width(),item.altura())) super().setSceneRect(rect)
def paint(self, painter, style, widget): painter.setFont(self.__font) painter.setPen(QPen(QColor(0, 0, 0), 1, Qt.DotLine)) metrics = QFontMetrics(self.__font) painter.drawLine(QLineF(QPointF(metrics.width(self.__text) / 2, metrics.height() / 2), QPointF(self.__get_local_origin()))) text_rect = QRectF(0, 0, metrics.width(self.__text), metrics.height()).adjusted(0, 0, 2 * self.__extraFrame, 2 * self.__extraFrame) painter.fillRect(text_rect, QBrush(QColor(255,255,255))) painter.drawText(text_rect.translated(self.__extraFrame, self.__extraFrame), 0, self.__text)
def paintEvent(self, event): QFrame.paintEvent(self, event) text = QDateTime.currentDateTime().toString(Qt.SystemLocaleLongDate) logicalRect = QRectF(QPointF(0, 0), QSizeF(QFontMetrics(self.font()).size(Qt.TextSingleLine, text))) physicalRect, frameWidth = QRectF(self.rect()), self.frameWidth() physicalRect.adjust(frameWidth, frameWidth, -frameWidth, -frameWidth) scaleForWidth = physicalRect.width() / logicalRect.width() scaleForHeight = physicalRect.height() / logicalRect.height() logicalRect.moveTo(frameWidth / scaleForWidth , frameWidth / scaleForHeight) painter = QStylePainter(self) painter.scale(scaleForWidth, scaleForHeight) painter.drawText(logicalRect, Qt.AlignCenter, text)
def setCenter(self, lon, lat): """Move the center of the visible area to new coordinates. Update the scene rect. Args: lon(float): New longitude of the center. lat(float): New latitude of the center. """ rect = QRectF(self.sceneRect()) pos = self.posFromLonLat(lon, lat) rect.moveCenter(pos) self.setSceneRect(rect)
def wait(self): array_data = self._arrayreq.wait() rectf = self.rectf if array_data.handedness_switched: # array_data should be of type slicingtools.ProjectedArray rectf = QRectF(rectf.height(), rectf.width()) from PyQt4.QtGui import QPainter img = QImage( QSize( self.rectf.width(), self.rectf.height() ), QImage.Format_ARGB32_Premultiplied) img.fill(0xffffffff) p = QPainter(img) p.drawImage(0,0, img) DummyItem(self.rectf).paint(p, None) return img
def paintEvent(self, event): if self.__pixmap.isNull(): return sourcerect = QRect(QPoint(0, 0), self.__pixmap.size()) pixsize = QSizeF(self.__pixmap.size()) rect = self.contentsRect() pixsize.scale(QSizeF(rect.size()), Qt.KeepAspectRatio) targetrect = QRectF(QPointF(0, 0), pixsize) targetrect.moveCenter(QPointF(rect.center())) painter = QPainter(self) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.drawPixmap(targetrect, self.__pixmap, QRectF(sourcerect)) painter.end()
def paintEvent(self, event): pixmap = self._shadowPixmap widget_rect = QRectF(QPointF(0.0, 0.0), QSizeF(self.size())) frame_rect = QRectF(self.contentsRect()) left, top, right, bottom = self.getContentsMargins() pixmap_rect = QRectF(QPointF(0, 0), QSizeF(pixmap.size())) # Shadow casting rectangle. pixmap_shadow_rect = pixmap_rect.adjusted(left, top, -right, -bottom) source_rects = self._shadowPixmapFragments(pixmap_rect, pixmap_shadow_rect) target_rects = self._shadowPixmapFragments(widget_rect, frame_rect) painter = QPainter(self) for source, target in zip(source_rects, target_rects): painter.drawPixmap(target, pixmap, source) painter.end()
def mousePressEvent(self, event): pos = event.scenePos() any_item = self.scene.item_at(pos) if not any_item and event.button() & Qt.LeftButton: self.modifiers = event.modifiers() self.selection_rect = QRectF(pos, QSizeF(0, 0)) self.rect_item = QGraphicsRectItem( self.selection_rect.normalized() ) self.rect_item.setPen( QPen(QBrush(QColor(51, 153, 255, 192)), 0.4, Qt.SolidLine, Qt.RoundCap) ) self.rect_item.setBrush( QBrush(QColor(168, 202, 236, 192)) ) self.rect_item.setZValue(-100) # Clear the focus if necessary. if not self.scene.stickyFocus(): self.scene.clearFocus() if not self.modifiers & Qt.ControlModifier: self.scene.clearSelection() event.accept() return True else: self.cancel(self.ErrorReason) return False
def __init__(self, title, palette, values, parent): QGraphicsObject.__init__(self, parent) GraphicsWidgetAnchor.__init__(self) self.parent = self.legend = parent self.palette = palette self.values = values self.title = QGraphicsTextItem('%s:' % title, self) f = self.title.font() f.setBold(True) self.title.setFont(f) self.title_item = QGraphicsRectItem(self.title.boundingRect(), self) self.title_item.setPen(QPen(Qt.NoPen)) self.title_item.stackBefore(self.title) self.label_items = [QGraphicsTextItem(text, self) for text in values] for i in self.label_items: i.setTextWidth(50) self.rect = QRectF() self.gradient_item = QGraphicsRectItem(self) self.gradient = QLinearGradient() self.gradient.setStops([(v * 0.1, self.palette[v * 0.1]) for v in range(11)]) self.orientation = Qt.Horizontal self.set_orientation(Qt.Vertical) self.setFlag(QGraphicsItem.ItemIgnoresTransformations, True) self.setFlag(QGraphicsItem.ItemIsMovable, True)
def clean_input_buffer_from_screen(self): rect = QRectF() rect.setX(self.lastwindow.cursor_real_pos[0]) rect.setY(self.lastwindow.cursor_real_pos[1]) rect.setWidth(self.pbuffer[0].width()-self.lastwindow.cursor_real_pos[0]+1) rect.setHeight(self.linesize) txtbuffer = '' for w in self.input_buf: txtbuffer += w bounding_rect = self.pbuffer_painter[0].boundingRect(rect, txtbuffer) if (rect.contains(bounding_rect)): # string fits in this line self.pbuffer_painter[0].eraseRect(bounding_rect) #self.pbuffer_painter.drawRect(bounding_rect) #print 'Erasing rect', bounding_rect else: self.pbuffer_painter[0].eraseRect(rect)
def update(self): metrics = QFontMetrics(self.__font) # Start by finding size of class name block drawable_height = 1 * self.__section_margin + metrics.height() # TODO: This doesn't belong here. Or does it? if "name" not in self.uml_object.properties: self.uml_object["name"] = self.uml_object.name drawable_width = 2 * self.__text_margin + metrics.width(self.uml_object['name']) # Add stereotype height if("stereotype" in self.uml_object.properties): drawable_height += self.__text_margin + metrics.height() stereotypeWidth = 2 * self.__text_margin + metrics.width("<< " + self.uml_object['stereotype'] + " >>") drawable_width = max(drawable_width, stereotypeWidth) # Find sizes of each section and update width/height for section in [map(str, self.uml_object.operations()), map(str, self.uml_object.attributes())]: size = self.__size_of_section(metrics, section) drawable_width = max(drawable_width, size[0]) drawable_height += size[1] self.__bounding_rect = QRectF(0, 0, max(2 * self.__text_margin + drawable_width, self.__min_width), drawable_height)
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() # na pozici [0, 0] se šířkou 50px a výškou 50px # musíme ho vykreslit my, protože je to pouze abstraktní objekt (abstrakní ve smyslu, že nám pouze uchovává data a poskytuje potřebné výpočty) self.__drag_and_drop_rect = QRectF(QPointF(), QSizeF(50, 50)) self.__rect_color = QColor("red") self.__mouse_pressed = False def paintEvent(self, _): """ :type _: QPaintEvent """ painter = QPainter(self) painter.setBrush(QBrush(self.__rect_color)) painter.setPen(QPen(self.__rect_color)) painter.drawRect(self.__drag_and_drop_rect) def mousePressEvent(self, mouse_event): """ :type mouse_event: QMouseEvent """ # je v bod kliknutí v obdelníku? self.__mouse_pressed = self.__drag_and_drop_rect.contains(mouse_event.pos()) def mouseReleaseEvent(self, _): """ :type _: QMouseEvent """ self.__mouse_pressed = False def mouseMoveEvent(self, mouse_event): """ :type mouse_event: QMouseEvent """ if not self.__mouse_pressed: return # přesuň obdelník na pozici kurzoru self.__drag_and_drop_rect.moveTo(mouse_event.pos()) # obnov okno(zavolá se metoda paintEvent) self.update()
def __init__(self, qScore, parent = None): super(QGraphicsListData, self).__init__(parent = parent, scene = qScore) self._qScore = qScore self._props = qScore.displayProperties self._rect = QRectF(0, 0, 0, 0) self.setRect() self.setCursor(Qt.PointingHandCursor) self.setAcceptsHoverEvents(True)
def paint(self, painter, option, widget=0): if self._pixmap.isNull(): return rect = self.contentsRect() pixsize = self.pixmapSize() pixrect = QRectF(QPointF(0, 0), pixsize) pixrect.moveCenter(rect.center()) painter.save() painter.setPen(QPen(QColor(0, 0, 0, 50), 3)) painter.drawRoundedRect(pixrect, 2, 2) painter.setRenderHint(QPainter.SmoothPixmapTransform) source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size())) painter.drawPixmap(pixrect, self._pixmap, source) painter.restore()
def __init__(self): super(MainWindow, self).__init__() # na pozici [0, 0] se šířkou 50px a výškou 50px # musíme ho vykreslit my, protože je to pouze abstraktní objekt (abstrakní ve smyslu, že nám pouze uchovává data a poskytuje potřebné výpočty) self.__drag_and_drop_rect = QRectF(QPointF(), QSizeF(50, 50)) self.__rect_color = QColor("red") self.__mouse_pressed = False
def inputLocation( self ): """ Returns the input location for this connection. :return <XConnectionLocation> """ if ( not self.autoCalculateInputLocation() ): return self._inputLocation # auto calculate directions based on the scene if ( self._outputNode ): outputRect = self._outputNode.sceneRect() else: y = self._outputPoint.y() outputRect = QRectF( self._outputPoint.x(), y, 0, 0 ) if ( self._inputNode ): inputRect = self._inputNode.sceneRect() else: y = self._inputPoint.y() inputRect = QRectF( self._inputPoint.x(), y, 0, 0 ) # use the input location as potential places where it can be iloc = self._inputLocation left = XConnectionLocation.Left right = XConnectionLocation.Right top = XConnectionLocation.Top bot = XConnectionLocation.Bottom if ( self._inputNode == self._outputNode ): if ( iloc & right ): return right elif ( iloc & left ): return left elif ( iloc & top ): return top else: return bot elif ( (iloc & left) and outputRect.right() < inputRect.left() ): return left elif ( (iloc & right) and inputRect.right() < outputRect.left() ): return right elif ( (iloc & top) and outputRect.bottom() < inputRect.top() ): return top elif ( (iloc & bot) ): return bot elif ( (iloc & left) ): return left elif ( (iloc & right) ): return right elif ( (iloc & top) ): return top else: return left
def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) TEST_DATA_DIR = unitTestDataPath() self.pngImage = TEST_DATA_DIR + "/sample_image.png" # create composition self.mapSettings = QgsMapSettings() self.composition = QgsComposition(self.mapSettings) self.composition.setPaperSize(297, 210) self.composerPicture = QgsComposerPicture(self.composition) self.composerPicture.setPicturePath(self.pngImage) self.composerPicture.setSceneRect(QRectF(70, 70, 100, 100)) self.composerPicture.setFrameEnabled(True) self.composition.addComposerPicture(self.composerPicture)
def _define_symbols(): """ Add symbol ? to ScatterPlotItemSymbols, reflect the triangle to point upwards """ symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols path = QPainterPath() path.addEllipse(QRectF(-0.25, -0.25, 0.5, 0.5)) path.moveTo(-0.5, 0.5) path.lineTo(0.5, -0.5) path.moveTo(-0.5, -0.5) path.lineTo(0.5, 0.5) symbols["?"] = path tr = QTransform() tr.rotate(180) symbols['t'] = tr.map(symbols['t'])
def paintArc(self, center_x, center_y, start_x, start_y, end_x, end_y): radius = math.sqrt( math.pow(center_x - start_x, 2) + math.pow(center_y - start_y, 2)) rect = QRectF(center_x - radius, center_y - radius, radius * 2, radius * 2) startAngle = 16 * math.atan2(start_x - center_y, start_x - center_x) * 180.0 / math.pi endAngle = 16 * math.atan2(end_y - center_y, end_x - center_x) * 180.0 / math.pi spanAngle = endAngle - startAngle self.__painter.begin(self.__board) self.__painter.setPen(QPen(self.__penColor, self.__thickness)) self.__painter.drawArc(rect, startAngle, spanAngle) self.__painter.end() self.update() #Show updates
def boundingRect(self): font = QFont('Verdana', 8) fm = QFontMetricsF(font) unfolded = isinstance(self.element, Algorithm) and not self.element.paramsFolded numParams = len(self.element.algorithm.parameters) if unfolded else 0 unfolded = isinstance(self.element, Algorithm) and not self.element.outputsFolded numOutputs = len(self.element.algorithm.outputs) if unfolded else 0 hUp = fm.height() * 1.2 * (numParams + 2) hDown = fm.height() * 1.2 * (numOutputs + 2) rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp, ModelerGraphicItem.BOX_WIDTH + 2, ModelerGraphicItem.BOX_HEIGHT + hDown + hUp) return rect
def getTiles(self, rectF): '''Get tiles in rect and request a refresh. Returns tiles intersecting with rectF immediately and requests a refresh of these tiles. Next time you call this function the tiles may be already (partially) updated. If you want to wait until the rendering is fully complete, call join(). ''' self.requestRefresh(rectF) tile_nos = self.tiling.intersected(rectF) stack_id = self._current_stack_id for tile_no in tile_nos: with self._cache: qimg, progress = self._cache.tile(stack_id, tile_no) yield TileProvider.Tile(tile_no, qimg, QRectF(self.tiling.imageRects[tile_no]), progress, self.tiling)
def __init__(self, parent=None, channel=None, rect=None, **kwargs): QGraphicsRectItem.__init__(self, **kwargs) self.setAcceptHoverEvents(True) self.setAcceptedMouseButtons(Qt.NoButton) self.__channel = None if rect is None: rect = QRectF(0, 0, 20, 20) self.setRect(rect) if channel: self.setChannel(channel) self.__shadow = QGraphicsDropShadowEffect(blurRadius=5, offset=QPointF(0, 0)) self.setGraphicsEffect(self.__shadow) self.__shadow.setEnabled(False)
def mouseDragEvent(self, ev, axis=None): if self.graph.state == SELECT and axis is None: ev.accept() pos = ev.pos() if ev.button() == Qt.LeftButton: self.safe_update_scale_box(ev.buttonDownPos(), ev.pos()) if ev.isFinish(): self.rbScaleBox.hide() pixel_rect = QRectF(ev.buttonDownPos(ev.button()), pos) value_rect = self.childGroup.mapRectFromParent(pixel_rect) self.graph.select_by_rectangle(value_rect) else: self.safe_update_scale_box(ev.buttonDownPos(), ev.pos()) elif self.graph.state == ZOOMING or self.graph.state == PANNING: ev.ignore() super().mouseDragEvent(ev, axis=axis) else: ev.ignore()
def __init__(self, palette, values, parent): QGraphicsObject.__init__(self, parent) self.parent = parent self.palette = palette self.values = values self.legend = parent self.label_items = [QGraphicsTextItem(text, self) for text in values] for i in self.label_items: i.setTextWidth(50) self.rect = QRectF() self.gradient_item = QGraphicsRectItem(self) self.gradient = QLinearGradient() self.gradient.setStops([(v * 0.1, self.palette[v * 0.1]) for v in range(11)]) self.orientation = Qt.Horizontal self.set_orientation(Qt.Vertical)
def fitImage(self): """ Fits the image to the View. :return: Method success. :rtype: bool """ if not self.__displayGraphicsItem: return False self.__graphicsView.fitInView( QRectF(-(self.__displayGraphicsItem.width / 2) - (self.__displayGraphicsItemMargin / 2), - (self.__displayGraphicsItem.height / 2) - (self.__displayGraphicsItemMargin / 2), self.__displayGraphicsItem.width + self.__displayGraphicsItemMargin, self.__displayGraphicsItem.height + self.__displayGraphicsItemMargin), Qt.KeepAspectRatio) return True
def mouseMoveEvent(self, event): if not self.dragging_line and self.drag_line and ( self.start_drag - event.screenPos()).manhattanLength() > 5: self.dragging_line = True if self.dragging_line: params = parameters.instance ms = min(self.scale) sel_thick = 2 * params.cell_thickness if sel_thick == 0: sel_thick = 2 * ms self.prepareGeometryChange() mp = self.moving_point mp.setX(event.pos().x()) mp.setY(event.pos().y()) self.bounding_rect = self.rect | QRectF( mp.x() - sel_thick, mp.y() - sel_thick, 2 * sel_thick, 2 * sel_thick) self.update()
def drawStats(self, qp): defaultCol = QColor(0,255,0, 200) #qp = QtGui.QPainter() qp.resetTransform() w = self.width() h = self.height() top = 50 bottom = h-50 width, height = w*0.2, 22 dist = 10 space = height+dist pos = width/4 # DRAW PROGRESS BAGS (left) if self.bat>-1: self.drawBar(qp, QRectF(pos, top+space*0, width,height), defaultCol, 'BAT %4.2fV'%(self.bat/1000.), self.bat, 3000, 4150) if self.link>-1: self.drawBar(qp, QRectF(pos, top+space*1, width,height), defaultCol, 'SIG %03d%%'%self.link, self.link) if self.cpu>-1: self.drawBar(qp, QRectF(pos, top+space*2, width,height), defaultCol, 'CPU %03d%%'%self.cpu, self.cpu) # DRAW RAW STATS( right) pos = w-width/4-width/2 space = height+2 if self.pktsOut>-1: qp.drawText(QRectF(pos, top+space*0, width,height), Qt.AlignLeft, '%04d kb/s'%self.pktsOut) if self.pktsIn>-1: qp.drawText(QRectF(pos, top+space*1, width,height), Qt.AlignLeft, '%04d kb/s'%self.pktsIn) if self.pressure>-1: qp.drawText(QRectF(pos, top+space*3, width,height), Qt.AlignLeft, '%06.2f hPa'%self.pressure) if self.temp>-1: qp.drawText(QRectF(pos, top+space*4, width,height), Qt.AlignLeft, QString('%05.2f'%self.temp)+QChar(0260)+QString("C")) if self.aslLong>-1: qp.drawText(QRectF(pos, top+space*5, width,height), Qt.AlignLeft, '%4.2f m'%self.aslLong)
def update_items(self): """ Updates the legend, repositioning the items according to the legend's orientation. """ self.box_rect = QRectF() x = y = 0 for lst in self.items.itervalues(): for item in lst: if hasattr(item, 'text_item'): item.text_item.setDefaultTextColor( self.graph.color(OWPalette.Text)) if hasattr(item, 'rect_item'): item.rect_item.setBrush(self.graph.color(OWPalette.Canvas)) if hasattr(item, 'set_orientation'): item.set_orientation(self._orientation) if self._orientation == Qt.Vertical: for lst in self.items.itervalues(): for item in lst: if self.max_size.height() and y and y + item.boundingRect( ).height() > self.max_size.height(): y = 0 x = x + item.boundingRect().width() self.box_rect = self.box_rect | item.boundingRect( ).translated(x, y) move_item_xy(item, x, y, self.graph.animate_plot) y = y + item.boundingRect().height() elif self._orientation == Qt.Horizontal: for lst in self.items.itervalues(): max_h = max(item.boundingRect().height() for item in lst) for item in lst: if self.max_size.width() and x and x + item.boundingRect( ).width() > self.max_size.width(): x = 0 y = y + max_h self.box_rect = self.box_rect | item.boundingRect( ).translated(x, y) move_item_xy(item, x, y, self.graph.animate_plot) x = x + item.boundingRect().width() if lst: x = 0 y = y + max_h
def updateDescAndQL(self): # get the name of the selected dataset dataset_name, dataset_serviceType = self.getSelectedNameAndType() #custom web service object dataset = self.selectdataSets(dataset_name, dataset_serviceType) quicklook = os.path.join(self.quicklooks_dir, dataset.QLname + ".jpg") desc = dataset.getDescription(self.language) name = dataset.getName(self.language) #update decription self.dlg.textEdit.clear() #creation and last update if self.language == "EN": crDate = "Creation date : " + dataset.creationDate update = "Last update : " + dataset.lastUpdate elif self.language == "GR": crDate = unicode( "Ημερομηνια δημιουργιας : " + dataset.creationDate, 'utf-8') update = unicode("Τελευταία ενημέρωση : " + dataset.lastUpdate, 'utf-8') cursor = QTextCursor(self.dlg.textEdit.document()) cursor.insertHtml("<h3> " + name + " <br><br></h3>") cursor.insertHtml("<p> " + desc + " <br><br><br></p>") cursor.insertHtml("<p><i> " + crDate + " <br></i></p>") #cursor.insertHtml("<p><i> "+update+" <br></i></p>") self.dlg.textEdit.setReadOnly(True) #update quicklook #GET DIMENSIONS OF THE IMAGE img = Image.open(quicklook) w, h = img.size scene = QGraphicsScene() pic = QPixmap(quicklook) scene.addItem(QGraphicsPixmapItem(pic)) self.dlg.graphicsView.setScene(scene) self.dlg.graphicsView.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio) self.dlg.graphicsView.show()
def setImage(self, image): """ Set the scene's current image pixmap to the input QImage or QPixmap. Raises a RuntimeError if the input image has type other than QImage or QPixmap. :type image: QImage | QPixmap """ if type(image) is QPixmap: pixmap = image elif type(image) is QImage: pixmap = QPixmap.fromImage(image) else: raise RuntimeError( "ImageViewer.setImage: Argument must be a QImage or QPixmap.") if self.hasImage(): self._pixmapHandle.setPixmap(pixmap) else: self._pixmapHandle = self.scene.addPixmap(pixmap) self.setSceneRect(QRectF( pixmap.rect())) # Set scene size to image size. self.updateViewer()
def drawImage(self, x, y, rx, ry, hImg): h = self.v.height() x0, y0 = self.t.transform(x, y) #rx=self.t.sx*rx #ry=self.t.sy*ry rx, ry = self.t.scale(rx, ry) #self.qPainter.drawRect(x0,h-y0,rx,-ry) r = QRectF(x0, h - y0 - ry, rx, ry) qImg = self.convertMatToQImage(hImg, rx, ry) #r=QRectF(x0,h-y0-ry,qImg.width()/2,qImg.height()/2) #qImg=QImage('../images/im2.png') #mat=hImg.convertQImageToMat(qImg) #cv2.imshow('nada',hImg.getData()) #print mat.shape #qImg=OpenCVQImage(mat) #qImgs=qImg.scaled(int(rx),int(ry)) #qImg=QImage('../images/CAM00293.jpg') #cvi=cv2.imread('../images/CAM00293.jpg') self.qPainter.drawImage(r, qImg)
def _setup_scene(self): self.matrix_item = DistanceMapItem(self._sorted_matrix[:, ::-1]) self.viewbox.addItem(self.matrix_item) self.viewbox.setRange(QRectF(0, 0, *self._sorted_matrix.shape), padding=0) self.matrix_item.selectionChanged.connect(self._invalidate_selection) if self.sorting == 0: tree = None elif self.sorting == 1: tree = self._cluster_tree() else: tree = self._ordered_cluster_tree() self._set_displayed_dendrogram(tree) self._update_color()
def mousePressEvent(self, event): if event.button() == Qt.LeftButton: pos = self.mapToPlot(event.pos()) if self._item.isVisible(): if self.selectionRect().contains(pos): event.setAccepted(False) self._item.setCursor(Qt.ClosedHandCursor) return False self._start_pos = pos self._item.setVisible(True) self._plot.addItem(self._item) self.setSelectionRect(QRectF(pos, pos)) event.accept() self.editingStarted.emit() return True else: return super().mousePressEvent(event)
def item_at(self, pos, type_or_tuple=None, buttons=0): """Return the item at `pos` that is an instance of the specified type (`type_or_tuple`). If `buttons` (`Qt.MouseButtons`) is given only return the item if it is the top level item that would accept any of the buttons (`QGraphicsItem.acceptedMouseButtons`). """ rect = QRectF(pos, QSizeF(1, 1)) items = self.items(rect) if buttons: items = itertools.dropwhile( lambda item: not item.acceptedMouseButtons() & buttons, items) items = list(items)[:1] if type_or_tuple: items = [i for i in items if isinstance(i, type_or_tuple)] return items[0] if items else None
def drawTiles(self, renderContext, tiles, sdx=1.0, sdy=1.0): # create an image that has the same resolution as the tiles image = tiles.image() # tile extent to pixel map2pixel = renderContext.mapToPixel() extent = tiles.extent() topLeft = map2pixel.transform(extent.xMinimum(), extent.yMaximum()) bottomRight = map2pixel.transform(extent.xMaximum(), extent.yMinimum()) rect = QRectF(QPointF(topLeft.x() * sdx, topLeft.y() * sdy), QPointF(bottomRight.x() * sdx, bottomRight.y() * sdy)) # draw the image on the map canvas renderContext.painter().drawImage(rect, image) self.log("Tiles extent: " + str(extent)) self.log("Draw into canvas rect: " + str(rect))
def prepareExport(self): if self.dlg is None: return self.setNumberOfSteps(1 + self.dlg.stack_tiffs()) # grab settings from dialog start, stop = self.dlg.getRoi() iter_axes, iter_coords, iter_n = self.dlg.getIterAxes() slice_axes = self.dlg.sliceAxes show_markers = self.dlg.showMarkers() folder, pattern, fileExt = self.dlg.getExportInfo() # width and height of images w = stop[slice_axes[0]] - start[slice_axes[0]] h = stop[slice_axes[1]] - start[slice_axes[1]] # scene rectangle to render rect = QRectF(start[slice_axes[0]], start[slice_axes[1]], w, h) # remember current position to correctly place view afterwards self.currentPos5D = list(self.posModel.slicingPos5D) pos = list(start) # show/hide slice intersection markers self.showed_markers = self.view._sliceIntersectionMarker.isVisible() if show_markers: self.view._sliceIntersectionMarker.setVisible(True) # to correctly display slice intersection markers for a in slice_axes: pos[a] = self.currentPos5D[a] else: self.view._sliceIntersectionMarker.setVisible(False) # create plain image and painter self.img = QImage(w, h, QImage.Format_RGB16) self.img.fill(Qt.black) self.painter = QPainter(self.img) # prepare export loop self.exportloop = self.loopGenerator(rect, pos, start, stop, iter_axes, iter_coords, folder, pattern, fileExt)
def draw_image(self, painter, canvasRect, srcRect, dstRect, xMap, yMap): # normally we use this method indirectly from quiqwt which takes the burden of constructing # the right parameters. if we want to call this method manually, eg for painting on on a # QPixmap for saving the image, we just use the last set of parmeters passed to this # method, this is much easier than constructing the params seperatly, and so we get the # exact same result as we see on screen: self.last_canvas_rect = canvasRect self.last_src_rect = srcRect self.last_dst_rect = dstRect self.last_xmap = xMap self.last_ymap = yMap rtmin, mzmax, rtmax, mzmin = srcRect x1, y1 = canvasRect.left(), canvasRect.top() x2, y2 = canvasRect.right(), canvasRect.bottom() NX = x2 - x1 NY = y2 - y1 rtmin, mzmax, rtmax, mzmin = srcRect image = self.compute_image(0, NX, NY, rtmin, rtmax, mzmin, mzmax)[::-1, :] image2 = self.compute_image(1, NX, NY, rtmin, rtmax, mzmin, mzmax)[::-1, :] dilated = dilate(image.astype(np.int32), mzmax, mzmin) dilated2 = dilate(image2.astype(np.int32), mzmax, mzmin) self.data = np.zeros_like(dilated, dtype=np.uint32)[::-1, :] # add image as rgb(255, 255, 0): first we add red, then green which yields yellow: self.data += dilated * 256 * 256 # plus red: self.data += dilated * 256 # add image2 as rgb(0, 0, 256) which is blue: self.data += dilated2 self.data |= 255 << 24 self.bounds = QRectF(rtmin, mzmin, rtmax - rtmin, mzmax - mzmin) RGBImageItem.draw_image(self, painter, canvasRect, srcRect, dstRect, xMap, yMap)
def joinRenderingAllTiles(self, viewport_only=True, rect=None): """ Wait until all tiles in the scene have been 100% rendered. If sceneRectF is None, use the viewport rect. If sceneRectF is an invalid QRectF(), then wait for all tiles. Note: If called from the GUI thread, the GUI thread will block until all tiles are rendered! """ # If this is the main thread, keep repainting (otherwise we'll deadlock). if threading.current_thread().name == "MainThread": if viewport_only: sceneRectF = self.views()[0].viewportRect() else: if rect is None or not isinstance(rect, QRectF): sceneRectF = QRectF( ) # invalid QRectF means 'get all tiles' else: sceneRectF = rect self._tileProvider.waitForTiles(sceneRectF) else: self._allTilesCompleteEvent.wait()
def __init__(self, rect=QRectF(-5, -5, 10, 10), view=None): super().__init__(rect) self.setCacheMode(self.DeviceCoordinateCache) self.setAcceptHoverEvents(True) self.setFlags(self.ItemIsMovable | self.ItemIsSelectable | self.ItemIgnoresTransformations | self.ItemIgnoresParentOpacity | self.ItemSendsGeometryChanges) self.setZValue(4) self.edges = [] self._radius = rect.width() / 2 self.__transform = view.transform # Add text labels label = self.label = QtGui.QGraphicsSimpleTextItem('test', self) label.setVisible(False) label.setFlags(self.ItemIgnoresParentOpacity | self.ItemIgnoresTransformations) label.setZValue(3) view.scene().addItem(label)
def mouseReleaseEvent(self, event): # Reimplemented if event.button() == Qt.LeftButton: if self.__selectionRect is not None: self.__selectionRect.setParentItem(None) if self.scene() is not None: self.scene().removeItem(self.__selectionRect) self.__selectionRect = None event.accept() rect = (QRectF(event.buttonDownPos(Qt.LeftButton), event.pos()).normalized()) if not rect.isValid(): rect = rect.adjusted(-1e-7, -1e-7, 1e-7, 1e-7) rect = rect.intersected(self.contentsRect()) action = action = self.__selstate.action & ~SelectAction.Current self.__setSelectionRect(rect, action) self.__selstate = None
def mouseMoveEvent(self, event): # Reimplemented if event.buttons() & Qt.LeftButton: assert self.__selstate is not None if self.__selectionRect is None: self.__selectionRect = QtGui.QGraphicsRectItem(self) rect = (QRectF(event.buttonDownPos(Qt.LeftButton), event.pos()).normalized()) if not rect.width(): rect = rect.adjusted(-1e-7, -1e-7, 1e-7, 1e-7) rect = rect.intersected(self.contentsRect()) self.__selectionRect.setRect(rect) self.__selstate.rect = rect self.__selstate.action |= SelectAction.Current self.__setSelectionRect(rect, self.__selstate.action) event.accept()
def paint(self, painter, option, widget=None): if not self.__isCollapsed: painter.setPen(QPen(QColor(0, 0, 0, 50), 2, Qt.SolidLine)) painter.setBrush(QColor(0, 0, 0, 50)) painter.drawRect(self.boundingRect().adjusted( self.pen().width(), self.__handleHeight, -self.pen().width(), 0.0)) painter.setPen(self.pen()) painter.setBrush( EDraw.EColor.LinearGradient(self.__handleRect, Qt.darkGray)) #painter.drawPolygon( QPolygonF( self.__handleRect.normalized().adjusted(-self.__boundExtra, 0.0, self.__boundExtra, 0.0 ) ) ) painter.drawPolygon(QPolygonF(self.__handleRect)) painter.setPen(Qt.lightGray) r = QRectF(0.0, 0.0, self.__name.boundingRect().width(), self.__handleRect.height()) painter.drawText(r, Qt.AlignCenter, self.__name.toPlainText())
def render_drop_shadow_frame(pixmap, shadow_rect, shadow_color, offset, radius, rect_fill_color): pixmap.fill(QColor(0, 0, 0, 0)) scene = QGraphicsScene() rect = QGraphicsRectItem(shadow_rect) rect.setBrush(QColor(rect_fill_color)) rect.setPen(QPen(Qt.NoPen)) scene.addItem(rect) effect = QGraphicsDropShadowEffect(color=shadow_color, blurRadius=radius, offset=offset) rect.setGraphicsEffect(effect) scene.setSceneRect(QRectF(QPointF(0, 0), QSizeF(pixmap.size()))) painter = QPainter(pixmap) scene.render(painter) painter.end() scene.clear() scene.deleteLater() return pixmap
def paint(self, painter, option, widget=None): if not self.__icon.isNull(): if option.state & QStyle.State_Selected: mode = QIcon.Selected elif option.state & QStyle.State_Enabled: mode = QIcon.Normal elif option.state & QStyle.State_Active: mode = QIcon.Active else: mode = QIcon.Disabled transform = self.sceneTransform() if widget is not None: # 'widget' is the QGraphicsView.viewport() view = widget.parent() if isinstance(view, QGraphicsView): # Combine the scene transform with the view transform. view_transform = view.transform() transform = view_transform * view_transform lod = option.levelOfDetailFromTransform(transform) w, h = self.__iconSize.width(), self.__iconSize.height() target = QRectF(0, 0, w, h) source = QRectF(0, 0, w * lod, w * lod).toRect() # The actual size of the requested pixmap can be smaller. size = self.__icon.actualSize(source.size(), mode=mode) source.setSize(size) pixmap = self.__icon.pixmap(source.size(), mode=mode) painter.setRenderHint( QPainter.SmoothPixmapTransform, self.__transformationMode == Qt.SmoothTransformation ) painter.drawPixmap(target, pixmap, QRectF(source))
def legend_anchor_pos(legend): """ Return the legend's anchor positions relative to it's parent (if defined). Return `None` if legend does not have a parent or the parent's size is empty. .. seealso:: LegendItem.anchor, rect_anchor_pos """ parent = legend.parentItem() if parent is None or parent.size().isEmpty(): return None rect = legend.geometry() # in parent coordinates. parent_rect = QRectF(QPointF(0, 0), parent.size()) # Find the closest corner of rect to parent rect c1, _, *parentPos = rect_anchor_pos(rect, parent_rect) return corner_anchor(c1), tuple(parentPos)
def sharpen_region_recur(node, region, nbins, depth, gridbin_func): if depth <= 1: return node elif not QRectF(*node.brect).intersects(region): return node elif node.is_empty: return node elif node.is_leaf: xs, xe, ys, ye = bindices(node, region) # indices in need of update indices = Node_nonzero(node) for i, j in zip(*indices): if xs <= i < xe and ys <= j < ye: node = sharpen_node_cell(node, i, j, nbins, gridbin_func) # if the exposed region is empty the node.is_leaf property # is preserved if node.is_leaf: return node return sharpen_region_recur(node, region, nbins, depth, gridbin_func) else: xs, xe, ys, ye = bindices(node, region) # indices is need of update indices1 = Node_nonzero(node) indices2 = node.children.nonzero() indices = sorted(set(list(zip(*indices1))) - set(list(zip(*indices2)))) for i, j in indices: if xs <= i < xe and ys <= j < ye: node = sharpen_node_cell(node, i, j, nbins, gridbin_func) children = np.array(node.children, dtype=object) children[xs: xe, ys: ye] = [ [sharpen_region_recur(ch, region, nbins, depth - 1, gridbin_func) if ch is not None else None for ch in row] for row in np.array(children[xs: xe, ys: ye]) ] return node._replace(children=children)