def __init__(self, highlight_level, bounding_box, label, shape, color=None, parent=None, label_pos=None, tooltip=None): super(NodeItem, self).__init__(highlight_level, parent) self._default_color = self._COLOR_BLACK if color is None else color self._brush = QBrush(self._default_color) self._label_pen = QPen() self._label_pen.setColor(self._default_color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._ellipse_pen = QPen(self._label_pen) self._ellipse_pen.setWidth(1) self._incoming_edges = set() self._outgoing_edges = set() self.parse_shape(shape, bounding_box) self.addToGroup(self._graphics_item) self._label = QGraphicsSimpleTextItem(label) self._label.setFont(GraphItem._LABEL_FONT) label_rect = self._label.boundingRect() if label_pos is None: label_rect.moveCenter(bounding_box.center()) else: label_rect.moveCenter(label_pos) self._label.setPos(label_rect.x(), label_rect.y()) self.addToGroup(self._label) if tooltip is not None: self.setToolTip(tooltip) self.set_node_color() self.setAcceptHoverEvents(True) self.hovershape = None
def _draw_annotation(self, data): old_item = None if self.annotation_item: old_item = self.annotation_item annotation_item = None if not data == {}: resolution = self._drawing_objects['map'].info.resolution origin = self._drawing_objects['map'].info.origin w = self._drawing_objects['map'].info.width h = self._drawing_objects['map'].info.height x = -((data['x'] - origin.position.x) / resolution - w) y = (data['y'] - origin.position.y) / resolution if data['type'] == "yocs_msgs/Waypoint": #annotation_item = self._scene.addEllipse(x - (data['scale'][0] / resolution), y -(data['scale'][1] / resolution), data['scale'][0] / resolution * 2, data['scale'][1] / resolution * 2, pen=QPen(QColor(0, 0, 255)), brush=QBrush(QColor(0, 0, 255, 125))) viz_marker_pose = QMatrix().rotate(-data['yaw'] + 180).map( self._viz_marker_polygon).translated(x, y) annotation_item = self._scene.addPolygon( viz_marker_pose, pen=QPen(QColor(0, 0, 255)), brush=QBrush(QColor(0, 0, 255, 125))) elif data['type'] == "ar_track_alvar_msgs/AlvarMarker": viz_marker_pose = QMatrix().rotate( -(data['yaw'] - 90) + 180).map( self._viz_marker_polygon).translated(x, y) annotation_item = self._scene.addPolygon( viz_marker_pose, pen=QPen(QColor(0, 0, 255)), brush=QBrush(QColor(0, 0, 255, 125))) annotation_item.setZValue(2) if old_item: self._scene.removeItem(old_item) self.annotation_item = annotation_item
def getComponentPen(state): b = QPen(QColor(0, 0, 255)) # unconfigured/preoperational if state == 'A': # stopped b = QPen(QBrush(QColor(255, 0, 0)), 5) elif state == 'N': # running b = QPen(QBrush(QColor(0, 0, 0)), 1) return b
def getComponentBrush(state): b = QBrush(QColor(0, 0, 255)) # unconfigured/preoperational if state == 'S': # stopped b = QBrush(QColor(255, 255, 255)) elif state == 'R': # running b = QBrush(QColor(0, 255, 0)) return b
def paintEvent(self,event): super(JoystickPointView,self).paintEvent(event) try: if self._initialized: pass except: self._origPos = self.pos() self._initialized = True qp = QPainter() qp.begin(self) borderWidth = 2 radius = self.height()/2 center = QtCore.QPoint(self.height()/2,self.width()/2) # Outer Circle qp.setRenderHint(QPainter.Antialiasing, True) qp.setPen(QPen(QtCore.Qt.darkGray, borderWidth, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap,QtCore.Qt.RoundJoin)) qp.setBrush(QBrush(QtCore.Qt.white, QtCore.Qt.SolidPattern)) qp.drawEllipse(center,radius-borderWidth,radius-borderWidth) # Inner Circle qp.setPen(QPen(QtCore.Qt.lightGray, borderWidth, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap,QtCore.Qt.RoundJoin)) qp.setBrush(QBrush(QtCore.Qt.white, QtCore.Qt.SolidPattern)) qp.drawEllipse(center,radius-borderWidth-1,radius-borderWidth-1) qp.end()
def paint(self, painter, option, widget): painter.setFont(self._time_font) painter.fillRect(0, 0, SandtrayItem.length * SandtrayItem.scale, SandtrayItem.width * SandtrayItem.scale, painter.background()) for color, polys in self._zones.items(): painter.setPen(QPen(color, 2)) for poly in polys: painter.drawPolygon(QPolygonF(poly)) painter.setBrush(QBrush(self._fg_color)) painter.setPen(QPen(self._border_color, 1)) painter.drawRect(0, 0, SandtrayItem.length * SandtrayItem.scale, SandtrayItem.width * SandtrayItem.scale) for label, pos in self._items.items(): x, y = pos[0] * SandtrayItem.scale, pos[1] * SandtrayItem.scale painter.drawText(x - 10, y - 10, label) if "cube" in label: painter.setBrush(QBrush(self._cube_color)) painter.drawRect(x - 5, y - 5, 10, 10) else: painter.setBrush(QBrush(self._item_color)) painter.drawEllipse(QPointF(x, y), 10, 10)
def setNodeState(self, running_nodes, stopped_nodes, error_nodes): ''' Sets the state of this capability. :param running_nodes: a list with running nodes. :type running_nodes: [str] :param stopped_nodes: a list with not running nodes. :type stopped_nodes: [str] :param error_nodes: a list with nodes having a problem. :type error_nodes: [str] ''' self.setAutoFillBackground(True) self.setBackgroundRole(QPalette.Base) palette = QPalette() if error_nodes: brush = QBrush(QColor(255, 100, 0)) elif running_nodes and stopped_nodes: brush = QBrush(QColor(140, 185, 255)) # 30, 50, 255 elif running_nodes: self.on_button.setFlat(True) self.off_button.setFlat(False) brush = QBrush(QColor(59, 223, 18)) # 59, 223, 18 else: brush = QBrush(QColor(255, 255, 255)) self.on_button.setFlat(False) self.off_button.setFlat(True) palette.setBrush(QPalette.Active, QPalette.Base, brush) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Inactive, QPalette.Base, brush) self.setPalette(palette)
def __init__(self, bounding_box, shape, label, label_pos=None, url=None, parent=None, **kwargs): super(DmgHtmlNodeItem, self).__init__(parent, **kwargs) self.url = url self._incoming_edges = set() self._outgoing_edges = set() self._brush = QBrush(self._color) self._label_pen = QPen() self._label_pen.setColor(self._color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._label_pen.setWidthF(self._label_pen_width) self._graphics_item_pen = QPen(self._label_pen) self._graphics_item_pen.setWidthF(self._pen_width) self._label = QGraphicsTextItem() self._label.setHtml(label) label_rectangle = self._label.boundingRect() if label_pos is None: label_rectangle.moveCenter(bounding_box.center()) else: label_rectangle.moveCenter(label_pos) self._label.setPos(label_rectangle.x(), label_rectangle.y()) self.addToGroup(self._label) self._graphics_item = ShapeFactory.create(shape, bounding_box) if ShapeFactory.message is not None: print ShapeFactory.message self.addToGroup(self._graphics_item) self._brush.setColor(self._color) self._graphics_item_pen.setColor(self._color) self._label_pen.setColor(self._color) self._graphics_item.setPen(self._graphics_item_pen) self._highlight_level = kwargs.get('highlight_level', self.HIGHLIGHT_LEVEL) self._hovered_color = kwargs.get('hovered_color', self.HOVERED_COLOR) self._highlighted_color = kwargs.get('highlighted_color', self.HIGHLIGHTED_COLOR) self._highlighted_pen_width = kwargs.get('highlighted_pen_width', self.HIGHLIGHTED_PEN_WIDTH) self._highlighted_label_pen_width = kwargs.get( 'highlighted_label_pen_width', self.HIGHLIGHTED_LABEL_PEN_WIDTH) self.hover_shape = None self.setAcceptHoverEvents(True)
def __init__(self, bounding_box, shape, label, label_pos=None, url=None, parent=None, **kwargs): super(NodeItem, self).__init__(parent, **kwargs) self.url = url self._incoming_edges = set() self._outgoing_edges = set() self._brush = QBrush(self._color) self._label_pen = QPen() self._label_pen.setColor(self._color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._label_pen.setWidthF(self._label_pen_width) if self._pen_width == 0.0: self._graphics_item_pen = QPen(Qt.NoPen) else: self._graphics_item_pen = QPen(self._label_pen) self._graphics_item_pen.setWidthF(self._pen_width) self._graphics_item = ShapeFactory.create(shape, bounding_box) if ShapeFactory.message is not None: print ShapeFactory.message self.addToGroup(self._graphics_item) if not shape == 'point': self._label = QGraphicsSimpleTextItem(label) label_rectangle = self._label.boundingRect() if label_pos is None: label_rectangle.moveCenter(bounding_box.center()) else: label_rectangle.moveCenter(label_pos) self._label.setPos(label_rectangle.x(), label_rectangle.y()) self.addToGroup(self._label) else: self._graphics_item.setBrush(self._color) self._label = None self._brush.setColor(self._color) self._graphics_item_pen.setColor(self._color) self._label_pen.setColor(self._color) self._graphics_item.setPen(self._graphics_item_pen) if self._label is not None: self._label.setBrush(self._brush) self._label.setPen(self._label_pen)
def __init__(self, parent): super(AngularLabel, self).__init__(parent) self.colorGreen = QColor(66, 255, 100, 128) self.colorRed = QColor(255, 66, 100, 128) self.brushGreen = QBrush(self.colorGreen) self.brushRed = QBrush(self.colorRed) self.penGreen = QPen(self.brushGreen, 1) self.penRed = QPen(self.brushRed, 1) self.setFixedSize(100, 100) self.angle = 0 self.velocity = 0
def paint(self, painter, option, widget): """Overwrites BlockItem.paint so that we can fill in the block rectangles""" brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(self.bgcolor) painter.fillRect(self.rect(), brush) border_pen = QPen() border_pen.setBrush(self.border_color) border_pen.setStyle(Qt.SolidLine) border_pen.setWidth(self.border_width) painter.setPen(border_pen) painter.drawRect(self.rect())
def __init__(self, mark_dim, view_dim): self.mark_dim = mark_dim self.view_dim = view_dim self._pens = { 'black': QPen(QtCore.Qt.black), 'white': QPen(QtCore.Qt.white) } self._brushes = { 'black': QBrush(QtCore.Qt.black), 'white': QBrush(QtCore.Qt.white) } self._prepare()
def transitionSelected(self, index): for e in self.prev_selected_connections: e.setPen(QPen(QBrush(QColor(0, 0, 0)), 0)) self.prev_selected_connections = [] if not self.component_selected: return for e in self.edges: data = e.data(0) if (data[0] == self.component_selected) and ( data[1] == self.selected_component_next_states_names[index]): e.setPen(QPen(QBrush(QColor(255, 0, 0)), 5)) self.prev_selected_connections.append(e)
def initStyleOption(self, option, index): """ Manupulates the background-color of a cell in the model. :param option: The options parameter :type option: QStyleOptionViewItem :param index: The QModelIndex that will be painted :type index: QModelIndex """ super(SizeDelegate, self).initStyleOption(option, index) temp = index.model().mapToSource(index) if temp.internalPointer().marked: option.backgroundBrush = QBrush(QColor(255, 165, 0, 70)) else: option.backgroundBrush = QBrush(choose_brush(index))
def paintEvent(self, event): with self.lock: self.event = event rect = event.rect() qp = QPainter() qp.begin(self) radius = min(rect.width(), rect.height()) - 50 qp.setFont(QFont('Helvetica', 100)) qp.setPen(QPen(QBrush(QColor(255, 255, 255)), 20)) if self.is_disabled: qp.fillRect(rect, self._DISABLED_COLOR) qp.drawText(rect, QtCore.Qt.AlignCenter, self._FROWN) elif self.is_blackout: qp.fillRect(rect, self._BLACKOUT_COLOR) qp.drawText(rect, QtCore.Qt.AlignCenter, self._FROWN) time_diff = (self.next_whiteout_time - rospy.Time.now()).to_sec() if time_diff < 0: time_diff = 0 time_ratio = time_diff / (self.next_whiteout_time - self.blackout_time).to_sec() qp.setFont(QFont('Helvetica', 30)) qp.drawText(0, rect.height() - 150, rect.width(), 150, QtCore.Qt.AlignCenter, "%.1f sec" % time_diff) # 0-360 if time_ratio > 0: rad = int(math.fmod(time_ratio * 360 + 90*16, 360) * 16) qp.drawArc((rect.width() - radius) / 2, (rect.height() - radius) / 2, radius, radius, 90*16, rad) else: qp.fillRect(rect, self._OK_COLOR) qp.drawText(rect, QtCore.Qt.AlignCenter, self._SMILEY) qp.end()
def add_ROI(self, pixel_coords): self.regionCounter += 1 markerSize = 25 ellipse_item = QGraphicsEllipseItem( QRectF( QPointF(pixel_coords.x() - markerSize / 2, pixel_coords.y() - markerSize / 2), QSizeF(markerSize, markerSize))) ellipse_item.setBrush(QBrush(QColor('red'))) self.addItem(ellipse_item) label_font = QFont() label_font.setPointSize(15) region_string = 'r' + str(self.regionCounter).zfill(2) ellipse_item_label = QGraphicsTextItem(region_string) ellipse_item_label.setPos(pixel_coords) ellipse_item_label.setFont(label_font) self.addItem(ellipse_item_label) self.items_dict.update({ region_string: { 'ellipse_item': ellipse_item, 'ellipse_item_label': ellipse_item_label, 'pixel_coords': pixel_coords, 'ap_item_label': {} } })
def _draw_playhead(self, painter): """ Draw a line and 2 triangles to denote the current position being viewed :param painter: ,''QPainter'' """ px = self.map_stamp_to_x(self.playhead.to_sec()) pw, ph = self._playhead_pointer_size # Line painter.setPen(QPen(self._playhead_color)) painter.setBrush(QBrush(self._playhead_color)) painter.drawLine(px, self._history_top - 1, px, self._history_bottom + 2) # Upper triangle py = self._history_top - ph painter.drawPolygon( QPolygonF([ QPointF(px, py + ph), QPointF(px + pw, py), QPointF(px - pw, py) ])) # Lower triangle py = self._history_bottom + 1 painter.drawPolygon( QPolygonF([ QPointF(px, py), QPointF(px + pw, py + ph), QPointF(px - pw, py + ph) ])) painter.setBrush(self._default_brush) painter.setPen(self._default_pen)
def _draw_major_divisions(self, painter, stamps, start_stamp, division): """ Draw black hashed vertical grid-lines showing major time divisions. :param painter: allows access to paint functions,''QPainter'' """ label_y = self._history_top - self._playhead_pointer_size[1] - 5 for stamp in stamps: x = self.map_stamp_to_x(stamp, False) label = self._get_label(division, stamp - start_stamp) label_x = x + self._major_divisions_label_indent if label_x + QFontMetrics( self._topic_font).width(label) < self.scene().width(): painter.setPen(self._default_pen) painter.setBrush(QBrush(Qt.black)) path = QPainterPath() path.addText(label_x, label_y, self._time_font, label) painter.drawPath(path) painter.setPen(self._major_division_pen) painter.drawLine( x, label_y - self._time_tick_height - self._time_font_size, x, self._history_bottom) painter.setBrush(self._default_brush) painter.setPen(self._default_pen)
def __init__(self, scene, time, color=None): y2 = len(scene._tracks) * TimelineTrack.height super(TimelineMarker, self).__init__(time, - TimelineTrack.height, time, y2, None, scene) self.setZValue(self._z) if color is None: color = QColor(self._default_color) color.setAlphaF(0.5) self.setPen(QPen(QBrush(color), 0.05))
def draw_viz_markers(self, data, key): old_items = [] if len(self._viz_marker_items[key]): for item in self._viz_marker_items[key]: old_items.append(item) self._viz_marker_items[key] = [] for viz_marker in data: if viz_marker['type'] is Marker.TEXT_VIEW_FACING: # text viz_marker_text = viz_marker['text'] viz_marker_pose_item = self._scene.addSimpleText( viz_marker_text, font=QFont()) # Everything must be mirrored viz_marker_pose_item.translate(-viz_marker['x'], viz_marker['y']) elif viz_marker['type'] is Marker.CYLINDER: # # waypoint # viz_marker_pose_item = self._scene.addEllipse(viz_marker['x'] - viz_marker['scale'][0] / 2, viz_marker['y'] - viz_marker['scale'][1] / 2, viz_marker['scale'][0], viz_marker['scale'][1], pen=QPen(QColor(255, 0, 0)), brush=QBrush(QColor(255, 0, 0))) # # Everything must be mirrored # self._mirror(viz_marker_pose_item) viz_marker_pose = QMatrix().scale( 1, -1).rotate(viz_marker['yaw'] + 180).map( self._viz_marker_polygon).translated( -viz_marker['x'], viz_marker['y']) viz_marker_pose_item = self._scene.addPolygon( viz_marker_pose, pen=QPen(QColor(0, 255, 0)), brush=QBrush(QColor(0, 255, 0))) elif viz_marker['type'] is Marker.ARROW: # marker # Everything must be mirrored viz_marker_pose = QMatrix().scale( 1, -1).rotate((viz_marker['yaw'] - 90) + 180).map( self._viz_marker_polygon).translated( -viz_marker['x'], viz_marker['y']) viz_marker_pose_item = self._scene.addPolygon( viz_marker_pose, pen=QPen(QColor(255, 0, 0)), brush=QBrush(QColor(255, 0, 0))) else: rospy.logerr("Unknown Marker type : %s" % (viz_marker['type'])) viz_marker_pose_item.setZValue(1) self._viz_marker_items[key].append(viz_marker_pose_item) if len(old_items): for item in old_items: self._scene.removeItem(item)
def portSelected(self, index): for e in self.prev_selected_connections: e.setPen(QPen(QBrush(QColor(0, 0, 0)), 0)) self.prev_selected_connections = [] if not self.component_selected: return for conn in self.parent.all_connections: if (conn[0] == self.component_selected and conn[1] == self.selected_component_port_names[index]) or \ (conn[2] == self.component_selected and conn[3] == self.selected_component_port_names[index]): for graph_name in self.edges: for e in self.edges[graph_name]: data = e.data(0) if (data[0] == conn[0] and data[1] == conn[2]) or \ (data[0] == conn[2] and data[1] == conn[0]): e.setPen(QPen(QBrush(QColor(255, 0, 0)), 5)) self.prev_selected_connections.append(e)
def __init__(self, context): super(Eyedrop, self).__init__(context) # Give QObjects reasonable names self.setObjectName('Eyedrop') rp = rospkg.RosPack() # Process standalone plugin command-line arguments from argparse import ArgumentParser parser = ArgumentParser() # Add argument(s) to the parser. parser.add_argument("-q", "--quiet", action="store_true", dest="quiet", help="Put plugin in silent mode") self.args, unknowns = parser.parse_known_args(context.argv()) # Create QWidget self._widget = QWidget() # Get path to UI file which is a sibling of this file # in this example the .ui and .py file are in the same folder ui_file = os.path.join(rp.get_path('rqt_eyedropper'), 'resource', 'Eyedrop.ui') # Extend the widget with all attributes and children from UI file loadUi(ui_file, self._widget) # Give QObjects reasonable names self._widget.setObjectName('EyedropUi') # Show _widget.windowTitle on left-top of each plugin (when # it's set in _widget). This is useful when you open multiple # plugins at once. Also if you open multiple instances of your # plugin at once, these lines add number to make it easy to # tell from pane to pane. if context.serial_number() > 1: self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number())) # Add widget to the user interface context.add_widget(self._widget) self._widget.button_refresh_topics.clicked.connect( self.button_refresh_topics_pressed) self._widget.button_take_sample.clicked.connect( self.button_take_sample_pressed) self._widget.combo_box_topic_image.currentIndexChanged.connect( self.do_subscribe_image) self._widget.combo_box_topic_point.currentIndexChanged.connect( self.do_subscribe_point) self.colour_pane_scene = QGraphicsScene() self.colour_pane_scene.setBackgroundBrush(QBrush(QColor(0, 0, 0))) self._widget.graphics_view_colour_pane.setScene(self.colour_pane_scene) self._widget.graphics_view_colour_pane.show() self.bridge = CvBridge() self.do_refresh_topic_lists()
def data(self, proxy_index, role=None): """ Set colors of items based on highlight filters. """ index = self.mapToSource(proxy_index) if role == Qt.ForegroundRole: msg = self._source_model._messages[index.row()] if not msg.highlighted: return QBrush(Qt.gray) return self._source_model.data(index, role)
def _draw_bag_ends(self, painter): """ Draw markers to indicate the area the bag file represents within the current visible area. :param painter: allows access to paint functions,''QPainter'' """ x_start, x_end = self.map_stamp_to_x(self._start_stamp.to_sec()), self.map_stamp_to_x(self._end_stamp.to_sec()) painter.setBrush(QBrush(self._bag_end_color)) painter.drawRect(self._history_left, self._history_top, x_start - self._history_left, self._history_bottom - self._history_top) painter.drawRect(x_end, self._history_top, self._history_left + self._history_width - x_end, self._history_bottom - self._history_top) painter.setBrush(self._default_brush) painter.setPen(self._default_pen)
def initStyleOption(self, option, index): """ Manupulates the background-color of a cell in the model. :param option: The options parameter :type option: QStyleOptionViewItem :param index: The QModelIndex that will be painted :type index: QModelIndex """ super(LogDelegate, self).initStyleOption(option, index) option.backgroundBrush = QBrush(choose_brush(index))
def add_curve(self, curve_id, curve_name, curve_color=QColor(Qt.blue), markers_on=False): curve_id = str(curve_id) if curve_id in self._curves: return curve_object = Qwt.QwtPlotCurve(curve_name) curve_object.attach(self) curve_object.setPen(curve_color) if markers_on: curve_object.setSymbol( Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, QBrush(curve_color), QPen(Qt.black), QSize(4, 4))) self._curves[curve_id] = curve_object
def _show_capture_teleop_message(self, rtn): if rtn: QMessageBox.warning(self._widget, 'SUCCESS', "CAPTURE!!!!", QMessageBox.Ok | QMessageBox.Ok) for k in self.robot_item_list.keys(): if self.robot_item_list[k] == self.current_robot: k.setBackground(0, QBrush(Qt.SolidPattern)) k.setBackgroundColor(0, QColor(0, 255, 0, 255)) robot_name = k.text(0) k.setText(0, str(robot_name) + " (captured)") else: k.setBackground(0, QBrush(Qt.NoBrush)) k.setBackgroundColor(0, QColor(0, 0, 0, 0)) robot_name = k.text(0) self._widget.capture_teleop_btn.setEnabled(False) self._widget.release_teleop_btn.setEnabled(True) self.current_captured_robot = self.current_robot else: QMessageBox.warning(self._widget, 'FAIL', "FAIURE CAPTURE!!!!", QMessageBox.Ok | QMessageBox.Ok) self._widget.setDisabled(False)
def setNodeState(self, running_nodes, stopped_nodes, error_nodes): ''' Sets the state of this capability. @param running_nodes: a list with running nodes. @type running_nodes: C{[str]} @param stopped_nodes: a list with not running nodes. @type stopped_nodes: C{[str]} @param error_nodes: a list with nodes having a problem. @type error_nodes: C{[str]} ''' self.setAutoFillBackground(True) self.setBackgroundRole(QPalette.Base) palette = QPalette() if error_nodes: brush = QBrush(QColor(255, 100, 0)) elif running_nodes and stopped_nodes: brush = QBrush(QColor(140, 185, 255)) # 30, 50, 255 elif running_nodes: self.on_button.setFlat(True) self.off_button.setFlat(False) brush = QBrush(QColor(59, 223, 18)) # 59, 223, 18 else: brush = QBrush(QColor(255, 255, 255)) self.on_button.setFlat(False) self.off_button.setFlat(True) palette.setBrush(QPalette.Active, QPalette.Base, brush) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Inactive, QPalette.Base, brush) self.setPalette(palette)
def data(self, index, role=None): """ Sets colors of items based on highlight filters and severity type """ messagelist = self.sourceModel()._messages.get_message_list() index = self.mapToSource(index) if index.row() >= 0 or index.row() < len(messagelist): if index.column() >= 0 or index.column() < messagelist[ index.row()].count(): if role == Qt.ForegroundRole: if index.column() == 1: data = index.data() severity_levels = {'Debug': QBrush(Qt.cyan), \ 'Info': QBrush(Qt.darkCyan), \ 'Warn': QBrush(Qt.darkYellow), \ 'Error': QBrush(Qt.darkRed), \ 'Fatal': QBrush(Qt.red)} if data in severity_levels.keys(): return severity_levels[data] else: raise KeyError('Unknown severity type: %s' % data) if self._highlight_filters.count_enabled_filters() > 0: if not self._highlight_filters.test_message( messagelist[index.row()]): return QBrush(Qt.gray) return self.sourceModel().data(index, role)
def _show_capture_resource_message(self, rtn): if rtn: QMessageBox.warning(self, 'SUCCESS', "CAPTURE!!!!", QMessageBox.Ok | QMessageBox.Ok) else: QMessageBox.warning(self, 'FAIL', "FAIURE CAPTURE!!!!", QMessageBox.Ok | QMessageBox.Ok) self._lock.acquire() if rtn: for k in self.resource_item_list.keys(): if self.resource_item_list[k] == self.current_resource: k.setBackground(0, QBrush(Qt.SolidPattern)) k.setBackgroundColor(0, QColor(0, 255, 0, 255)) resource_name = k.text(0) k.setText(0, str(resource_name) + " (captured)") else: k.setBackground(0, QBrush(Qt.NoBrush)) k.setBackgroundColor(0, QColor(0, 0, 0, 0)) resource_name = k.text(0) self.capture_resource_btn.setEnabled(False) self.release_resource_btn.setEnabled(True) self.current_captured_resource = self.current_resource self.setDisabled(False) self._lock.release()
def _draw_topic_dividers(self, painter): """ Draws horizontal lines between each topic to visually separate the messages :param painter: allows access to paint functions,''QPainter'' """ clip_left = self._history_left clip_right = self._history_left + self._history_width row = 0 for topic in self.topics: (x, y, w, h) = self._history_bounds[topic] if row % 2 == 0: painter.setPen(Qt.lightGray) painter.setBrush(QBrush(self._history_background_color_alternate)) else: painter.setPen(Qt.lightGray) painter.setBrush(QBrush(self._history_background_color)) left = max(clip_left, x) painter.drawRect(left, y, min(clip_right - left, w), h) row += 1 painter.setBrush(self._default_brush) painter.setPen(self._default_pen)
def __init__(self, bounding_box, shape, label, label_pos=None, url=None, parent=None, **kwargs): super(NodeItem, self).__init__(parent, **kwargs) self.url = url self._incoming_edges = set() self._outgoing_edges = set() self._brush = QBrush(self._color) self._label_pen = QPen() self._label_pen.setColor(self._color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._label_pen.setWidthF(self._label_pen_width) if self._pen_width == 0.0: self._graphics_item_pen = QPen(Qt.NoPen) else: self._graphics_item_pen = QPen(self._label_pen) self._graphics_item_pen.setWidthF(self._pen_width) self._graphics_item = ShapeFactory.create(shape, bounding_box) if ShapeFactory.message is not None: print ShapeFactory.message self.addToGroup(self._graphics_item) if not shape == 'point': self._label = QGraphicsSimpleTextItem(label) label_rectangle = self._label.boundingRect() if label_pos is None: label_rectangle.moveCenter(bounding_box.center()) else: label_rectangle.moveCenter(label_pos) self._label.setPos(label_rectangle.x(), label_rectangle.y()) self.addToGroup(self._label) else: self._graphics_item.setBrush(self._color) self._label = None self._brush.setColor(self._color) self._graphics_item_pen.setColor(self._color) self._label_pen.setColor(self._color) self._graphics_item.setPen(self._graphics_item_pen) if self._label is not None: self._label.setBrush(self._brush) self._label.setPen(self._label_pen)
def remove_robot(self): if self.num_robots > 1: rospy.loginfo('rqt_simulation : A robot tab was removed.') self.num_robots = self.num_robots - 1 self.current_graphicsScene.removeItem( self.tab_list[self.num_robots].initial_pose[ 'start_' + str(self.num_robots + 1).zfill(2)]['text_item']) for i in range(0, len(self.current_graphicsScene.items_dict)): self.current_graphicsScene.items_dict[ self.current_graphicsScene.items_dict.keys() [i]]['ellipse_item'].setBrush(QBrush(QColor('red'))) if len(self.FTS.region_of_interest) > 0: for i in range(0, self.num_robots): self.current_graphicsScene.items_dict[ self.tab_list[i].initial_pose['start_' + str(i + 1).zfill(2)] ['label']]['ellipse_item'].setBrush( QBrush(QColor('green'))) rect = self.current_graphicsScene.items_dict[ self.tab_list[i].initial_pose['start_' + str(i + 1).zfill(2)] ['label']]['ellipse_item'].rect() point = rect.topLeft() self.tab_list[i].initial_pose[ 'start_' + str(i + 1).zfill(2)]['text_item'].setPos( point.x() - 11, point.y() - 22) self.tabWidget.removeTab(self.num_robots) del self.tab_list[self.num_robots] if self.num_robots == 1: self.button_remove_robot.setEnabled(False)
def __init__(self, bounding_box, shape, label, label_pos=None, url=None, parent=None, **kwargs): super(DmgHtmlNodeItem, self).__init__(parent, **kwargs) self.url = url self._incoming_edges = set() self._outgoing_edges = set() self._brush = QBrush(self._color) self._label_pen = QPen() self._label_pen.setColor(self._color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._label_pen.setWidthF(self._label_pen_width) self._graphics_item_pen = QPen(self._label_pen) self._graphics_item_pen.setWidthF(self._pen_width) self._label = QGraphicsTextItem() self._label.setHtml(label) label_rectangle = self._label.boundingRect() if label_pos is None: label_rectangle.moveCenter(bounding_box.center()) else: label_rectangle.moveCenter(label_pos) self._label.setPos(label_rectangle.x(), label_rectangle.y()) self.addToGroup(self._label) self._graphics_item = ShapeFactory.create(shape, bounding_box) if ShapeFactory.message is not None: print ShapeFactory.message self.addToGroup(self._graphics_item) self._brush.setColor(self._color) self._graphics_item_pen.setColor(self._color) self._label_pen.setColor(self._color) self._graphics_item.setPen(self._graphics_item_pen) self._highlight_level = kwargs.get('highlight_level', self.HIGHLIGHT_LEVEL) self._hovered_color = kwargs.get('hovered_color', self.HOVERED_COLOR) self._highlighted_color = kwargs.get('highlighted_color', self.HIGHLIGHTED_COLOR) self._highlighted_pen_width = kwargs.get('highlighted_pen_width', self.HIGHLIGHTED_PEN_WIDTH) self._highlighted_label_pen_width = kwargs.get('highlighted_label_pen_width', self.HIGHLIGHTED_LABEL_PEN_WIDTH) self.hover_shape = None self.setAcceptHoverEvents(True)
def paint(self, painter, option, widget): # Paint background brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(self.bgcolor) painter.fillRect(self.rect(), brush) # Paint border border_pen = QPen() border_pen.setBrush(self.border_color) border_pen.setStyle(Qt.SolidLine) border_pen.setWidth(self.border_width) painter.setPen(border_pen) painter.drawRect(self.rect()) rect = self.geometry() # Create arrows arrow_scale = 0.25 arrow_width = rect.width() * arrow_scale arrow_height = arrow_width * 0.8 arrow_margin = (rect.width() - arrow_width) / 2.0 brush.setColor(self.label_color) painter.setPen(Qt.NoPen) painter.setBrush(brush) arrow = None if self.topBand == self.dest_band_item: # Draw pointing up arrow = QPolygon([QPoint(0, arrow_height), QPoint(arrow_width, arrow_height), QPoint(arrow_width / 2.0, 0)]) arrow.translate(self.rect().x() + arrow_margin, self.rect().y() + 1) else: # Draw pointing down arrow = QPolygon([QPoint(0, 0), QPoint(arrow_width, 0), QPoint(arrow_width / 2.0, arrow_height)]) arrow.translate(self.rect().x() + arrow_margin, self.rect().y() + rect.height() - arrow_height) painter.drawPolygon(arrow) # Label painter.setPen(self.label_color) painter.rotate(-90) fm = painter.fontMetrics() elided = fm.elidedText(self.label, Qt.ElideRight, rect.height()) twidth = fm.width(elided) painter.drawText(-twidth - (rect.height() - twidth) / 2, rect.width() - 2, elided)
def __init__(self, highlight_level, bounding_box, label, shape, color=None, parent=None, label_pos=None, tooltip=None): super(NodeItem, self).__init__(highlight_level, parent) self._default_color = self._COLOR_BLACK if color is None else color self._brush = QBrush(self._default_color) self._label_pen = QPen() self._label_pen.setColor(self._default_color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._ellipse_pen = QPen(self._label_pen) self._ellipse_pen.setWidth(1) self._incoming_edges = set() self._outgoing_edges = set() if shape == 'box': self._graphics_item = QGraphicsRectItem(bounding_box) else: self._graphics_item = QGraphicsEllipseItem(bounding_box) self.addToGroup(self._graphics_item) self._label = QGraphicsSimpleTextItem(label) label_rect = self._label.boundingRect() if label_pos is None: label_rect.moveCenter(bounding_box.center()) else: label_rect.moveCenter(label_pos) self._label.setPos(label_rect.x(), label_rect.y()) self.addToGroup(self._label) if tooltip is not None: self.setToolTip(tooltip) self.set_node_color() self.setAcceptHoverEvents(True) self.hovershape = None
def paint(self, painter, option, widget): # Paint background brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(self.bgcolor) painter.fillRect(self.rect(), brush) # Paint border border_pen = QPen() border_pen.setBrush(self.border_color) border_pen.setStyle(Qt.SolidLine) border_pen.setWidth(self.border_width) painter.setPen(border_pen) painter.drawRect(self.rect()) rect = self.geometry() # Create arrows arrow_scale = 0.25 arrow_width = rect.width() * arrow_scale arrow_height = arrow_width * 0.8 arrow_margin = (rect.width() - arrow_width) / 2.0 brush.setColor(self.label_color) painter.setPen(Qt.NoPen) painter.setBrush(brush)
def __init__(self, spline, label, label_center, from_node, to_node, parent=None, **kwargs): super(EdgeItem, self).__init__(parent, **kwargs) self._edge_pen_width = kwargs.get('edge_pen_width', self.EDGE_PEN_WIDTH) self.from_node = from_node self.from_node.add_outgoing_edge(self) self.to_node = to_node self.to_node.add_incoming_edge(self) self._brush = QBrush(self._color) self._label_pen = QPen() self._label_pen.setColor(self._color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._label_pen.setWidthF(self._label_pen_width) self._edge_pen = QPen() self._edge_pen.setColor(self._color) self._edge_pen.setWidthF(self._edge_pen_width) self._sibling_edges = set() self._label = None if label is not None: self._label = QGraphicsSimpleTextItem(label) font = self._label.font() font.setPointSize(8) self._label.setFont(font) label_rect = self._label.boundingRect() label_rect.moveCenter(label_center) self._label.setPos(label_rect.x(), label_rect.y()) # spline specification according to http://www.graphviz.org/doc/info/attrs.html#k:splineType coordinates = spline.split(' ') # extract optional end_point end_point = None if coordinates[0].startswith('e,'): parts = coordinates.pop(0)[2:].split(',') end_point = QPointF(float(parts[0]), -float(parts[1])) # extract optional start_point if coordinates[0].startswith('s,'): parts = coordinates.pop(0).split(',') # first point parts = coordinates.pop(0).split(',') point = QPointF(float(parts[0]), -float(parts[1])) path = QPainterPath(point) while len(coordinates) > 2: # extract triple of points for a cubic spline parts = coordinates.pop(0).split(',') point1 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point2 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point3 = QPointF(float(parts[0]), -float(parts[1])) path.cubicTo(point1, point2, point3) self._arrow = None if end_point is not None: # draw arrow self._arrow = QGraphicsPolygonItem() polygon = QPolygonF() polygon.append(point3) offset = QPointF(end_point - point3) corner1 = QPointF(-offset.y(), offset.x()) * 0.35 corner2 = QPointF(offset.y(), -offset.x()) * 0.35 polygon.append(point3 + corner1) polygon.append(end_point) polygon.append(point3 + corner2) self._arrow.setPolygon(polygon) self._path = QGraphicsPathItem() self._path.setPath(path) self.addToGroup(self._path) self._brush.setColor(self._color) self._edge_pen.setColor(self._color) self._label_pen.setColor(self._color) self._path.setPen(self._edge_pen) if self._arrow is not None: self._arrow.setBrush(self._brush) self._arrow.setPen(self._edge_pen) if self._label is not None: self._label.setBrush(self._brush) self._label.setPen(self._label_pen)
def __init__(self, highlight_level, spline, label_center, label, from_node, to_node, parent=None, penwidth=1, edge_color=None, style='solid'): super(EdgeItem, self).__init__(highlight_level, parent) self.from_node = from_node self.from_node.add_outgoing_edge(self) self.to_node = to_node self.to_node.add_incoming_edge(self) self._default_edge_color = self._COLOR_BLACK if edge_color is not None: self._default_edge_color = edge_color self._default_text_color = self._COLOR_BLACK self._default_color = self._COLOR_BLACK self._text_brush = QBrush(self._default_color) self._shape_brush = QBrush(self._default_color) if style in ['dashed', 'dotted']: self._shape_brush = QBrush(Qt.transparent) self._label_pen = QPen() self._label_pen.setColor(self._default_text_color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._edge_pen = QPen(self._label_pen) self._edge_pen.setWidth(penwidth) self._edge_pen.setColor(self._default_edge_color) self._edge_pen.setStyle(self._qt_pen_styles.get(style, Qt.SolidLine)) self._sibling_edges = set() self._label = None if label is not None: self._label = QGraphicsSimpleTextItem(label) label_rect = self._label.boundingRect() label_rect.moveCenter(label_center) self._label.setPos(label_rect.x(), label_rect.y()) self._label.hoverEnterEvent = self._handle_hoverEnterEvent self._label.hoverLeaveEvent = self._handle_hoverLeaveEvent self._label.setAcceptHoverEvents(True) # spline specification according to http://www.graphviz.org/doc/info/attrs.html#k:splineType coordinates = spline.split(' ') # extract optional end_point end_point = None if (coordinates[0].startswith('e,')): parts = coordinates.pop(0)[2:].split(',') end_point = QPointF(float(parts[0]), -float(parts[1])) # extract optional start_point if (coordinates[0].startswith('s,')): parts = coordinates.pop(0).split(',') # first point parts = coordinates.pop(0).split(',') point = QPointF(float(parts[0]), -float(parts[1])) path = QPainterPath(point) while len(coordinates) > 2: # extract triple of points for a cubic spline parts = coordinates.pop(0).split(',') point1 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point2 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point3 = QPointF(float(parts[0]), -float(parts[1])) path.cubicTo(point1, point2, point3) self._arrow = None if end_point is not None: # draw arrow self._arrow = QGraphicsPolygonItem() polygon = QPolygonF() polygon.append(point3) offset = QPointF(end_point - point3) corner1 = QPointF(-offset.y(), offset.x()) * 0.35 corner2 = QPointF(offset.y(), -offset.x()) * 0.35 polygon.append(point3 + corner1) polygon.append(end_point) polygon.append(point3 + corner2) self._arrow.setPolygon(polygon) self._arrow.hoverEnterEvent = self._handle_hoverEnterEvent self._arrow.hoverLeaveEvent = self._handle_hoverLeaveEvent self._arrow.setAcceptHoverEvents(True) self._path = QGraphicsPathItem() self._path.setPath(path) self.addToGroup(self._path) self.set_node_color() self.set_label_color()
class EdgeItem(GraphItem): _qt_pen_styles = { 'dashed': Qt.DashLine, 'dotted': Qt.DotLine, 'solid': Qt.SolidLine, } def __init__(self, highlight_level, spline, label_center, label, from_node, to_node, parent=None, penwidth=1, edge_color=None, style='solid'): super(EdgeItem, self).__init__(highlight_level, parent) self.from_node = from_node self.from_node.add_outgoing_edge(self) self.to_node = to_node self.to_node.add_incoming_edge(self) self._default_edge_color = self._COLOR_BLACK if edge_color is not None: self._default_edge_color = edge_color self._default_text_color = self._COLOR_BLACK self._default_color = self._COLOR_BLACK self._text_brush = QBrush(self._default_color) self._shape_brush = QBrush(self._default_color) if style in ['dashed', 'dotted']: self._shape_brush = QBrush(Qt.transparent) self._label_pen = QPen() self._label_pen.setColor(self._default_text_color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._edge_pen = QPen(self._label_pen) self._edge_pen.setWidth(penwidth) self._edge_pen.setColor(self._default_edge_color) self._edge_pen.setStyle(self._qt_pen_styles.get(style, Qt.SolidLine)) self._sibling_edges = set() self._label = None if label is not None: self._label = QGraphicsSimpleTextItem(label) label_rect = self._label.boundingRect() label_rect.moveCenter(label_center) self._label.setPos(label_rect.x(), label_rect.y()) self._label.hoverEnterEvent = self._handle_hoverEnterEvent self._label.hoverLeaveEvent = self._handle_hoverLeaveEvent self._label.setAcceptHoverEvents(True) # spline specification according to http://www.graphviz.org/doc/info/attrs.html#k:splineType coordinates = spline.split(' ') # extract optional end_point end_point = None if (coordinates[0].startswith('e,')): parts = coordinates.pop(0)[2:].split(',') end_point = QPointF(float(parts[0]), -float(parts[1])) # extract optional start_point if (coordinates[0].startswith('s,')): parts = coordinates.pop(0).split(',') # first point parts = coordinates.pop(0).split(',') point = QPointF(float(parts[0]), -float(parts[1])) path = QPainterPath(point) while len(coordinates) > 2: # extract triple of points for a cubic spline parts = coordinates.pop(0).split(',') point1 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point2 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point3 = QPointF(float(parts[0]), -float(parts[1])) path.cubicTo(point1, point2, point3) self._arrow = None if end_point is not None: # draw arrow self._arrow = QGraphicsPolygonItem() polygon = QPolygonF() polygon.append(point3) offset = QPointF(end_point - point3) corner1 = QPointF(-offset.y(), offset.x()) * 0.35 corner2 = QPointF(offset.y(), -offset.x()) * 0.35 polygon.append(point3 + corner1) polygon.append(end_point) polygon.append(point3 + corner2) self._arrow.setPolygon(polygon) self._arrow.hoverEnterEvent = self._handle_hoverEnterEvent self._arrow.hoverLeaveEvent = self._handle_hoverLeaveEvent self._arrow.setAcceptHoverEvents(True) self._path = QGraphicsPathItem() self._path.setPath(path) self.addToGroup(self._path) self.set_node_color() self.set_label_color() def add_to_scene(self, scene): scene.addItem(self) if self._label is not None: scene.addItem(self._label) if self._arrow is not None: scene.addItem(self._arrow) def setToolTip(self, tool_tip): super(EdgeItem, self).setToolTip(tool_tip) if self._label is not None: self._label.setToolTip(tool_tip) if self._arrow is not None: self._arrow.setToolTip(tool_tip) def add_sibling_edge(self, edge): self._sibling_edges.add(edge) def set_node_color(self, color=None): if color is None: self._label_pen.setColor(self._default_text_color) self._text_brush.setColor(self._default_color) if self._shape_brush.isOpaque(): self._shape_brush.setColor(self._default_color) self._edge_pen.setColor(self._default_edge_color) else: self._label_pen.setColor(color) self._text_brush.setColor(color) if self._shape_brush.isOpaque(): self._shape_brush.setColor(color) self._edge_pen.setColor(color) self._path.setPen(self._edge_pen) if self._arrow is not None: self._arrow.setBrush(self._shape_brush) self._arrow.setPen(self._edge_pen) def set_label_color(self, color=None): if color is None: self._label_pen.setColor(self._default_text_color) else: self._label_pen.setColor(color) if self._label is not None: self._label.setBrush(self._text_brush) self._label.setPen(self._label_pen) def _handle_hoverEnterEvent(self, event): # hovered edge item in red self.set_node_color(self._COLOR_RED) if self._highlight_level > 1: if self.from_node != self.to_node: # from-node in blue self.from_node.set_node_color(self._COLOR_BLUE) # to-node in green self.to_node.set_node_color(self._COLOR_GREEN) else: # from-node/in-node in teal self.from_node.set_node_color(self._COLOR_TEAL) self.to_node.set_node_color(self._COLOR_TEAL) if self._highlight_level > 2: # sibling edges in orange for sibling_edge in self._sibling_edges: sibling_edge.set_node_color(self._COLOR_ORANGE) def _handle_hoverLeaveEvent(self, event): self.set_node_color() if self._highlight_level > 1: self.from_node.set_node_color() self.to_node.set_node_color() if self._highlight_level > 2: for sibling_edge in self._sibling_edges: sibling_edge.set_node_color()
class NodeItem(GraphItem): def __init__(self, highlight_level, bounding_box, label, shape, color=None, parent=None, label_pos=None, tooltip=None): super(NodeItem, self).__init__(highlight_level, parent) self._default_color = self._COLOR_BLACK if color is None else color self._brush = QBrush(self._default_color) self._label_pen = QPen() self._label_pen.setColor(self._default_color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._ellipse_pen = QPen(self._label_pen) self._ellipse_pen.setWidth(1) self._incoming_edges = set() self._outgoing_edges = set() if shape == 'box': self._graphics_item = QGraphicsRectItem(bounding_box) else: self._graphics_item = QGraphicsEllipseItem(bounding_box) self.addToGroup(self._graphics_item) self._label = QGraphicsSimpleTextItem(label) label_rect = self._label.boundingRect() if label_pos is None: label_rect.moveCenter(bounding_box.center()) else: label_rect.moveCenter(label_pos) self._label.setPos(label_rect.x(), label_rect.y()) self.addToGroup(self._label) if tooltip is not None: self.setToolTip(tooltip) self.set_node_color() self.setAcceptHoverEvents(True) self.hovershape = None def set_hovershape(self, newhovershape): self.hovershape = newhovershape def shape(self): if self.hovershape is not None: path = QPainterPath() path.addRect(self.hovershape) return path else: return super(self.__class__, self).shape() def add_incoming_edge(self, edge): self._incoming_edges.add(edge) def add_outgoing_edge(self, edge): self._outgoing_edges.add(edge) def set_node_color(self, color=None): if color is None: color = self._default_color self._brush.setColor(color) self._ellipse_pen.setColor(color) self._label_pen.setColor(color) self._graphics_item.setPen(self._ellipse_pen) self._label.setBrush(self._brush) self._label.setPen(self._label_pen) def hoverEnterEvent(self, event): # hovered node item in red self.set_node_color(self._COLOR_RED) if self._highlight_level > 1: cyclic_edges = self._incoming_edges.intersection(self._outgoing_edges) # incoming edges in blue incoming_nodes = set() for incoming_edge in self._incoming_edges.difference(cyclic_edges): incoming_edge.set_node_color(self._COLOR_BLUE) if incoming_edge.from_node != self: incoming_nodes.add(incoming_edge.from_node) # outgoing edges in green outgoing_nodes = set() for outgoing_edge in self._outgoing_edges.difference(cyclic_edges): outgoing_edge.set_node_color(self._COLOR_GREEN) if outgoing_edge.to_node != self: outgoing_nodes.add(outgoing_edge.to_node) # incoming/outgoing edges in teal for edge in cyclic_edges: edge.set_node_color(self._COLOR_TEAL) if self._highlight_level > 2: cyclic_nodes = incoming_nodes.intersection(outgoing_nodes) # incoming nodes in blue for incoming_node in incoming_nodes.difference(cyclic_nodes): incoming_node.set_node_color(self._COLOR_BLUE) # outgoing nodes in green for outgoing_node in outgoing_nodes.difference(cyclic_nodes): outgoing_node.set_node_color(self._COLOR_GREEN) # incoming/outgoing nodes in teal for node in cyclic_nodes: node.set_node_color(self._COLOR_TEAL) def hoverLeaveEvent(self, event): self.set_node_color() if self._highlight_level > 1: for incoming_edge in self._incoming_edges: incoming_edge.set_node_color() if self._highlight_level > 2 and incoming_edge.from_node != self: incoming_edge.from_node.set_node_color() for outgoing_edge in self._outgoing_edges: outgoing_edge.set_node_color() if self._highlight_level > 2 and outgoing_edge.to_node != self: outgoing_edge.to_node.set_node_color()
class DmgHtmlNodeItem(GraphItem): HIGHLIGHT_LEVEL = 1 HOVERED_COLOR = QColor(250, 0, 0) HIGHLIGHTED_COLOR = QColor(100, 100, 100) HIGHLIGHTED_PEN_WIDTH = 2.0 HIGHLIGHTED_LABEL_PEN_WIDTH = 1.0 def __init__(self, bounding_box, shape, label, label_pos=None, url=None, parent=None, **kwargs): super(DmgHtmlNodeItem, self).__init__(parent, **kwargs) self.url = url self._incoming_edges = set() self._outgoing_edges = set() self._brush = QBrush(self._color) self._label_pen = QPen() self._label_pen.setColor(self._color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._label_pen.setWidthF(self._label_pen_width) self._graphics_item_pen = QPen(self._label_pen) self._graphics_item_pen.setWidthF(self._pen_width) self._label = QGraphicsTextItem() self._label.setHtml(label) label_rectangle = self._label.boundingRect() if label_pos is None: label_rectangle.moveCenter(bounding_box.center()) else: label_rectangle.moveCenter(label_pos) self._label.setPos(label_rectangle.x(), label_rectangle.y()) self.addToGroup(self._label) self._graphics_item = ShapeFactory.create(shape, bounding_box) if ShapeFactory.message is not None: print ShapeFactory.message self.addToGroup(self._graphics_item) self._brush.setColor(self._color) self._graphics_item_pen.setColor(self._color) self._label_pen.setColor(self._color) self._graphics_item.setPen(self._graphics_item_pen) self._highlight_level = kwargs.get('highlight_level', self.HIGHLIGHT_LEVEL) self._hovered_color = kwargs.get('hovered_color', self.HOVERED_COLOR) self._highlighted_color = kwargs.get('highlighted_color', self.HIGHLIGHTED_COLOR) self._highlighted_pen_width = kwargs.get('highlighted_pen_width', self.HIGHLIGHTED_PEN_WIDTH) self._highlighted_label_pen_width = kwargs.get('highlighted_label_pen_width', self.HIGHLIGHTED_LABEL_PEN_WIDTH) self.hover_shape = None self.setAcceptHoverEvents(True) def add_incoming_edge(self, edge): self._incoming_edges.add(edge) def add_outgoing_edge(self, edge): self._outgoing_edges.add(edge) def set_color(self, color=None): if color is None: color = self._color self._brush.setColor(color) self._graphics_item_pen.setColor(color) self._label.setDefaultTextColor(color) self._graphics_item.setPen(self._graphics_item_pen) def set_hover_shape(self, shape): self.hover_shape = shape def shape(self): if self.hover_shape is not None: path = QPainterPath() path.addRect(self.hover_shape) return path return super(GraphItem, self).shape() def hoverEnterEvent(self, event): self.set_color(self._highlighted_color) self._highlight_connections() def hoverLeaveEvent(self, event): self.set_color() self._highlight_connections(False) def _highlight_connections(self, highlighted=True): if highlighted: if self._highlight_level > 1: cyclic_edges = self._incoming_edges.intersection(self._outgoing_edges) # incoming edges in blue incoming_nodes = set() for incoming_edge in self._incoming_edges.difference(cyclic_edges): incoming_edge.set_color(self.COLOR_BLUE) if incoming_edge.from_node != self: incoming_nodes.add(incoming_edge.from_node) # outgoing edges in green outgoing_nodes = set() for outgoing_edge in self._outgoing_edges.difference(cyclic_edges): outgoing_edge.set_color(self.COLOR_GREEN) if outgoing_edge.to_node != self: outgoing_nodes.add(outgoing_edge.to_node) # incoming/outgoing edges in teal for edge in cyclic_edges: edge.set_color(self.COLOR_TEAL) if self._highlight_level > 2: cyclic_nodes = incoming_nodes.intersection(outgoing_nodes) # incoming nodes in blue for incoming_node in incoming_nodes.difference(cyclic_nodes): incoming_node.set_color(self.COLOR_BLUE) # outgoing nodes in green for outgoing_node in outgoing_nodes.difference(cyclic_nodes): outgoing_node.set_color(self.COLOR_GREEN) # incoming/outgoing nodes in teal for node in cyclic_nodes: node.set_color(self.COLOR_TEAL) else: if self._highlight_level > 1: for incoming_edge in self._incoming_edges: incoming_edge.set_color() if self.highlight_level > 2 and incoming_edge.from_node != self: incoming_edge.from_node.set_color() for outgoing_edge in self._outgoing_edges: outgoing_edge.set_color() if self.highlight_level > 2 and outgoing_edge.to_node != self: outgoing_edge.to_node.set_color() def highlight(self, highlighted=True): if highlighted: self._graphics_item_pen.setWidthF(self._highlighted_pen_width) else: self._graphics_item_pen.setWidthF(self._pen_width) self._graphics_item.setPen(self._graphics_item_pen)
def paint(self, painter, option, widget): brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(QColor("red")) painter.fillRect(self.rect(), brush)