def __init__(self, palette, parent, orientation): super().__init__(parent) self.__gradient = QLinearGradient() num_colors = len(palette) for idx, stop in enumerate(palette): self.__gradient.setColorAt(idx * (1. / (num_colors - 1)), stop) # We need to tell the gradient where it's start and stop points are self.__gradient.setStart(QPointF(0, 0)) if orientation == Qt.Vertical: final_stop = QPointF(0, self.GRADIENT_HEIGHT) else: final_stop = QPointF(self.GRADIENT_HEIGHT, 0) self.__gradient.setFinalStop(final_stop) # Get the appropriate rectangle dimensions based on orientation if orientation == Qt.Vertical: width, height = self.GRADIENT_WIDTH, self.GRADIENT_HEIGHT elif orientation == Qt.Horizontal: width, height = self.GRADIENT_HEIGHT, self.GRADIENT_WIDTH self.__rect_item = QGraphicsRectItem(0, 0, width, height, self) self.__rect_item.setPen(QPen(QColor(0, 0, 0, 0))) self.__rect_item.setBrush(QBrush(self.__gradient)) self._size_hint = QSizeF(self.__rect_item.boundingRect().size())
def draw_attribute(self, y, atr_name, atr_val, atr_contrib, error): fix = (self.offset_left + self.atr_area_w) """vertical line where x = 0""" self.scene.addLine(0 + fix, y, 0 + fix, y + self.rect_height, self.black_pen) """borders""" self.scene.addLine(self.offset_left, y, fix + self.atr_area_w, y, self.gray_pen) self.scene.addLine(self.offset_left, y + self.rect_height, fix + self.atr_area_w, y + self.rect_height, self.gray_pen) if atr_name is not None and atr_val is not None and atr_contrib is not None: atr_contrib_x = atr_contrib * self.scale + fix error_x = error * self.scale padded_rect = self.rect_height - 2 * self.offset_y len_rec = 2 * error_x graphed_rect = QGraphicsRectItem( atr_contrib_x - error_x, y + self.offset_y, len_rec, padded_rect) graphed_rect.setBrush(self.brush) graphed_rect.setPen(QPen(Qt.NoPen)) self.scene.addItem(graphed_rect) """vertical line marks calculated contribution of attribute""" self.atr_line = self.scene.addLine(atr_contrib_x, y + self.offset_y + 2, atr_contrib_x, y + self.rect_height - self.offset_y - 2, self.blue_pen) """atr name and value on the left""" self.place_left(QGraphicsSimpleTextItem( atr_val, None), y + self.rect_height/2) self.place_left_edge(QGraphicsSimpleTextItem( atr_name, None), y + self.rect_height/2) """atr score on the right""" self.place_right(self.format_marking( atr_contrib), y + self.rect_height/2)
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 _create_drag_tooltip(self, scene): tip_parts = [ (Qt.ShiftModifier, "Shift: Add group"), (Qt.ShiftModifier + Qt.ControlModifier, "Shift-{}: Append to group". format("Cmd" if sys.platform == "darwin" else "Ctrl")), (Qt.AltModifier, "Alt: Remove") ] all_parts = ", ".join(part for _, part in tip_parts) self.tiptexts = { int(modifier): all_parts.replace(part, "<b>{}</b>".format(part)) for modifier, part in tip_parts } self.tiptexts[0] = all_parts self.tip_textitem = text = QGraphicsTextItem() # Set to the longest text text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier]) text.setPos(4, 2) r = text.boundingRect() rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4) rect.setBrush(QColor(224, 224, 224, 212)) rect.setPen(QPen(Qt.NoPen)) self.update_tooltip() scene.drag_tooltip = scene.createItemGroup([rect, text]) scene.drag_tooltip.hide()
def __init__(self, color, parent): super().__init__(parent) height, width = self.SIZE.height(), self.SIZE.width() self.__square = QGraphicsRectItem(0, 0, height, width) self.__square.setBrush(QBrush(color)) self.__square.setPen(QPen(QColor(0, 0, 0, 0))) self.__square.setParentItem(self)
def __init__(self, anchor, parent=None): QGraphicsRectItem.__init__(self, parent=parent) self.setAcceptHoverEvents(True) self.anchor = anchor self.setRect(anchor.boundingRect()) self.setPos(self.mapFromScene(anchor.scenePos())) self.setFlag(QGraphicsItem.ItemHasNoContents, True)
def __init__(self, text, parent): QGraphicsObject.__init__(self, parent) self.text_item = QGraphicsTextItem(text + ':', self) f = self.text_item.font() f.setBold(True) self.text_item.setFont(f) self.rect_item = QGraphicsRectItem(self.text_item.boundingRect(), self) self.rect_item.setPen(QPen(Qt.NoPen)) self.rect_item.stackBefore(self.text_item)
def __init__(self, name, values, scale, name_offset, offset, labels=None): super().__init__() # leading label font = name.document().defaultFont() if self.bold_label: font.setWeight(QFont.Bold) name.setFont(font) name.setPos(name_offset, -10) name.setParentItem(self) # prediction marker self.dot = self.DOT_ITEM_CLS(self.DOT_RADIUS, scale, offset, values[0], values[-1]) self.dot.setParentItem(self) # pylint: disable=unused-variable # line line = QGraphicsLineItem(min(values) * scale + offset, 0, max(values) * scale + offset, 0, self) if labels is None: labels = [str(abs(v) if v == -0 else v) for v in values] old_x_tick = None shown_items = [] w = QGraphicsSimpleTextItem(labels[0]).boundingRect().width() text_finish = values[0] * scale - w + offset - 10 for i, (label, value) in enumerate(zip(labels, values)): text = QGraphicsSimpleTextItem(label) x_text = value * scale - text.boundingRect().width() / 2 + offset if text_finish > x_text - 10: y_text, y_tick = self.DOT_RADIUS * 0.7, 0 text_finish = values[0] * scale + offset else: y_text = - text.boundingRect().height() - self.DOT_RADIUS * 0.7 y_tick = - self.tick_height text_finish = x_text + text.boundingRect().width() text.setPos(x_text, y_text) if not collides(text, shown_items): text.setParentItem(self) shown_items.append(text) x_tick = value * scale - self.tick_width / 2 + offset tick = QGraphicsRectItem( x_tick, y_tick, self.tick_width, self.tick_height, self) tick.setBrush(QColor(Qt.black)) if self.half_tick_height and i: x = x_tick - (x_tick - old_x_tick) / 2 half_tick = QGraphicsLineItem(x, - self.half_tick_height, x, 0, self) old_x_tick = x_tick
def strudel(self, dist): attr = self.attribute ss = np.sum(dist) box = QGraphicsItemGroup() if ss < 1e-6: QGraphicsRectItem(0, -10, 1, 10, box) cum = 0 for i, v in enumerate(dist): if v < 1e-6: continue if self.stretched: v /= ss v *= self.scale_x rect = QGraphicsRectItem(cum + 1, -6, v - 2, 12, box) rect.setBrush(QBrush(QColor(*attr.colors[i]))) rect.setPen(QPen(Qt.NoPen)) if self.stretched: tooltip = "{}: {:.2f}%".format(attr.values[i], 100 * dist[i] / sum(dist)) else: tooltip = "{}: {}".format(attr.values[i], int(dist[i])) rect.setToolTip(tooltip) text = QGraphicsTextItem(attr.values[i]) box.addToGroup(text) cum += v return box
def __init__(self, width, height, color, parent=None): super().__init__(parent=parent) self.width = width self.height = height self.color = color if not isinstance(self.color, QColor): self.color = QColor(self.color) self.__rect = QGraphicsRectItem(0, 0, self.width, self.height, self) self.__rect.setPen(QPen(Qt.NoPen)) self.__rect.setBrush(QBrush(self.color))
class LegendGradient(QGraphicsWidget): """Gradient widget. A gradient square bar that can be used to display continuous values. Parameters ---------- palette : iterable[QColor] parent : QGraphicsWidget orientation : Qt.Orientation Notes ----- .. note:: While the gradient does support any number of colors, any more than 3 is not very readable. This should not be a problem, since Orange only implements 2 or 3 colors. """ # Default sizes (assume gradient is vertical by default) GRADIENT_WIDTH = 20 GRADIENT_HEIGHT = 150 _size_hint = QSizeF(GRADIENT_WIDTH, GRADIENT_HEIGHT) def __init__(self, palette, parent, orientation): super().__init__(parent) self.__gradient = QLinearGradient() num_colors = len(palette) for idx, stop in enumerate(palette): self.__gradient.setColorAt(idx * (1. / (num_colors - 1)), stop) # We need to tell the gradient where it's start and stop points are self.__gradient.setStart(QPointF(0, 0)) if orientation == Qt.Vertical: final_stop = QPointF(0, self.GRADIENT_HEIGHT) else: final_stop = QPointF(self.GRADIENT_HEIGHT, 0) self.__gradient.setFinalStop(final_stop) # Get the appropriate rectangle dimensions based on orientation if orientation == Qt.Vertical: width, height = self.GRADIENT_WIDTH, self.GRADIENT_HEIGHT elif orientation == Qt.Horizontal: width, height = self.GRADIENT_HEIGHT, self.GRADIENT_WIDTH self.__rect_item = QGraphicsRectItem(0, 0, width, height, self) self.__rect_item.setPen(QPen(QColor(0, 0, 0, 0))) self.__rect_item.setBrush(QBrush(self.__gradient)) self._size_hint = QSizeF(self.__rect_item.boundingRect().size()) def sizeHint(self, size_hint, size_constraint=None, *args, **kwargs): return self._size_hint
def __update(self): self.__clear() pen = self.pen() brush = self.brush() for _ in range(self.count()): item = QGraphicsRectItem(self) item.setPen(pen) item.setBrush(brush) self.__items.append(item) self.__layout()
def updateSelectionRect(self, event): pos = event.scenePos() buttonDownPos = event.buttonDownScenePos(Qt.LeftButton) rect = QRectF(pos, buttonDownPos).normalized() rect = rect.intersected(self.sceneRect()) if not self.selectionRect: self.selectionRect = QGraphicsRectItem() self.selectionRect.setBrush(QColor(10, 10, 10, 20)) self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200))) self.addItem(self.selectionRect) self.selectionRect.setRect(rect) self.selectionRectPointChanged.emit(pos)
def __init__(self): GraphicsWidget.__init__(self) self.width_bar = 15 self.colors = None self.gradient = QLinearGradient() self.setMaximumHeight(2**16) self.setMinimumWidth(self.width_bar) self.setMaximumWidth(self.width_bar) self.rect = QGraphicsRectItem(QRectF(0, 0, self.width_bar, 100), self) self.axis = pg.AxisItem('right', parent=self) self.axis.setX(self.width_bar) self.axis.geometryChanged.connect(self._update_width) self.adapt_to_size() self._initialized = True
def show_selection(self): self.plot_mark.clear() if not self.is_valid: # though if it's not, selection is empty anyway return blue = QColor(Qt.blue) pen = QPen(QBrush(blue), 3) pen.setCosmetic(True) brush = QBrush(blue.lighter(190)) for group in self.grouped_selection(): group = list(group) left_idx, right_idx = group[0], group[-1] left_pad, right_pad = self._determine_padding(left_idx, right_idx) x0 = self.bar_items[left_idx].x0 - left_pad x1 = self.bar_items[right_idx].x1 + right_pad item = QGraphicsRectItem(x0, 0, x1 - x0, 1) item.setPen(pen) item.setBrush(brush) if self.var.is_continuous: valname = self.str_int( x0, x1, not left_idx, right_idx == len(self.bar_items) - 1) inside = sum(np.sum(self.bar_items[i].freqs) for i in group) total = len(self.valid_data) item.setToolTip( "<p style='white-space:pre;'>" f"<b>{escape(valname)}</b>: " f"{inside} ({100 * inside / total:.2f} %)") self.plot_mark.addItem(item)
def box_group(self, stat, height=20): def line(x0, y0, x1, y1, *args): return QGraphicsLineItem(x0 * scale_x, y0, x1 * scale_x, y1, *args) scale_x = self.scale_x box = QGraphicsItemGroup() whisker1 = line(stat.a_min, -1.5, stat.a_min, 1.5, box) whisker2 = line(stat.a_max, -1.5, stat.a_max, 1.5, box) vert_line = line(stat.a_min, 0, stat.a_max, 0, box) mean_line = line(stat.mean, -height / 3, stat.mean, height / 3, box) for it in (whisker1, whisker2, mean_line): it.setPen(self._pen_paramet) vert_line.setPen(self._pen_dotted) var_line = line(stat.mean - stat.dev, 0, stat.mean + stat.dev, 0, box) var_line.setPen(self._pen_paramet) if stat.q25 is not None and stat.q75 is not None: mbox = QGraphicsRectItem(stat.q25 * scale_x, -height / 2, (stat.q75 - stat.q25) * scale_x, height, box) mbox.setBrush(self._box_brush) mbox.setPen(QPen(Qt.NoPen)) mbox.setZValue(-200) if stat.median is not None: median_line = line(stat.median, -height / 2, stat.median, height / 2, box) median_line.setPen(self._pen_median) median_line.setZValue(-150) return box
def set_data(self, value): self._x_data = value item = QGraphicsRectItem() item.setX(0) item.setY(self._height / 2 - self._height * 0.5 / 2) width = value * self._width / (self._range[1] - self._range[0]) item.setRect(0, 0, width, self._height * 0.5) self._group.addToGroup(item)
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 test_other_exporter(self): sc = QGraphicsScene() sc.addItem(QGraphicsRectItem(0, 0, 3, 3)) with patch("orangewidget.io.ImgFormat._get_exporter", Mock()) as mfn: with self.assertRaises(Exception): imgio.ImgFormat.write("", sc) self.assertEqual(0, mfn.call_count)
def addSquare(self, size): size = np.clip(1.3**np.log2(size**.5), 8, 20) item = QGraphicsRectItem(self) offset = len(self.childItems()) item.setRect(offset * 3, offset * 2, size, size) item.setPen(QColor('maroon')) item.setBrush(QColor('pink')) self.selected(False) self.addToGroup(item)
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)
class LegendItemSquare(ColorIndicator): """Legend square item. The legend square item is a small colored square image that can be plugged into the legend in front of the text object. This should only really be used in conjunction with ˙LegendItem˙. Parameters ---------- color : QColor The color of the square. parent : QGraphicsItem See Also -------- LegendItemCircle """ SIZE = QSizeF(12, 12) _size_hint = SIZE def __init__(self, color, parent): super().__init__(parent) height, width = self.SIZE.height(), self.SIZE.width() self.__square = QGraphicsRectItem(0, 0, height, width) self.__square.setBrush(QBrush(color)) self.__square.setPen(QPen(QColor(0, 0, 0, 0))) self.__square.setParentItem(self) self._size_hint = QSizeF(self.__square.boundingRect().size()) def sizeHint(self, size_hint, size_constraint=None, *args, **kwargs): return self._size_hint
def box_group(self, stat, height=20): def line(x0, y0, x1, y1, *args): return QGraphicsLineItem(x0 * scale_x, y0, x1 * scale_x, y1, *args) scale_x = self.scale_x box = QGraphicsItemGroup() whisker1 = line(stat.a_min, -1.5, stat.a_min, 1.5, box) whisker2 = line(stat.a_max, -1.5, stat.a_max, 1.5, box) vert_line = line(stat.a_min, 0, stat.a_max, 0, box) mean_line = line(stat.mean, -height / 3, stat.mean, height / 3, box) for it in (whisker1, whisker2, mean_line): it.setPen(self._pen_paramet) vert_line.setPen(self._pen_dotted) var_line = line(stat.mean - stat.dev, 0, stat.mean + stat.dev, 0, box) var_line.setPen(self._pen_paramet) mbox = QGraphicsRectItem(stat.q25 * scale_x, -height / 2, (stat.q75 - stat.q25) * scale_x, height, box) mbox.setBrush(self._box_brush) mbox.setPen(QPen(Qt.NoPen)) mbox.setZValue(-200) median_line = line(stat.median, -height / 2, stat.median, height / 2, box) median_line.setPen(self._pen_median) median_line.setZValue(-150) return box
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 test_pdf(self): sc = QGraphicsScene() sc.addItem(QGraphicsRectItem(0, 0, 20, 20)) fd, fname = tempfile.mkstemp() os.close(fd) try: imgio.PdfFormat.write_image(fname, sc) finally: os.unlink(fname)
def __init__(self, parent): super().__init__(parent) self.__range = None # type: Tuple[float] self.__value_range = None # type: Tuple[float] self.__model_output = None # type: float self.__base_value = None # type: float self.__group = QGraphicsItemGroup(self) low_color, high_color = QColor(*RGB_LOW), QColor(*RGB_HIGH) self.__low_item = QGraphicsRectItem() self.__low_item.setPen(QPen(low_color)) self.__low_item.setBrush(QBrush(low_color)) self.__high_item = QGraphicsRectItem() self.__high_item.setPen(QPen(high_color)) self.__high_item.setBrush(QBrush(high_color)) self.__low_cover_item = LowCoverItem() self.__high_cover_item = HighCoverItem() pen = QPen(IndicatorItem.COLOR) pen.setStyle(Qt.DashLine) pen.setWidth(1) self.__model_output_line = QGraphicsLineItem() self.__model_output_line.setPen(pen) self.__base_value_line = QGraphicsLineItem() self.__base_value_line.setPen(pen) self.__model_output_ind = IndicatorItem("Model prediction: {}") self.__base_value_ind = IndicatorItem("Base value: {}\nThe average " "prediction for selected class.") self.__group.addToGroup(self.__low_item) self.__group.addToGroup(self.__high_item) self.__group.addToGroup(self.__low_cover_item) self.__group.addToGroup(self.__high_cover_item) self.__group.addToGroup(self.__model_output_line) self.__group.addToGroup(self.__base_value_line) self.__group.addToGroup(self.__model_output_ind) self.__group.addToGroup(self.__base_value_ind) self.__low_parts = [] # type: List[LowPartItem] self.__high_parts = [] # type: List[HighPartItem]
class OWLegendTitle(QGraphicsObject): """ A legend item that shows ``text`` with a bold font and no symbol. """ def __init__(self, text, parent): QGraphicsObject.__init__(self, parent) self.text_item = QGraphicsTextItem(text + ':', self) f = self.text_item.font() f.setBold(True) self.text_item.setFont(f) self.rect_item = QGraphicsRectItem(self.text_item.boundingRect(), self) self.rect_item.setPen(QPen(Qt.NoPen)) self.rect_item.stackBefore(self.text_item) def boundingRect(self): return self.text_item.boundingRect() def paint(self, painter, option, widget): pass
def updateSelectionRect(self, event): pos = event.scenePos() buttonDownPos = event.buttonDownScenePos(Qt.LeftButton) rect = QRectF(pos, buttonDownPos).normalized() rect = rect.intersected(self.sceneRect()) if not self.selectionRect: self.selectionRect = QGraphicsRectItem() self.selectionRect.setBrush(QColor(10, 10, 10, 20)) self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200))) self.addItem(self.selectionRect) self.selectionRect.setRect(rect) if event.modifiers() & Qt.ControlModifier or \ event.modifiers() & Qt.ShiftModifier: path = self.selectionArea() else: path = QPainterPath() path.addRect(rect) self.setSelectionArea(path) self.selectionRectPointChanged.emit(pos)
def addSquare(self, size): size = np.clip(1.3**np.log2(size**.5), 8, 20) item = QGraphicsRectItem(self) offset = len(self.childItems()) item.setRect(offset*3, offset*2, size, size) item.setPen(QColor('maroon')) item.setBrush(QColor('pink')) self.selected(False) self.addToGroup(item)
def test_other(self): fd, fname = tempfile.mkstemp('.pdf') os.close(fd) sc = QGraphicsScene() sc.addItem(QGraphicsRectItem(0, 0, 3, 3)) try: imgio.PdfFormat.write(fname, sc) with open(fname, "rb") as f: self.assertTrue(f.read().startswith(b'%PDF')) finally: os.unlink(fname)
def mouseMoveEvent(self, event): # Reimplemented if event.buttons() & Qt.LeftButton: assert self.__selstate is not None if self.__selectionRect is None: self.__selectionRect = 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 test_other(self): fd, fname = tempfile.mkstemp('.png') os.close(fd) sc = QGraphicsScene() sc.addItem(QGraphicsRectItem(0, 0, 3, 3)) try: imgio.PngFormat.write(fname, sc) im = QImage(fname) # writer adds 15*2 of empty space self.assertEqual((30+4, 30+4), (im.width(), im.height())) finally: os.unlink(fname)
def updateSelectionArea(self): mask = self.selectionMask() brush = self._stylebrush[mask.astype(int)] self._item.setBrush(brush) if self._selitem is not None: self.removeItem(self._selitem) self._selitem = None if self.__selectiondelegate is not None: self._selitem = QGraphicsItemGroup() self._selitem.dataBounds = \ lambda axis, frac=1.0, orthoRange=None: None for p1, p2 in self.__selectiondelegate.selection: r = QRectF(p1, p2).normalized() ritem = QGraphicsRectItem(r, self._selitem) ritem.setBrush(QBrush(Qt.NoBrush)) ritem.setPen(QPen(Qt.red, 0)) self.addItem(self._selitem)
def _create_drag_tooltip(self, scene): tip_parts = [(Qt.ShiftModifier, "Shift: Add group"), (Qt.ShiftModifier + Qt.ControlModifier, "Shift-{}: Append to group".format( "Cmd" if sys.platform == "darwin" else "Ctrl")), (Qt.AltModifier, "Alt: Remove")] all_parts = ", ".join(part for _, part in tip_parts) self.tiptexts = { int(modifier): all_parts.replace(part, "<b>{}</b>".format(part)) for modifier, part in tip_parts } self.tiptexts[0] = all_parts self.tip_textitem = text = QGraphicsTextItem() # Set to the longest text text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier]) text.setPos(4, 2) r = text.boundingRect() rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4) rect.setBrush(QColor(224, 224, 224, 212)) rect.setPen(QPen(Qt.NoPen)) self.update_tooltip(Qt.NoModifier) scene.drag_tooltip = scene.createItemGroup([rect, text]) scene.drag_tooltip.hide()
class BarItem(QGraphicsWidget): """A single bar in a histogram representing one single target value.""" def __init__(self, width, height, color, parent=None): super().__init__(parent=parent) self.width = width self.height = height self.color = color if not isinstance(self.color, QColor): self.color = QColor(self.color) self.__rect = QGraphicsRectItem(0, 0, self.width, self.height, self) self.__rect.setPen(QPen(Qt.NoPen)) self.__rect.setBrush(QBrush(self.color)) def boundingRect(self): return self.__rect.boundingRect() def sizeHint(self, which, constraint): return self.boundingRect().size() def sizePolicy(self): return QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
def __init__(self, name, point, parent): QGraphicsObject.__init__(self, parent) self.text_item = QGraphicsTextItem(name, self) if point: s = point.size() height = max(2 * s, self.text_item.boundingRect().height()) else: height = self.text_item.boundingRect().height() p = 0.5 * height self.text_item.setPos(height, 0) self.point_item = point if point: self.point_item.setParentItem(self) self.point_item.setPos(p, p) self._rect = QRectF(0, 0, height + self.text_item.boundingRect().width(), height) self.rect_item = QGraphicsRectItem(self._rect, self) self.rect_item.setPen(QPen(Qt.NoPen)) self.rect_item.stackBefore(self.text_item) if self.point_item: self.rect_item.stackBefore(self.point_item)
def test_controlpointrect(self): control = ControlPointRect() rect = QGraphicsRectItem(QRectF(10, 10, 100, 200)) self.scene.addItem(rect) self.scene.addItem(control) control.setRect(rect.rect()) control.setFocus() control.rectChanged.connect(rect.setRect) control.setRect(QRectF(20, 20, 100, 200)) self.assertEqual(control.rect(), rect.rect()) self.assertEqual(control.rect(), QRectF(20, 20, 100, 200)) control.setControlMargins(5) self.assertEqual(control.controlMargins(), QMargins(5, 5, 5, 5)) control.rectEdited.connect(rect.setRect) self.view.show() self.app.exec_() self.assertEqual(rect.rect(), control.rect())
def __init__(self, parent=None, channel=None, rect=None, **kwargs): QGraphicsRectItem.__init__(self, **kwargs) self.setAcceptedMouseButtons(Qt.NoButton) self.__channel = None # AnchorHover handles hover events # self.setAcceptHoverEvents(True) if rect is None: rect = QRectF(0, 0, 20, 20) self.setRect(rect) if channel: self.setChannel(channel) self.__default_pen = QPen(QColor('#000000'), 1) self.__hover_pen = QPen(QColor('#000000'), 2) self.setPen(self.__default_pen) self.enabledBrush = QColor('#FFFFFF') self.disabledBrush = QColor('#BBBBBB') self.setBrush(self.enabledBrush)
class GraphicsScene(QGraphicsScene): selectionRectPointChanged = Signal(QPointF) # override the default signal since it should only be emitted when a selection is finished selectionChanged = Signal(set, int) def __init__(self, *args): QGraphicsScene.__init__(self, *args) self.selectionRect = None # TODO figure out how to keep items highlighted and prevent redrawing during selection without disabling this method def mousePressEvent(self, event): QGraphicsScene.mousePressEvent(self, event) def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: screenPos = event.screenPos() buttonDown = event.buttonDownScreenPos(Qt.LeftButton) if (screenPos - buttonDown).manhattanLength() > 2.0: self.updateSelectionRect(event) QGraphicsScene.mouseMoveEvent(self, event) def mouseReleaseEvent(self, event): QGraphicsScene.mouseReleaseEvent(self, event) if event.button() == Qt.LeftButton: modifiers = event.modifiers() path = QPainterPath() # the mouse was moved if self.selectionRect: path.addRect(self.selectionRect.rect()) self.removeItem(self.selectionRect) self.selectionRect = None # the mouse was only clicked - create a selection area of 1x1 size else: rect = QRectF(event.buttonDownScenePos(Qt.LeftButton), QSizeF(1., 1.)).intersected(self.sceneRect()) path.addRect(rect) self.setSelectionArea(path) self.selectionChanged.emit(set(self.selectedItems()), modifiers) def updateSelectionRect(self, event): pos = event.scenePos() buttonDownPos = event.buttonDownScenePos(Qt.LeftButton) rect = QRectF(pos, buttonDownPos).normalized() rect = rect.intersected(self.sceneRect()) if not self.selectionRect: self.selectionRect = QGraphicsRectItem() self.selectionRect.setBrush(QColor(10, 10, 10, 20)) self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200))) self.addItem(self.selectionRect) self.selectionRect.setRect(rect) self.selectionRectPointChanged.emit(pos)
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 __init__(self, name, point, parent): QGraphicsObject.__init__(self, parent) self.text_item = QGraphicsTextItem(name, self) if point: s = point.size() height = max(2*s, self.text_item.boundingRect().height()) else: height = self.text_item.boundingRect().height() p = 0.5 * height self.text_item.setPos(height, 0) self.point_item = point if point: self.point_item.setParentItem(self) self.point_item.setPos(p, p) self._rect = QRectF(0, 0, height + self.text_item.boundingRect().width(), height ) self.rect_item = QGraphicsRectItem(self._rect, self) self.rect_item.setPen(QPen(Qt.NoPen)) self.rect_item.stackBefore(self.text_item) if self.point_item: self.rect_item.stackBefore(self.point_item)
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
class RectangleCurve(OWCurve): """ A plot item that shows a rectangle. This class accepts the same options as :obj:`.PolygonCurve`. The rectangle is calculated as the smallest rectangle that contains all points in ``xData`` and ``yData``. """ def __init__(self, pen = QPen(Qt.black), brush = QBrush(Qt.white), xData = None, yData = None, tooltip = None): OWCurve.__init__(self, xData, yData, tooltip=tooltip) self.set_pen(pen) self.set_brush(brush) self._item = QGraphicsRectItem(self) def update_properties(self): self._item.setRect(self.graph_transform().mapRect(self.data_rect())) self._item.setPen(self.pen()) self._item.setBrush(self.brush())
class GraphicsScene(QGraphicsScene): selectionRectPointChanged = Signal(QPointF) def __init__(self, *args): QGraphicsScene.__init__(self, *args) self.selectionRect = None def mousePressEvent(self, event): QGraphicsScene.mousePressEvent(self, event) def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: screenPos = event.screenPos() buttonDown = event.buttonDownScreenPos(Qt.LeftButton) if (screenPos - buttonDown).manhattanLength() > 2.0: self.updateSelectionRect(event) QGraphicsScene.mouseMoveEvent(self, event) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: if self.selectionRect: self.removeItem(self.selectionRect) self.selectionRect = None QGraphicsScene.mouseReleaseEvent(self, event) def updateSelectionRect(self, event): pos = event.scenePos() buttonDownPos = event.buttonDownScenePos(Qt.LeftButton) rect = QRectF(pos, buttonDownPos).normalized() rect = rect.intersected(self.sceneRect()) if not self.selectionRect: self.selectionRect = QGraphicsRectItem() self.selectionRect.setBrush(QColor(10, 10, 10, 20)) self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200))) self.addItem(self.selectionRect) self.selectionRect.setRect(rect) if event.modifiers() & Qt.ControlModifier or \ event.modifiers() & Qt.ShiftModifier: path = self.selectionArea() else: path = QPainterPath() path.addRect(rect) self.setSelectionArea(path) self.selectionRectPointChanged.emit(pos)