def __init__(self, node_id): super().__init__() self.setZValue(2) self.setAcceptHoverEvents(True) self.setFlag(QGraphicsItem.ItemIsMovable) # 可以移动 self.setFlag(QGraphicsItem.ItemSendsGeometryChanges) self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) # 面向UINet 负责增添逻辑操作 self.node_id = node_id self.hover = False self.cached_size = None self.bounding_rect = QRectF() # XXX 在重绘时会被更新,重绘前可能会节点可能会被覆盖显示 # self.call_backs = CallTable() self.text_item = QGraphicsSimpleTextItem(self) self.text_item.setZValue(3) # 面向图形界面, 负责控制显示效果 self.style = { 'name': f' {node_id}', 'color': Qt.white, 'shape': 'Pie', # ('Pie', 'Rect', QPixmap) 'size': 0.5, # 0~1 的中间值 'text': '', 'text_color': Qt.black, 'show_text': False, }
def __init__(self, v_from: Vertex, v_to: Vertex, node: Vertex, oriented: bool, weight: int = 1, weighted: bool = True): super().__init__() self.v_from = v_from self.v_to = v_to self.node = node self.weighted = weighted self.weight = weight # self.pen = QPen(QBrush(QColor(0, 0, 0)), 3) if weighted: self.ellipse = QGraphicsEllipseItem(self.node.x - 8, self.node.y - 8, 16, 16) self.ellipse.setBrush(QBrush(QColor(0, 0, 0))) self.addToGroup(self.ellipse) text = QGraphicsSimpleTextItem(str(self.weight)) font = QFont() font.setPixelSize(8) text.setPen(QColor(255, 255, 255)) text.setFont(font) # настраиваем расположение текста if self.weight < 10: text.setPos(self.node.x - 16 / 6, self.node.y - 16 / 3) else: text.setPos(self.node.x - 4, self.node.y - 16 / 3) self.addToGroup(text) else: self.ellipse = QGraphicsEllipseItem(self.node.x - 4, self.node.y - 4, 8, 8) self.ellipse.setBrush(QBrush(QColor(0, 0, 0))) self.addToGroup(self.ellipse)
def __init__(self, model, manager, text_color=Qt.black): bg_color = model.get_bg_color() super(BasicNode, self).__init__() self.model = model text = model.get_display_text() self.manager = manager self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemIsFocusable, True) self.text_graph = QGraphicsSimpleTextItem(text) self.text_graph.setBrush(text_color) bound = self.text_graph.boundingRect() r = QPointF(bound.width() / 2, bound.height() / 2) text_center = self.text_graph.pos() + r self.text_graph.setPos(-text_center) self.addToGroup(self.text_graph) self.box_graph = BoxOutline(bg_color) empty_space = QPointF(UNIT, UNIT) newr = (empty_space + r) self.box_graph.rect = QRectF(-newr, newr) self.addToGroup(self.box_graph) self.text_graph.setZValue(1.0) self.box_graph.setZValue(0.0) self.children = []
def drawGrid(self): black_notes = [2,4,6,9,11] scale_bar = QGraphicsRectItem(0, 0, self.grid_width, self.note_height, self.piano) scale_bar.setPos(self.piano_width, 0) scale_bar.setBrush(QColor(100,100,100)) clearpen = QPen(QColor(0,0,0,0)) for i in range(self.end_octave - self.start_octave, self.start_octave - self.start_octave, -1): for j in range(self.notes_in_octave, 0, -1): scale_bar = QGraphicsRectItem(0, 0, self.grid_width, self.note_height, self.piano) scale_bar.setPos(self.piano_width, self.note_height * j + self.octave_height * (i - 1)) scale_bar.setPen(clearpen) if j not in black_notes: scale_bar.setBrush(QColor(120,120,120)) else: scale_bar.setBrush(QColor(100,100,100)) measure_pen = QPen(QColor(0, 0, 0, 120), 3) half_measure_pen = QPen(QColor(0, 0, 0, 40), 2) line_pen = QPen(QColor(0, 0, 0, 40)) for i in range(0, int(self.num_measures) + 1): measure = QGraphicsLineItem(0, 0, 0, self.piano_height + self.header_height - measure_pen.width(), self.header) measure.setPos(self.measure_width * i, 0.5 * measure_pen.width()) measure.setPen(measure_pen) if i < self.num_measures: number = QGraphicsSimpleTextItem('%d' % (i + 1), self.header) number.setPos(self.measure_width * i + 5, 2) number.setBrush(Qt.white) for j in self.frange(0, self.time_sig[0]*self.grid_div/self.time_sig[1], 1.): line = QGraphicsLineItem(0, 0, 0, self.piano_height, self.header) line.setZValue(1.0) line.setPos(self.measure_width * i + self.value_width * j, self.header_height) if j == self.time_sig[0]*self.grid_div/self.time_sig[1] / 2.0: line.setPen(half_measure_pen) else: line.setPen(line_pen)
def __createTexts(self): """ Private method to create the text items of the module item. """ if self.model is None: return boldFont = QFont(self.font) boldFont.setBold(True) classes = self.model.getClasses() x = self.margin + self.rect().x() y = self.margin + self.rect().y() self.header = QGraphicsSimpleTextItem(self) self.header.setFont(boldFont) self.header.setText(self.model.getName()) self.header.setPos(x, y) y += self.header.boundingRect().height() + self.margin if classes: txt = "\n".join(classes) else: txt = " " self.classes = QGraphicsSimpleTextItem(self) self.classes.setFont(self.font) self.classes.setText(txt) self.classes.setPos(x, y)
def __init__(self, qt_node, pin): super(SocketRow, self).__init__() assert qt_node is not None self.setParentItem(qt_node) self._parent_node = weakref.ref(qt_node) self._pin = pin self._spacerConstant = 5.0 self._label = QGraphicsSimpleTextItem(self) self._socket = None self._outputHook = None socket_colour = QColor(*pin.colour) socket_type = pin.shape if pin.io_type == "input": self._socket = QtSocket(self, "input", socket_type) self._socket.setColor(socket_colour) else: self._socket = QtSocket(self, "output", socket_type) self._socket.setColor(socket_colour) self.setLabelColor(self.defaultColor()) self.setLabelText(self._pin.name) self._socket.setVisible(True)
def create_time_labels(self): """Create the time labels, but don't plot them yet. Notes ----- It's necessary to have the height of the time labels, so that we can adjust the main scene. Not very robust, because it uses seconds as integers. """ min_time = int(floor(min(self.data.axis['time'][0]))) max_time = int(ceil(max(self.data.axis['time'][0]))) n_time_labels = self.parent.value('n_time_labels') self.idx_time = [] self.time_pos = [] for one_time in linspace(min_time, max_time, n_time_labels): x_label = (self.data.start_time + timedelta(seconds=one_time)).strftime('%H:%M:%S') item = QGraphicsSimpleTextItem(x_label) item.setFlag(QGraphicsItem.ItemIgnoresTransformations) self.idx_time.append(item) self.time_pos.append(QPointF(one_time, len(self.idx_label) * self.parent.value('y_distance')))
def showCurrentPosition(): if hasattr(self, "qgstiCurrentX")==False: self.qgstiCurrentX=QGraphicsSimpleTextItem(self.chart()) self.qgstiCurrentY=QGraphicsSimpleTextItem(self.chart()) self.qgstiCurrentX.setPos(event.pos().x(), maxY-10) self.qgstiCurrentY.setPos(self.chart().size().width()-47, event.pos().y()) self.qgstiCurrentX.setText(str(epochms2dtaware(xVal).date())) self.qgstiCurrentY.setText(str(round(yVal,2)))
def add_letter(self, letter): """ Add small letter to blank tile """ self.txt = QGraphicsSimpleTextItem(letter, self.pixmap_item) self.txt.setFont(QFont("Arial", 14, QFont.DemiBold)) self.txt.setBrush(QBrush(Qt.darkRed)) wd, ht = self.txt.boundingRect().width(), self.txt.boundingRect( ).height() self.txt.setPos((Cons.WIDTH - wd) / 2, (Cons.HEIGHT - ht) / 2)
def __init__(self, parent=None): super().__init__(QGraphicsScene(), parent) self.m_tooltip = None self.m_callouts = [] self.setDragMode(QGraphicsView.NoDrag) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # chart self.m_chart = QChart() self.m_chart.setMinimumSize(640, 480) self.m_chart.setTitle( "Hover the line to show callout. Click the line to make it stay" ) self.m_chart.legend().hide() series = QLineSeries() series.append(1, 3) series.append(4, 5) series.append(5, 4.5) series.append(7, 1) series.append(11, 2) self.m_chart.addSeries(series) series2 = QSplineSeries() series2.append(1.6, 1.4) series2.append(2.4, 3.5) series2.append(3.7, 2.5) series2.append(7, 4) series2.append(10, 2) self.m_chart.addSeries(series2) self.m_chart.createDefaultAxes() self.m_chart.setAcceptHoverEvents(True) self.setRenderHint(QPainter.Antialiasing) self.scene().addItem(self.m_chart) self.m_coordX = QGraphicsSimpleTextItem(self.m_chart) self.m_coordX.setPos( self.m_chart.size().width() / 2 - 50, self.m_chart.size().height() ) self.m_coordX.setText("X: ") self.m_coordY = QGraphicsSimpleTextItem(self.m_chart) self.m_coordY.setPos( self.m_chart.size().width() / 2 + 50, self.m_chart.size().height() ) self.m_coordY.setText("Y: ") series.clicked.connect(self.keepCallout) series.hovered.connect(self.tooltip) series2.clicked.connect(self.keepCallout) series2.hovered.connect(self.tooltip) self.setMouseTracking(True)
def _updateLabel(self, isLeft): """ Called by updatePositionAndAppearance during init, or later by updateConnectivity. Updates drawing and position of the label. """ lbl = self._label if self._idx != None: if lbl == None: bw = _BASE_WIDTH num = self._partner_virtual_helix.number() tbr = _FM.tightBoundingRect(str(num)) half_label_h = tbr.height() / 2.0 half_label_w = tbr.width() / 2.0 # determine x and y positions labelX = bw / 2.0 - half_label_w if self._is_on_top: labelY = -0.25 * half_label_h - 0.5 - 0.5 * bw else: labelY = 2 * half_label_h + 0.5 + 0.5 * bw # adjust x for left vs right labelXoffset = 0.25 * bw if isLeft else -0.25 * bw labelX += labelXoffset # adjust x for numeral 1 if num == 1: labelX -= half_label_w / 2.0 # create text item lbl = QGraphicsSimpleTextItem(str(num), self) lbl.setPos(labelX, labelY) lbl.setBrush(_ENAB_BRUSH) lbl.setFont(_toHelixNumFont) self._label = lbl # end if lbl.setText(str(self._partner_virtual_helix.number()))
def create_scale(self): section_num = len(self.section_analyzer.section_list) section_distance = self.section_analyzer.section_distance total_distance = section_num * section_distance div = int(Math.integer_division(total_distance, 1.0)) print(total_distance) for i in range(div+1): x = self.graph_zero[0] + i * self.length_multiplier + self.line_extend y = self.graph_zero[1] scale_text = QGraphicsSimpleTextItem("%.2f" % float(i)) scale_text.setPos(x, y) self.addToGroup(scale_text) start_to_zero = self.graph_zero[1] - self.position[1] step = abs(start_to_zero) // 25 x = self.graph_zero[0] - 15 y = self.graph_zero[1] for i in range(int(step)-1): if i > 0: value = i * 25 / 100 scene_y = y - i * 25 text = QGraphicsSimpleTextItem("-%.2f" % value) text.setPos(x, scene_y) self.addToGroup(text) start_to_zero = self.position[1] + self.height - self.graph_zero[1] step = abs(start_to_zero) // 25 x = self.graph_zero[0] - 15 y = self.graph_zero[1] for i in range(int(step)-1): if i > 0: value = i * 25 / 100 scene_y = y + i * 25 text = QGraphicsSimpleTextItem("%.2f" % value) text.setPos(x, scene_y) self.addToGroup(text)
def __init__(self, x, y, width=STATION_WIDTH, height=STATION_HEIGHT, name=""): # 此处的初始化 xy 值是以 item coordinate 标记矩形的起始点(左上角) super().__init__(-width / 2, -height / 2, width, height) # 此处的 xy 值是以 scene coordinate 标记矩形,结合上面的初始化,标记点是矩形的几何中心 self.setPos(x, y) # 背景黑色 self.setBrush(black_brush) # icon(相对于父 item 的 xy 值) QGraphicsPixmapItem( QPixmap(RM_path("./source/station.png")).scaled( ICON_WIDTH, ICON_HEIGHT), self).setPos(-width / 2 + 8, -ICON_HEIGHT / 2) # name(相对于父 item 的 xy 值) name = QGraphicsSimpleTextItem(name, self) name.setBrush(white_brush) name.setFont(title_font) name.setPos(-width / 2 + 8 + ICON_WIDTH, -name.boundingRect().height() / 2)
def __init__(self): super().__init__() self.timer = Timer() self.timeout_handle = None self.qtimer = QTimer() self.qtimer.timeout.connect(self.my_update) self.label = QGraphicsSimpleTextItem("Stopwatch:", self.root) self.time = QGraphicsSimpleTextItem("00:00", self.root) self.seconds = QGraphicsSimpleTextItem("00'00", self.root)
def __init__(self, nx_node, center_pos, nx_pos, steps, steps_max, small): """ Create node in the graph scene :param tuple nx_node: Node info :param center_pos: The position of the center node :param nx_pos: Position of the nodes in the graph :param int steps: The steps from the center identity :param int steps_max: The steps max of the graph :param bool small: Small dots for big networks """ super().__init__(nx_node, nx_pos) self.steps = steps self.steps_max = steps_max self.highlighted = False self.status_sentry = False if small: self.setRect(0, 0, 10, 10) self.text_item = None else: # text inside ellipse self.text_item = QGraphicsSimpleTextItem(self) self.text_item.setText(self.text) # center ellipse around text self.setRect(0, 0, self.text_item.boundingRect().width() * 2, self.text_item.boundingRect().height() * 2) # center text in ellipse self.text_item.setPos(self.boundingRect().width() / 4.0, self.boundingRect().height() / 4.0) # set anchor to the center self.setTransform(QTransform().translate( -self.boundingRect().width() / 2.0, -self.boundingRect().height() / 2.0)) # cursor change on hover self.setAcceptHoverEvents(True) self.setZValue(1) # animation and moves self.timeline = None self.loading_timer = QTimer() self.loading_timer.timeout.connect(self.next_tick) self.loading_counter = 0 self._refresh_colors() self.setPos(center_pos) self.move_to(nx_pos)
def __init__(self, node, view): super(QtNode, self).__init__() self._spacingConstant = 5.0 self._roundness = 3 self._labelColor = QColor(255, 255, 255) self._label = QGraphicsSimpleTextItem(self) self._label.setBrush(self._labelColor) self._label.setText(node.name) self._selectedColor = QColor(255, 255, 255) self._shapePen = QPen(Qt.NoPen) self._shapePen.setColor(self._selectedColor) self._shapePen.setWidthF(1.5) self._brush = QBrush(QColor(*COLOUR_THEMES[node.node_type])) self._dropShadowEffect = QGraphicsDropShadowEffect() self.setGraphicsEffect(self._dropShadowEffect) self._dropShadowEffect.setOffset(0.0, 10.0) self._dropShadowEffect.setBlurRadius(8.0) self._dropShadowEffect.setColor(QColor(0, 0, 0, 50)) self.setFlag(QGraphicsItem.ItemIsMovable) self.setFlag(QGraphicsItem.ItemIsSelectable) self.setAcceptHoverEvents(True) self.setToolTip(node.tooltip) self._name = node.name self._node = node self._view = weakref.ref(view) self._busy = False self._socketRows = OrderedDict() # Build IO pin socket rows for pin_name in node.pin_order: if pin_name in node.inputs: pin = node.inputs[pin_name] else: pin = node.outputs[pin_name] socket_row = SocketRow(self, pin) self._socketRows[pin_name] = socket_row self.updateLayout()
class FloatingTextWidget(QGraphicsWidget): def __init__(self, parent=None, anchor="center"): QGraphicsWidget.__init__(self, parent) assert anchor in {"center", "corner"} self.anchor = anchor self._label = QGraphicsSimpleTextItem(self) self._label.setBrush(QColor(255, 255, 255)) # Add drop shadow self._dropShadowEffect = QGraphicsDropShadowEffect() self.setGraphicsEffect(self._dropShadowEffect) self._dropShadowEffect.setOffset(0.0, 10.0) self._dropShadowEffect.setBlurRadius(8.0) self._dropShadowEffect.setColor(QColor(0, 0, 0, 50)) self._spacingConstant = 5.0 def updateLayout(self): width = self._label.boundingRect().width() height = self._label.boundingRect().height() width = self._spacingConstant + width + self._spacingConstant height = self._spacingConstant + height + self._spacingConstant self._label.setPos(self._spacingConstant, self._spacingConstant) self.resize(width, height) self.update() def paint(self, painter, option, widget): shape = QPainterPath() shape.addRoundedRect(self.rect(), 1, 1) painter.setBrush(QBrush(QColor(0, 0, 0))) painter.drawPath(shape) # painter.setPen(self._pen) # painter.drawPath(self._path) def onUpdated(self, center_position, text): self._label.setText(text) self.updateLayout() rect = self.rect() x_pos = center_position.x() y_pos = center_position.y() if self.anchor == "center": x_pos -= rect.width() / 2 y_pos -= rect.height() / 2 else: y_pos -= rect.height() self.setPos(x_pos, y_pos)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # initialize 2D grid of cell data self.cells = { (i,j): Cell(val = CellType.empty) for i in range(Config.NUM_CELLS_X) for j in range(Config.NUM_CELLS_Y) } self.animations = dict() self.setItemIndexMethod(QGraphicsScene.NoIndex) self.draw_grid() self.init_start_goal() self.set_diagonal() self.repaint_cells() self.display_text = QGraphicsSimpleTextItem() self.display_text.setPos(5, self.height() - 60) self.display_text.setFont(QFont("Helvetica", 12, QFont.Bold))
def create_chan_labels(self): """Create the channel labels, but don't plot them yet. Notes ----- It's necessary to have the width of the labels, so that we can adjust the main scene. """ self.idx_label = [] for one_grp in self.parent.channels.groups: for one_label in one_grp['chan_to_plot']: item = QGraphicsSimpleTextItem(one_label) item.setBrush(QBrush(QColor(one_grp['color']))) item.setFlag(QGraphicsItem.ItemIgnoresTransformations) self.idx_label.append(item)
def __init__(self, g_data_item, w_data_item, parent=None, eval_gui=None, appending_ports=True): """Initializes GAction. :param g_data_item: Object which holds data describing graphical properties of this GAction. :param w_data_item: Object which holds data about action in workflow. :param parent: Action which holds this subaction: this GAction is inside parent GAction. """ super(GAction, self).__init__(parent) self._width = g_data_item.data(GActionData.WIDTH) self._height = g_data_item.data(GActionData.HEIGHT) self.in_ports = [] self.out_ports = [] self.eval_gui = eval_gui self._hide_name = False self.appending_ports = appending_ports self.setPos(QtCore.QPoint(g_data_item.data(GActionData.X), g_data_item.data(GActionData.Y))) self.setPen(QtGui.QPen(QtCore.Qt.black)) self.setBrush(QtCore.Qt.darkGray) self.setFlag(self.ItemIsMovable) self.setFlag(self.ItemIsSelectable) self.setFlag(self.ItemSendsGeometryChanges) self.setZValue(0.0) self.resize_handle_width = 6 self.type_name = QGraphicsSimpleTextItem(w_data_item.action_name, self) self.type_name.setPos(QtCore.QPoint(self.resize_handle_width, GPort.SIZE / 2)) self.type_name.setBrush(QtCore.Qt.white) self._name = EditableLabel(g_data_item.data(GActionData.NAME), self) self.background = GActionBackground(self) self.background.setZValue(1.0) self.setCacheMode(self.DeviceCoordinateCache) self.g_data_item = g_data_item self.w_data_item = w_data_item self.update_ports() self.level = 0 self.height = self.height self.width = self.width self.progress = 0
def createLabel(self) -> QGraphicsSimpleTextItem: """ Returns: the label item """ label = QGraphicsSimpleTextItem("%d" % (self._id_num)) label.setFont(_FONT) label.setZValue(styles.ZPATHHELIX) label.setParentItem(self) return label
class WotNode(BaseNode): def __init__(self, nx_node, pos): """ Create node in the graph scene :param tuple nx_node: Node info :param x_y: Position of the node """ super().__init__(nx_node, pos) # color around ellipse outline_color = QColor('grey') outline_style = Qt.SolidLine outline_width = 1 if self.status_wallet: outline_color = QColor('black') outline_width = 2 if not self.status_member: outline_color = QColor('red') outline_style = Qt.SolidLine self.setPen(QPen(outline_color, outline_width, outline_style)) # text inside ellipse self.text_item = QGraphicsSimpleTextItem(self) self.text_item.setText(self.text) text_color = QColor('grey') if self.status_wallet == NodeStatus.HIGHLIGHTED: text_color = QColor('black') self.text_item.setBrush(QBrush(text_color)) # center ellipse around text self.setRect( 0, 0, self.text_item.boundingRect().width() * 2, self.text_item.boundingRect().height() * 2 ) # set anchor to the center self.setTransform( QTransform().translate(-self.boundingRect().width() / 2.0, -self.boundingRect().height() / 2.0)) # center text in ellipse self.text_item.setPos(self.boundingRect().width() / 4.0, self.boundingRect().height() / 4.0) # create gradient inside the ellipse gradient = QRadialGradient(QPointF(0, self.boundingRect().height() / 4), self.boundingRect().width()) gradient.setColorAt(0, QColor('white')) gradient.setColorAt(1, QColor('darkgrey')) self.setBrush(QBrush(gradient)) # cursor change on hover self.setAcceptHoverEvents(True) self.setZValue(1)
class BasicNode(QGraphicsItemGroup): def __init__(self, model, manager, text_color=Qt.black): bg_color = model.get_bg_color() super(BasicNode, self).__init__() self.model = model text = model.get_display_text() self.manager = manager self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemIsFocusable, True) self.text_graph = QGraphicsSimpleTextItem(text) self.text_graph.setBrush(text_color) bound = self.text_graph.boundingRect() r = QPointF(bound.width() / 2, bound.height() / 2) text_center = self.text_graph.pos() + r self.text_graph.setPos(-text_center) self.addToGroup(self.text_graph) self.box_graph = BoxOutline(bg_color) empty_space = QPointF(UNIT, UNIT) newr = (empty_space + r) self.box_graph.rect = QRectF(-newr, newr) self.addToGroup(self.box_graph) self.text_graph.setZValue(1.0) self.box_graph.setZValue(0.0) self.children = [] def itemChange(self, change, value): if change == QGraphicsItem.ItemSelectedChange: self.manager.selection_changed(self, value) return value else: return super(BasicNode, self).itemChange(change, value) def get_width(self): return self.boundingRect().width() def set_left_pos(self, pos): pos += QPoint(self.get_width() / 2.0, 0) self.setPos(pos) def left_pos(self): return self.pos() - QPointF(self.get_width() / 2.0, 0) def center_pos(self): return self.pos() def right_pos(self): return self.pos() + QPointF(self.get_width() / 2.0, 0) """
def __init__(self, *args): super(ClearanceWidthGraph, self).__init__(*args) self.dimension_analysis = self.section_analyzer.dimension_analysis self.clearance_analysis = self.section_analyzer.clearance_analysis self.min_horizontal_clearance = self.dimension_analysis.min_horizontal_clearance self.graph_zero = [None, None] self.graph_end = [None, None] self.clearance_label = QGraphicsSimpleTextItem() self.addToGroup(self.clearance_label) self.clearance_label.setZValue(1.0) self.init_dimension()
def create_material_legend(self, *args): self.position = args[0], args[1] square_size = 20 material_list_key = sorted(self.material_dict) x_init = self.position[0] + self.left_margin y_init = self.position[1] + self.top_margin i = 0 for key in material_list_key: scene_y = y_init + i * (square_size + 5) material = self.material_dict[key] surface_colour = material.get_surface_colour() rect = QGraphicsRectItem(x_init, scene_y, square_size, square_size) pen = QPen() pen.setWidthF(0.5) rect.setPen(pen) BaseGraphic.set_rect_fill(self.visualization_mode, rect, surface_colour) self.graphic_items.append(rect) text = QGraphicsSimpleTextItem(key) text.setPos(x_init + square_size + 5, scene_y) self.graphic_items.append(text) i += 1
def __createTexts(self): """ Private method to create the text items of the class item. """ if self.model is None: return boldFont = QFont(self.font) boldFont.setBold(True) attrs = self.model.getAttributes() meths = self.model.getMethods() x = self.margin + self.rect().x() y = self.margin + self.rect().y() self.header = QGraphicsSimpleTextItem(self) self.header.setFont(boldFont) self.header.setText(self.model.getName()) self.header.setPos(x, y) y += self.header.boundingRect().height() + self.margin if not self.noAttrs and not self.external: if attrs: txt = "\n".join(attrs) else: txt = " " self.attrs = QGraphicsSimpleTextItem(self) self.attrs.setFont(self.font) self.attrs.setText(txt) self.attrs.setPos(x, y) y += self.attrs.boundingRect().height() + self.margin else: self.attrs = None if meths: txt = "\n".join(meths) else: txt = " " self.meths = QGraphicsSimpleTextItem(self) self.meths.setFont(self.font) self.meths.setText(txt) self.meths.setPos(x, y)
def makeCoords(self): """ draws Coordinates """ xLabels = "ABCDEFGHIKLMNOPQRSTUVWXYZ" yLabels = list(range(1, 26)) botGrid = [] leftGrid = [] # generate pixel coordinates grids for n in range(self.board.size): (xBot, yBot) = self.grid[self.board.size-1][n] yBot += self.baseWidth*0.4/self.baseRectRatio xBot -= self.baseWidth*0.1 botGrid.append((xBot, yBot)) (xLeft, yLeft) = self.grid[n][0] xLeft -= self.baseWidth*1.2 yLeft -= self.baseWidth*0.3/self.baseRectRatio leftGrid.append((xLeft, yLeft)) # generate Text items and add them to group self.coordGroup = QGraphicsItemGroup() for n in range(self.board.size): leftText = QGraphicsSimpleTextItem(str(yLabels[n])) leftText.setPos(*leftGrid[n]) self.coordGroup.addToGroup(leftText) bottomText = QGraphicsSimpleTextItem(xLabels[n]) bottomText.setPos(*botGrid[n]) self.coordGroup.addToGroup(bottomText) # draw coordinates and update visibility according to self.showCoords self.scene.addItem(self.coordGroup) self.updateCoords()
def create_distance_pointer(self): self.distance_pointer = QGraphicsLineItem() pen = QPen() pen.setWidthF(1.0) pen.setStyle(Qt.DashDotLine) color = Color.create_qcolor_from_rgb_tuple_f((1,0,0)) pen.setColor(color) self.distance_pointer.setPen(pen) self.distance_pointer.setZValue(1.0) self.addToGroup(self.distance_pointer) self.distance_label = QGraphicsSimpleTextItem() self.distance_label.setZValue(1.0) self.addToGroup(self.distance_label)
def drawPiano(self): piano_keys_width = self.piano_width - self.padding labels = ('B','Bb','A','Ab','G','Gb','F','E','Eb','D','Db','C') black_notes = (2,4,6,9,11) piano_label = QFont() piano_label.setPointSize(6) self.piano = QGraphicsRectItem(0, 0, piano_keys_width, self.piano_height) self.piano.setPos(0, self.header_height) self.addItem(self.piano) key = PianoKeyItem(piano_keys_width, self.note_height, self.piano) label = QGraphicsSimpleTextItem('C8', key) label.setPos(18, 1) label.setFont(piano_label) key.setBrush(QColor(255, 255, 255)) for i in range(self.end_octave - self.start_octave, self.start_octave - self.start_octave, -1): for j in range(self.notes_in_octave, 0, -1): if j in black_notes: key = PianoKeyItem(piano_keys_width/1.4, self.note_height, self.piano) key.setBrush(QColor(0, 0, 0)) key.setZValue(1.0) key.setPos(0, self.note_height * j + self.octave_height * (i - 1)) elif (j - 1) and (j + 1) in black_notes: key = PianoKeyItem(piano_keys_width, self.note_height * 2, self.piano) key.setBrush(QColor(255, 255, 255)) key.setPos(0, self.note_height * j + self.octave_height * (i - 1) - self.note_height/2.) elif (j - 1) in black_notes: key = PianoKeyItem(piano_keys_width, self.note_height * 3./2, self.piano) key.setBrush(QColor(255, 255, 255)) key.setPos(0, self.note_height * j + self.octave_height * (i - 1) - self.note_height/2.) elif (j + 1) in black_notes: key = PianoKeyItem(piano_keys_width, self.note_height * 3./2, self.piano) key.setBrush(QColor(255, 255, 255)) key.setPos(0, self.note_height * j + self.octave_height * (i - 1)) if j == 12: label = QGraphicsSimpleTextItem('{}{}'.format(labels[j - 1], self.end_octave - i), key ) label.setPos(18, 6) label.setFont(piano_label) self.piano_keys.append(key)
def createLabel(self): """Summary Returns: TYPE: Description """ label = QGraphicsSimpleTextItem("%d" % (self._id_num)) label.setFont(_FONT) label.setZValue(styles.ZPATHHELIX) label.setParentItem(self) return label
def createLabel(self) -> QGraphicsSimpleTextItem: """Creates a text label to display the ID number. Font and Z are set in gridstyles. Returns: the label """ label = QGraphicsSimpleTextItem("%d" % self.idNum()) label.setFont(_FONT) label.setZValue(_ZVALUE) label.setParentItem(self) return label
def drawHRefs(self): if self.xvmax < self.xvmin or self.awidth <= 0: return minsep = 30 factor = 1 unitincrement = self.awidth/float(self.xvmax-self.xvmin) xmaxint = self.xvmax vx = int(self.xvmin) pstart = self.value2point(vx, self.yvmin) px = pstart.x() pystart = pstart.y() pend = self.value2point(xmaxint, self.yvmin) pxend = pend.x() pyend = pend.y()-2 try: minsep = 10 * max([len(h) for h in self.hheaders]) except Exception: pass while (unitincrement*factor < minsep): provfactor = 2*factor if(unitincrement*provfactor > minsep): factor = provfactor break provfactor = 5*factor if(unitincrement*provfactor > minsep): factor = provfactor break factor = 10*factor # px+=unitincrement*factor # vx +=factor while(px <= pxend): colour = QtGui.QColor(0, 0, 0, 255) PlotLine(px+0.5, pystart+2, px+0.5, pyend, 1.5, colour, self) try: header = self.hheaders[vx] except IndexError: header = vx nlabel = QGraphicsSimpleTextItem( "{}".format(header), self) font = nlabel.font() font.setPixelSize(20) nlabel.setFont(font) nlabelrect = nlabel.boundingRect() nlabel.setPos(px + 0.5 - nlabelrect.width()/2, pystart+3) px += unitincrement*factor vx += factor
def __init__(self, nx_node, center_pos, nx_pos, steps, steps_max): """ Create node in the graph scene :param tuple nx_node: Node info :param center_pos: The position of the center node :param nx_pos: Position of the nodes in the graph :param int steps: The steps from the center identity :param int steps_max: The steps max of the graph """ super().__init__(nx_node, nx_pos) self.steps = steps self.steps_max = steps_max self.highlighted = False # text inside ellipse self.text_item = QGraphicsSimpleTextItem(self) self.text_item.setText(self.text) # center ellipse around text self.setRect( 0, 0, self.text_item.boundingRect().width() * 2, self.text_item.boundingRect().height() * 2 ) # set anchor to the center self.setTransform( QTransform().translate(-self.boundingRect().width() / 2.0, -self.boundingRect().height() / 2.0)) # center text in ellipse self.text_item.setPos(self.boundingRect().width() / 4.0, self.boundingRect().height() / 4.0) # cursor change on hover self.setAcceptHoverEvents(True) self.setZValue(1) # animation and moves self.timeline = None self.loading_timer = QTimer() self.loading_timer.timeout.connect(self.next_tick) self.loading_counter = 0 self._refresh_colors() self.setPos(center_pos) self.move_to(nx_pos)
def __init__(self, from_virtual_helix_item, to_virtual_helix_item, index, strand_type, is_low_idx): super(PreXoverItem, self).__init__(from_virtual_helix_item) self._from_vh_item = from_virtual_helix_item self._to_vh_item = to_virtual_helix_item self._idx = index self._strand_type = strand_type # translate from Low to Left for the Path View self._is_low_index = is_low_idx self._is_active = False self._pen = _SCAF_PEN if strand_type == StrandType.SCAFFOLD else _STAP_PEN is_on_top = from_virtual_helix_item.isStrandTypeOnTop(strand_type) bw = _BASE_WIDTH x = bw * index y = (-1.25 if is_on_top else 2.25) * bw self.setPos(x, y) num = to_virtual_helix_item.number() tBR = _FM.tightBoundingRect(str(num)) half_label_H = tBR.height()/2.0 half_label_W = tBR.width()/2.0 labelX = bw/2.0 - half_label_W # if num == 1: # adjust for the number one labelX -= half_label_W/2.0 if is_on_top: labelY = -0.25*half_label_H - .5 else: labelY = 2*half_label_H + .5 self._label = QGraphicsSimpleTextItem(self) self._label.setPos(labelX, labelY) # create a bounding rect item to process click events # over a wide area self._clickArea = c_a = QGraphicsRectItem(_RECT, self) c_a.mousePressEvent = self.mousePress yoffset = 0.2*bw if is_on_top else -0.4*bw c_a.setPos(0, yoffset) c_a.setPen(QPen(Qt.NoPen)) self.updateStyle() self._updateLabel() self.setPainterPath()
def drawVRefs(self): if self.yvmax < self.yvmin or self.aheight <= 0: return minsep = 30 factor = 1 try: unitincrement = self.aheight/float(self.yvmax-self.yvmin) except ZeroDivisionError: msg = "Division by zero in drawVRefs. Limits are {}-{}" print(msg.format(self.yvmin, self.yvmax)) while (unitincrement*factor < minsep): provfactor = 2*factor if(unitincrement*provfactor > minsep): factor = provfactor break provfactor = 5*factor if(unitincrement*provfactor > minsep): factor = provfactor break factor = 10*factor if (self.yvmin <= 0): vy = int(self.yvmin/factor)*factor else: vy = (int(self.yvmin/factor)+1)*factor pstart = self.value2point(self.xvmin, vy) pxstart = pstart.x() py = pstart.y() pend = self.value2point(self.xvmax, self.yvmax) pxend = pend.x() pyend = pend.y() while(py > pyend): colour = QtGui.QColor(0, 0, 0, 200) if vy == 0: PlotLine(pxstart-2, py, pxend, py, 1.5, QtCore.Qt.black, self) else: PlotLine(pxstart-2, py, pxend, py, 0.5, colour, self) nlabel = QGraphicsSimpleTextItem("{}".format(vy), self) font = nlabel.font() font.setPixelSize(20) nlabel.setFont(font) nlabelrect = nlabel.boundingRect() nlabel.setPos(pxstart - nlabelrect.width() - 5, py-nlabelrect.height()/2) py -= unitincrement*factor vy += factor
def __init__(self): super().__init__() self.model = CalendarModel() self.cursor_pos = None self.cursor = QGraphicsRectItem(self.root) self.header = QGraphicsSimpleTextItem(self.root) self.weekdays = [] days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] for day in days: self.weekdays.append(QGraphicsSimpleTextItem(day, self.root)) self.header_line = QGraphicsLineItem(self.root) self.days = [] for _ in range(0, 6 * 7): self.days.append(QGraphicsSimpleTextItem(self.root))
def __init__(self, part_item, active_base_index): super(ActiveSliceItem, self).__init__(part_item) self._part_item = part_item self._getActiveTool = part_item._getActiveTool self._active_slice = 0 self._low_drag_bound = 0 self._high_drag_bound = self.part().maxBaseIdx() self._controller = ActiveSliceItemController(self, part_item.part()) self._label = QGraphicsSimpleTextItem("", parent=self) self._label.setPos(0, -18) self._label.setFont(_FONT) self._label.setBrush(_LABEL_BRUSH) self._label.hide() self.setFlag(QGraphicsItem.ItemIsMovable) self.setAcceptHoverEvents(True) self.setZValue(styles.ZACTIVESLICEHANDLE) self.setRect(QRectF(0, 0, _BASE_WIDTH,\ self._part_item.boundingRect().height())) self.setPos(active_base_index*_BASE_WIDTH, 0) self.setBrush(_BRUSH) self.setPen(_PEN) # reuse select tool methods for other tools self.addSeqToolMousePress = self.selectToolMousePress self.addSeqToolMouseMove = self.selectToolMouseMove self.breakToolMousePress = self.selectToolMousePress self.breakToolMouseMove = self.selectToolMouseMove self.insertionToolMousePress = self.selectToolMousePress self.insertionToolMouseMove = self.selectToolMouseMove self.paintToolMousePress = self.selectToolMousePress self.paintToolMouseMove = self.selectToolMouseMove self.pencilToolMousePress = self.selectToolMousePress self.pencilToolMouseMove = self.selectToolMouseMove self.skipToolMousePress = self.selectToolMousePress self.skipToolMouseMove = self.selectToolMouseMove
class ActiveSliceItem(QGraphicsRectItem): """ActiveSliceItem for the Path View""" def __init__(self, part_item, active_base_index): super(ActiveSliceItem, self).__init__(part_item) self._part_item = part_item self._getActiveTool = part_item._getActiveTool self._active_slice = 0 self._low_drag_bound = 0 self._high_drag_bound = self.part().maxBaseIdx() self._controller = ActiveSliceItemController(self, part_item.part()) self._label = QGraphicsSimpleTextItem("", parent=self) self._label.setPos(0, -18) self._label.setFont(_FONT) self._label.setBrush(_LABEL_BRUSH) self._label.hide() self.setFlag(QGraphicsItem.ItemIsMovable) self.setAcceptHoverEvents(True) self.setZValue(styles.ZACTIVESLICEHANDLE) self.setRect(QRectF(0, 0, _BASE_WIDTH,\ self._part_item.boundingRect().height())) self.setPos(active_base_index*_BASE_WIDTH, 0) self.setBrush(_BRUSH) self.setPen(_PEN) # reuse select tool methods for other tools self.addSeqToolMousePress = self.selectToolMousePress self.addSeqToolMouseMove = self.selectToolMouseMove self.breakToolMousePress = self.selectToolMousePress self.breakToolMouseMove = self.selectToolMouseMove self.insertionToolMousePress = self.selectToolMousePress self.insertionToolMouseMove = self.selectToolMouseMove self.paintToolMousePress = self.selectToolMousePress self.paintToolMouseMove = self.selectToolMouseMove self.pencilToolMousePress = self.selectToolMousePress self.pencilToolMouseMove = self.selectToolMouseMove self.skipToolMousePress = self.selectToolMousePress self.skipToolMouseMove = self.selectToolMouseMove # end def ### SLOTS ### def strandChangedSlot(self, sender, vh): pass # end def def updateRectSlot(self, part): bw = _BASE_WIDTH new_rect = QRectF(0, 0, bw,\ self._part_item.virtualHelixBoundingRect().height()) if new_rect != self.rect(): self.setRect(new_rect) self._hideIfEmptySelection() self.updateIndexSlot(part, part.activeBaseIndex()) return new_rect # end def def updateIndexSlot(self, part, base_index): """The slot that receives active slice changed notifications from the part and changes the receiver to reflect the part""" label = self._label bw = _BASE_WIDTH bi = util.clamp(int(base_index), 0, self.part().maxBaseIdx()) self.setPos(bi * bw, -styles.PATH_HELIX_PADDING) self._active_slice = bi if label: label.setText("%d" % bi) label.setX((bw - label.boundingRect().width()) / 2) # end def ### ACCESSORS ### def activeBaseIndex(self): return self.part().activeBaseIndex() # end def def part(self): return self._part_item.part() # end def def partItem(self): return self._part_item # end def ### PUBLIC METHODS FOR DRAWING / LAYOUT ### def removed(self): scene = self.scene() scene.removeItem(self._label) scene.removeItem(self) self._part_item = None self._label = None self._controller.disconnectSignals() self.controller = None # end def def resetBounds(self): """Call after resizing virtualhelix canvas.""" self._high_drag_bound = self.part().maxBaseIdx() # end def ### PRIVATE SUPPORT METHODS ### def _hideIfEmptySelection(self): vis = self.part().numberOfVirtualHelices() > 0 self.setVisible(vis) self._label.setVisible(vis) # end def def _setActiveBaseIndex(self, base_index): self.part().setActiveBaseIndex(base_index) # end def ### EVENT HANDLERS ### def hoverEnterEvent(self, event): self.setCursor(Qt.OpenHandCursor) self._part_item.updateStatusBar("%d" % self.part().activeBaseIndex()) QGraphicsItem.hoverEnterEvent(self, event) # end def def hoverLeaveEvent(self, event): self.setCursor(Qt.ArrowCursor) self._part_item.updateStatusBar("") QGraphicsItem.hoverLeaveEvent(self, event) # end def def mousePressEvent(self, event): """ Parses a mousePressEvent, calling the approproate tool method as necessary. Stores _move_idx for future comparison. """ if event.button() != Qt.LeftButton: event.ignore() QGraphicsItem.mousePressEvent(self, event) return self.scene().views()[0].addToPressList(self) self._move_idx = int(floor((self.x() + event.pos().x()) / _BASE_WIDTH)) tool_method_name = self._getActiveTool().methodPrefix() + "MousePress" if hasattr(self, tool_method_name): # if the tool method exists modifiers = event.modifiers() getattr(self, tool_method_name)(modifiers) # call tool method def mouseMoveEvent(self, event): """ Parses a mouseMoveEvent, calling the approproate tool method as necessary. Updates _move_idx if it changed. """ tool_method_name = self._getActiveTool().methodPrefix() + "MouseMove" if hasattr(self, tool_method_name): # if the tool method exists idx = int(floor((self.x() + event.pos().x()) / _BASE_WIDTH)) if idx != self._move_idx: # did we actually move? modifiers = event.modifiers() self._move_idx = idx getattr(self, tool_method_name)(modifiers, idx) # call tool method def customMouseRelease(self, event): """ Parses a mouseReleaseEvent, calling the approproate tool method as necessary. Deletes _move_idx if necessary. """ tool_method_name = self._getActiveTool().methodPrefix() + "MouseRelease" if hasattr(self, tool_method_name): # if the tool method exists modifiers = event.modifiers() x = event.pos().x() getattr(self, tool_method_name)(modifiers, x) # call tool method if hasattr(self, '_move_idx'): del self._move_idx ### TOOL METHODS ### def selectToolMousePress(self, modifiers): """ Set the allowed drag bounds for use by selectToolMouseMove. """ if (modifiers & Qt.AltModifier) and (modifiers & Qt.ShiftModifier): self.part().undoStack().beginMacro("Auto-drag Scaffold(s)") for vh in self.part().getVirtualHelices(): # SCAFFOLD # resize 3' first for strand in vh.scaffoldStrandSet(): idx5p = strand.idx5Prime() idx3p = strand.idx3Prime() if not strand.hasXoverAt(idx3p): lo, hi = strand.getResizeBounds(idx3p) if strand.isDrawn5to3(): strand.resize((idx5p, hi)) else: strand.resize((lo, idx5p)) # resize 5' second for strand in vh.scaffoldStrandSet(): idx5p = strand.idx5Prime() idx3p = strand.idx3Prime() if not strand.hasXoverAt(idx5p): lo, hi = strand.getResizeBounds(idx5p) if strand.isDrawn5to3(): strand.resize((lo, idx3p)) else: strand.resize((idx3p, hi)) # STAPLE # resize 3' first for strand in vh.stapleStrandSet(): idx5p = strand.idx5Prime() idx3p = strand.idx3Prime() if not strand.hasXoverAt(idx3p): lo, hi = strand.getResizeBounds(idx3p) if strand.isDrawn5to3(): strand.resize((idx5p, hi)) else: strand.resize((lo, idx5p)) # resize 5' second for strand in vh.stapleStrandSet(): idx5p = strand.idx5Prime() idx3p = strand.idx3Prime() if not strand.hasXoverAt(idx3p): lo, hi = strand.getResizeBounds(idx5p) if strand.isDrawn5to3(): strand.resize((lo, idx3p)) else: strand.resize((idx3p, hi)) self.part().undoStack().endMacro() # end def def selectToolMouseMove(self, modifiers, idx): """ Given a new index (pre-validated as different from the prev index), calculate the new x coordinate for self, move there, and notify the parent strandItem to redraw its horizontal line. """ idx = util.clamp(idx, self._low_drag_bound, self._high_drag_bound) x = int(idx * _BASE_WIDTH) self.setPos(x, self.y()) self.updateIndexSlot(None, idx) self._setActiveBaseIndex(idx) self._part_item.updateStatusBar("%d" % self.part().activeBaseIndex())
def _updateLabel(self, is_left): """Called by updatePositionAndAppearance during init. Updates drawing and position of the label. Args: is_left (TYPE): Description """ lbl = self._label if self._idx is not None: bw = _BASE_WIDTH num = self._partner_virtual_helix.idNum() tBR = _FM.tightBoundingRect(str(num)) half_label_h = tBR.height()/2.0 half_label_w = tBR.width()/2.0 # determine x and y positions label_x = bw/2.0 - half_label_w if self._is_on_top: label_y = -0.25*half_label_h - 0.5 - 0.5*bw else: label_y = 2*half_label_h + 0.5 + 0.5*bw # adjust x for left vs right label_x_offset = 0.25*bw if is_left else -0.25*bw label_x += label_x_offset # adjust x for numeral 1 if num == 1: label_x -= half_label_w/2.0 # create text item if lbl is None: lbl = QGraphicsSimpleTextItem(str(num), self) lbl.setPos(label_x, label_y) lbl.setBrush(_ENAB_BRUSH) lbl.setFont(_TO_HELIX_NUM_FONT) self._label = lbl lbl.setText(str(self._partner_virtual_helix.idNum())) lbl.show()
class PreXoverItem(QGraphicsPathItem): def __init__(self, from_virtual_helix_item, to_virtual_helix_item, index, strand_type, is_low_idx): super(PreXoverItem, self).__init__(from_virtual_helix_item) self._from_vh_item = from_virtual_helix_item self._to_vh_item = to_virtual_helix_item self._idx = index self._strand_type = strand_type # translate from Low to Left for the Path View self._is_low_index = is_low_idx self._is_active = False self._pen = _SCAF_PEN if strand_type == StrandType.SCAFFOLD else _STAP_PEN is_on_top = from_virtual_helix_item.isStrandTypeOnTop(strand_type) bw = _BASE_WIDTH x = bw * index y = (-1.25 if is_on_top else 2.25) * bw self.setPos(x, y) num = to_virtual_helix_item.number() tBR = _FM.tightBoundingRect(str(num)) half_label_H = tBR.height()/2.0 half_label_W = tBR.width()/2.0 labelX = bw/2.0 - half_label_W # if num == 1: # adjust for the number one labelX -= half_label_W/2.0 if is_on_top: labelY = -0.25*half_label_H - .5 else: labelY = 2*half_label_H + .5 self._label = QGraphicsSimpleTextItem(self) self._label.setPos(labelX, labelY) # create a bounding rect item to process click events # over a wide area self._clickArea = c_a = QGraphicsRectItem(_RECT, self) c_a.mousePressEvent = self.mousePress yoffset = 0.2*bw if is_on_top else -0.4*bw c_a.setPos(0, yoffset) c_a.setPen(QPen(Qt.NoPen)) self.updateStyle() self._updateLabel() self.setPainterPath() # end def ### DRAWING METHODS ### def remove(self): scene = self.scene() if scene: scene.removeItem(self._label) scene.removeItem(self._clickArea) scene.removeItem(self) self._label = None self._clickArea = None self._from_vh_item = None self._to_vh_item = None # end def def setPainterPath(self): """ Sets the PainterPath according to the index (low = Left, high = Right) and strand position (top = Up, bottom = Down). """ path_LUT = (_PPATH_RD, _PPATH_RU, _PPATH_LD, _PPATH_LU) # Lookup table vhi = self._from_vh_item st = self._strand_type path = path_LUT[2*int(self._is_low_index) + int(vhi.isStrandTypeOnTop(st))] self.setPath(path) # end def def updateStyle(self): """ If a PreXover can be installed the pen is a bold color, otherwise the PreXover is drawn with a disabled or muted color """ from_vh = self._from_vh_item.virtualHelix() to_vh = self._to_vh_item.virtualHelix() part = self._from_vh_item.part() pen = _DISAB_PEN self._label_brush = _DISAB_BRUSH if part.possibleXoverAt(from_vh, to_vh, self._strand_type, self._idx): pen = self._pen self._is_active = True self._label_brush = _ENAB_BRUSH self.setPen(pen) # end def def _updateLabel(self): lbl = self._label lbl.setBrush(self._label_brush) lbl.setFont(_TO_HELIX_NUM_FONT) lbl.setText( str(self._to_vh_item.number() ) ) # end def ### TOOL METHODS ### def selectToolMousePress(self, event): """removexover(from_strand, from_idx, to_strand, to_idx)""" pass # end def def mousePress(self, event): if event.button() != Qt.LeftButton: return QGraphicsPathItem.mousePressEvent(self, event) if event.modifiers() & Qt.ShiftModifier: return # ignore shift click, user is probably trying to merge if self._is_active: from_vh = self._from_vh_item.virtualHelix() to_vh = self._to_vh_item.virtualHelix() from_ss = from_vh.getStrandSetByType(self._strand_type) to_ss = to_vh.getStrandSetByType(self._strand_type) from_strand = from_ss.getStrand(self._idx) to_strand = to_ss.getStrand(self._idx) part = self._from_vh_item.part() # determine if we are a 5' or a 3' end if self.path() in [_PPATH_LU, _PPATH_RD]: # 3' end of strand5p clicked strand5p = from_strand strand3p = to_strand else: # 5' strand5p = to_strand strand3p = from_strand # Gotta clear selections when installing a prexover # otherwise parenting in screwed up self._from_vh_item.viewroot().clearStrandSelections() part.createXover(strand5p, self._idx, strand3p, self._idx) else: event.setAccepted(False)
def createLabel(self): label = QGraphicsSimpleTextItem("%d" % self._virtual_helix.number()) label.setFont(_FONT) label.setZValue(_ZVALUE) label.setParentItem(self) return label
class ModuleItem(UMLItem): """ Class implementing a module item. """ ItemType = "module" def __init__(self, model=None, x=0, y=0, rounded=False, parent=None, scene=None): """ Constructor @param model module model containing the module data (ModuleModel) @param x x-coordinate (integer) @param y y-coordinate (integer) @keyparam rounded flag indicating a rounded corner (boolean) @keyparam parent reference to the parent object (QGraphicsItem) @keyparam scene reference to the scene object (QGraphicsScene) """ UMLItem.__init__(self, model, x, y, rounded, parent) scene.addItem(self) if self.model: self.__createTexts() self.__calculateSize() def __createTexts(self): """ Private method to create the text items of the module item. """ if self.model is None: return boldFont = QFont(self.font) boldFont.setBold(True) classes = self.model.getClasses() x = self.margin + self.rect().x() y = self.margin + self.rect().y() self.header = QGraphicsSimpleTextItem(self) self.header.setFont(boldFont) self.header.setText(self.model.getName()) self.header.setPos(x, y) y += self.header.boundingRect().height() + self.margin if classes: txt = "\n".join(classes) else: txt = " " self.classes = QGraphicsSimpleTextItem(self) self.classes.setFont(self.font) self.classes.setText(txt) self.classes.setPos(x, y) def __calculateSize(self): """ Private method to calculate the size of the module item. """ if self.model is None: return width = self.header.boundingRect().width() height = self.header.boundingRect().height() if self.classes: width = max(width, self.classes.boundingRect().width()) height = height + self.classes.boundingRect().height() self.setSize(width + 2 * self.margin, height + 2 * self.margin) def setModel(self, model): """ Public method to set the module model. @param model module model containing the module data (ModuleModel) """ self.scene().removeItem(self.header) self.header = None if self.classes: self.scene().removeItem(self.classes) self.meths = None self.model = model self.__createTexts() self.__calculateSize() def paint(self, painter, option, widget=None): """ Public method to paint the item in local coordinates. @param painter reference to the painter object (QPainter) @param option style options (QStyleOptionGraphicsItem) @param widget optional reference to the widget painted on (QWidget) """ pen = self.pen() if (option.state & QStyle.State_Selected) == \ QStyle.State(QStyle.State_Selected): pen.setWidth(2) else: pen.setWidth(1) painter.setPen(pen) painter.setBrush(self.brush()) painter.setFont(self.font) offsetX = self.rect().x() offsetY = self.rect().y() w = self.rect().width() h = self.rect().height() painter.drawRect(offsetX, offsetY, w, h) y = self.margin + self.header.boundingRect().height() painter.drawLine(offsetX, offsetY + y, offsetX + w - 1, offsetY + y) self.adjustAssociations() def buildItemDataString(self): """ Public method to build a string to persist the specific item data. This string must start with ", " and should be built like "attribute=value" with pairs separated by ", ". value must not contain ", " or newlines. @return persistence data (string) """ entries = [ "name={0}".format(self.model.getName()), ] classes = self.model.getClasses() if classes: entries.append("classes={0}".format("||".join(classes))) return ", " + ", ".join(entries) def parseItemDataString(self, version, data): """ Public method to parse the given persistence data. @param version version of the data (string) @param data persisted data to be parsed (string) @return flag indicating success (boolean) """ parts = data.split(", ") if len(parts) < 1: return False name = "" classes = [] for part in parts: key, value = part.split("=", 1) if key == "name": name = value.strip() elif key == "classes": classes = value.strip().split("||") else: return False self.model = ModuleModel(name, classes) self.__createTexts() self.__calculateSize() return True