def texting(self): # image = self.image.copy() # cv2.putText(image, # self.ui.textEdit_edit.toPlainText(), # (10, 10), # cv2.FONT_HERSHEY_SIMPLEX, # 0.6, (0, 0, 0), lineType=cv2.LINE_AA) # qpixmap = mat2qpixmap(image) # self.scene_edit.clear() # self.scene_edit.addPixmap(qpixmap) # self.scene_edit.update() text = self.ui.textEdit_edit.toPlainText() self.scene_edit.clear() self.scene_edit.addPixmap(self.qPixmap) qText = QGraphicsTextItem() qText.setDefaultTextColor(QColor(0, 0, 0)) qText.setPlainText(text) qText.setFont(self.font) qPixmapWidth = self.qPixmap.width() qTextWidth = qText.boundingRect().width() qPixmapHeight = self.qPixmap.height() qTextHeigt = qText.boundingRect().height() posX = (qPixmapWidth - qTextWidth) / 2 + self.posX_default posY = (qPixmapHeight - qTextHeigt) / 2 + self.posY_default qText.setPos(posX, posY) self.scene_edit.addItem(qText) self.scene_edit.update()
class LabelItem(GraphicsItem): font_bold_italic = None def __init__(self, model_item: SimulatorProtocolLabel, parent=None): assert isinstance(model_item, SimulatorProtocolLabel) super().__init__(model_item=model_item, parent=parent) self.name = QGraphicsTextItem(self) self.name.setFont(GraphicsItem.font) def update_flags(self): if self.scene().mode == 1: self.set_flags(is_selectable=True, accept_hover_events=True) def update_numbering(self): pass def paint(self, painter, option, widget): painter.setBrush(constants.LABEL_COLORS[self.model_item.color_index]) painter.drawRect(self.boundingRect()) if self.scene().mode == 1: super().paint(painter, option, widget) def boundingRect(self): return self.childrenBoundingRect() def refresh(self): self.name.setPlainText(self.model_item.name)
def __init__(self, position, angle, arrow_size, value, unit): super(StressRepresentation, self).__init__() arrow_line = QLineF() arrow_line.setP1(position) arrow_line.setLength(arrow_size) arrow_line.setAngle(angle) arrow = QGraphicsLineItem() arrow.setLine(arrow_line) self.addToGroup(arrow) arrow_head1_line = QLineF() arrow_head1_line.setP1(arrow_line.p1()) arrow_head1_line.setLength(arrow_size / 4) arrow_head1_line.setAngle(arrow_line.angle() + 45) arrow_head1 = QGraphicsLineItem() arrow_head1.setLine(arrow_head1_line) self.addToGroup(arrow_head1) arrow_head2_line = QLineF() arrow_head2_line.setP1(arrow_line.p1()) arrow_head2_line.setLength(arrow_size / 4) arrow_head2_line.setAngle(arrow_line.angle() - 45) arrow_head2 = QGraphicsLineItem() arrow_head2.setLine(arrow_head2_line) self.addToGroup(arrow_head2) text = QGraphicsTextItem() text.setPlainText(f'{str(value)}{unit}') text.setPos(arrow_line.p2()) self.addToGroup(text) self._set_color()
def __init__(self, position, scene, row, style=Qt.SolidLine, rect=None, matrix=QTransform()): super(BoxItem, self).__init__() self.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsFocusable) x = position.x() y = position.y() Width = row["Width"] Height = row["Height"] #print(row["Item"]) if rect is None: rect = QRectF(-10 * PointSize, -PointSize, Width, Height) self.rect = rect self.style = style self.setPos(x + 100, y + 10) #self.setTransform(matrix) text = QGraphicsTextItem() text.setPlainText(row["Bin"]) text.setPos(x, y) scene.addItem(self) scene.addItem(text)
class DSO_range(QGraphicsPolygonItem): def __init__(self, parent, text="", color=Qt.white, text_col=Qt.black): super().__init__(None) polygon = QPolygonF() self.width = 175 self.height = 24 polygon.append(QPointF(0, 0)) polygon.append(QPointF(0, self.height)) polygon.append(QPointF(self.width, self.height)) polygon.append(QPointF(self.width, 0)) self.setPolygon(polygon) # we want black background bg = QBrush() col = QColor(color) col.setAlpha(200) bg.setColor(col) bg.setStyle(Qt.SolidPattern) self.setBrush(bg) self.text = QGraphicsTextItem(self) self.text.setDefaultTextColor(QColor(text_col)) self.text.setPlainText(text) self.show() def setText(self, text): self.text.setPlainText(text)
def __init__(self, parent, name="", color=Qt.white, typ="X"): super().__init__(None) polygon = QPolygonF() if typ == "Y": polygon.append(QPointF(0, 0)) polygon.append(QPointF(0, 16)) polygon.append(QPointF(12, 16)) polygon.append(QPointF(20, 8)) polygon.append(QPointF(12, 0)) if typ == "X": polygon.append(QPointF(0, 0)) polygon.append(QPointF(6, 6)) polygon.append(QPointF(12, 0)) self.setPolygon(polygon) # we want black background bg = QBrush() col = QColor(color) col.setAlpha(200) bg.setColor(col) bg.setStyle(Qt.SolidPattern) self.setBrush(bg) if typ == "Y": text = QGraphicsTextItem(self) text.setPlainText(name) text.setY(text.y() - 4) self.typ = typ self.show()
def draw_vp(self, point, index): key = self.vp_eng.get_key_from_id(index) print("drawing at {} {}".format(point, key)) x, y = point r = 10 graphic_view = self.get_graphic_view() graphic_view.vp_drawn_callback(point, index) self.vp_eng.add_vpoint(index, point) circle_item = QGraphicsEllipseItem(x - r, y - r, 2 * r, 2 * r) circle_item.setPen( QPen(self.get_pen_color(), 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) circle_item.setBrush(QBrush(Qt.black, Qt.SolidPattern)) text_item = QGraphicsTextItem() text_item.setPos(x, y) text_item.setPlainText("V{}".format(key)) if self.vp_dict[key]["vp"] is not None: self.removeItem(self.vp_dict[key]["vp"]) self.removeItem(self.vp_dict[key]["label"]) self.vp_dict[key]["vp"] = circle_item self.vp_dict[key]["label"] = text_item self.addItem(circle_item) self.addItem(text_item)
def _showClue(self, i, j): """ Graphical representation of a summation square is created here. """ x = j * self.SQUARE_SIZE y = i * self.SQUARE_SIZE self.scene.addRect(x, y, self.SQUARE_SIZE, self.SQUARE_SIZE, QPen(Qt.black, 1, Qt.SolidLine), QBrush(Qt.gray, Qt.SolidPattern)) self.scene.addLine(x, y, x + self.SQUARE_SIZE, y + self.SQUARE_SIZE, QPen(Qt.black, 1, Qt.SolidLine)) hTextItem = QGraphicsTextItem('') vTextItem = QGraphicsTextItem('') horizontal = (self.model.grid[i][j])[self.model.HORIZONTAL] vertical = (self.model.grid[i][j])[self.model.VERTICAL] if horizontal is not None: hTextItem.setPlainText(str(horizontal)) if vertical is not None: vTextItem.setPlainText(str(vertical)) hTextItem.setPos(x + self.SQUARE_SIZE / 2, y + self.SQUARE_SIZE / 4) vTextItem.setPos(x + self.SQUARE_SIZE / 4, y + self.SQUARE_SIZE / 2) self.scene.addItem(hTextItem) self.scene.addItem(vTextItem)
def graficarArbol(self, ambiente, posX, posY): # Crear los esquemas ara utilizar la libreria nodo1 = QPen(Qt.black) nodo2 = QPen(Qt.green) # Asignar coordenada X y Y al nuevo ambiente ambiente.x = posX ambiente.y = self.y # Crear un modelo de ambiente (nodo) ambiente.dibujarN = QRect(ambiente.x, ambiente.y, ambiente.dimension, ambiente.dimension) # Definir si el ambiente esta activo para marcarlo con color diferente a los demas if ambiente.nActivo: self.panelDibujo.addEllipse(ambiente.x, ambiente.y, ambiente.dimension, ambiente.dimension, nodo2) else: self.panelDibujo.addEllipse(ambiente.x, ambiente.y, ambiente.dimension, ambiente.dimension, nodo1) # Informacion que tendra el ambiente cadena = QGraphicsTextItem() cadena.setPlainText(str(ambiente.nombre)) cadena.setPos(QPointF(ambiente.x + 2, ambiente.y - 3)) posX += 50 # Graficar los hijos del ambiente actual for i in ambiente.hijos: self.y += 40 self.graficarArbol(i, posX, self.y)
def __drawPoint(self, x, y, index): #横线 line1 = QGraphicsLineItem() line1.setPen(self.pen) line1.setLine(x - self.lineRadius, y, x + self.lineRadius, y) #竖线 line2 = QGraphicsLineItem() line2.setPen(self.pen) line2.setLine(x, y - self.lineRadius, x, y + self.lineRadius) #文字说明 text = QGraphicsTextItem() text.setDefaultTextColor(Qt.blue) text.setFont(self.font) text.setPlainText(self.pointsName[index]) text.setPos(x, y) #放到组中 pointGroup = QGraphicsItemGroup() pointGroup.addToGroup(line1) pointGroup.addToGroup(line2) pointGroup.addToGroup(text) #显示 if self.pointsItem[index] is not None: self.scene.removeItem(self.pointsItem[index]) #保存到字典 self.pointsItem[index] = pointGroup #显示该点 self.scene.addItem(self.pointsItem[index])
class GraphicItem(QGraphicsPixmapItem): def __init__(self, parent=None, text='', left=True): super().__init__(parent) self.pix = QPixmap("./res/Model.png") self.width = 55 self.height = 55 self.setPixmap(self.pix.scaled(self.width, self.height)) self.setFlag(QGraphicsItem.ItemIsSelectable) self.setFlag(QGraphicsItem.ItemIsMovable) self.left = left self.index = 0 self.text = QGraphicsTextItem(self) self.text.setPlainText(text) if self.left: self.text.setDefaultTextColor(QColor(236, 190, 92)) else: self.text.setDefaultTextColor(QColor(255, 59, 48)) font = QFont() font.setBold(True) font.setPixelSize(16) self.text.setFont(font) def mouseMoveEvent(self, event): super().mouseMoveEvent(event) # update selected node and its edge if self.isSelected(): for gr_edge in self.scene().edges: gr_edge.edge_wrap.update_positions()
def __showCircle(self): ratio = 3 pen = QPen() pen.setBrush(Qt.red) pen.setWidth(0.01) font = QFont() font.setPointSize(200 * ratio) self.scene.clear() for i in range(len(self.pointsXYItem)): (x, y) = self.pointsXYItem[i] r = self.radius[i] * ratio circleItem = QGraphicsEllipseItem(x - r, y - r, 2 * r, 2 * r) circleItem.setPen(pen) self.scene.addItem(circleItem) strItem = QGraphicsTextItem() strItem.setDefaultTextColor(Qt.blue) strItem.setFont(font) strItem.setPlainText(self.pointsName[i]) strItem.setPos(x, y) self.scene.addItem(strItem)
def setPlainText(self, text): '''Sets the item's text to text. Argument(s): text (str): New text ''' QGraphicsTextItem.setPlainText(self, text) self.parentItem().updateShapeAndEdges()
def loadText(self): self.scene.clear() noImageTxt = QGraphicsTextItem() noImageTxt.setPlainText( u"Wählen Sie ein repräsentatives Luftbild aus ...") self.rect = noImageTxt.boundingRect() self.scene.addItem(noImageTxt) self.scene.setSceneRect(self.rect) self.uiRepresentativeImageView.fitInView(self.rect, Qt.KeepAspectRatio)
def create_winner_label(self): w = QGraphicsTextItem() w.setPlainText("%s" % self.mini_game_winner) game_board = self.parent() print(game_board) w.setFont(QFont('SansSerif', self.fonts[self.mini_game_winner])) w.setDefaultTextColor(Qt.black) w.setPos(self.x(), self.y()) w.setVisible(False) return w
def display_text(message, view: QGraphicsView): text = QGraphicsTextItem() text.setPos(0, 0) text.setPlainText(message.text) text.setTextWidth(view.width()) scene = QGraphicsScene() scene.addItem(text) view.setAlignment(Qt.AlignTop | Qt.AlignLeft) view.setScene(scene)
def printAttributes(self, background, border, text): """ Prints the attributes of the node The attributes are a key, value pair :param background: background color of the node :param border: border color for the node :param text: text color for the node """ y = self.y() + self.headerHeight x = self.x() self.attributesHeight = 0 for k, v in self.node.attributes.items(): key = QGraphicsTextItem() key.setFont(Configuration.font) key.setDefaultTextColor(QColor(text)) key.setTextWidth(100) key.setPlainText(k) keyHeight = int(key.boundingRect().height() / 20 + 0.5) * 20 value = QGraphicsTextItem() value.setFont(Configuration.font) value.setDefaultTextColor(QColor(text)) value.setTextWidth(100) value.setPlainText(v) valueHeight = int(value.boundingRect().height() / 20 + 0.5) * 20 height = valueHeight if valueHeight > keyHeight else keyHeight keyRect = QGraphicsRectItem() keyRect.setRect(x, y, 100, height) valueRect = QGraphicsRectItem() valueRect.setRect(x + 100, y, 100, height) keyRect.setBrush(QBrush(QColor(background))) valueRect.setBrush(QBrush(QColor(background))) keyRect.setPen(QPen(QColor(border), 2)) valueRect.setPen(QPen(QColor(border), 2)) key.setPos(x, y - 2) value.setPos(x + 100, y - 2) self.attributes.addToGroup(keyRect) self.attributes.addToGroup(valueRect) self.attributes.addToGroup(key) self.attributes.addToGroup(value) y = y + height self.attributesHeight += height self.addToGroup(self.attributes)
class PickingStation(VisualizerGraphicItem): def __init__(self, ID=0, x=0, y=0): super(self.__class__, self).__init__(ID, x, y) self._kind_name = 'pickingStation' self._items = [] self._graphics_item = QGraphicsRectItem(self) self._items.append(QGraphicsRectItem(self._graphics_item)) self._items.append(QGraphicsRectItem(self._graphics_item)) self._text = QGraphicsTextItem(self._graphics_item) def set_rect(self, rect): scale = config.get('display', 'id_font_scale') bold = config.get('display', 'id_font_bold') self._text.setFont(QFont('', rect.width() * 0.08 * scale)) self._text.setPos(rect.x(), rect.y() + 0.6 * rect.height()) self._text.setDefaultTextColor( QColor(config.get('display', 'id_font_color'))) if self._display_mode == 0: if bold: self._text.setHtml('<b>P(' + str(self._id) + ')</b>') else: self._text.setHtml('P(' + str(self._id) + ')') self._graphics_item.setRect(rect.x(), rect.y(), rect.width(), rect.height()) self._items[0].setRect(rect.x() + rect.width() / 5, rect.y(), rect.width() / 5, rect.height()) self._items[1].setRect(rect.x() + rect.width() / 5 * 3, rect.y(), rect.width() / 5, rect.height()) elif self._display_mode == 1: self._text.setPlainText('') self._graphics_item.setRect(rect.x(), rect.y(), rect.width(), rect.height()) self._items[0].setRect(rect.x() + rect.width() / 5, rect.y(), rect.width() / 5, rect.height()) self._items[1].setRect(rect.x() + rect.width() / 5 * 3, rect.y(), rect.width() / 5, rect.height()) def determine_color(self, number, count, pattern=None): color = self._colors[0] color2 = self._colors[1] color.setAlpha(150) color2.setAlpha(150) brush = QBrush(color) brush2 = QBrush(color2) self._graphics_item.setBrush(brush) self._items[0].setBrush(brush2) self._items[1].setBrush(brush2) def get_rect(self): return self._graphics_item.rect()
class ParticipantItem(QGraphicsItem): def __init__(self, model_item: Participant, parent=None): super().__init__(parent) self.model_item = model_item self.text = QGraphicsTextItem(self) self.line = QGraphicsLineItem(self) self.line.setPen( QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) self.refresh() def update_position(self, x_pos=-1, y_pos=-1): if x_pos == -1: x_pos = self.x_pos() if y_pos == -1: y_pos = self.line.line().y2() self.text.setPos(x_pos - (self.text.boundingRect().width() / 2), 0) self.line.setLine(x_pos, 30, x_pos, y_pos) def x_pos(self): return self.line.line().x1() def width(self): return self.boundingRect().width() def refresh(self): self.text.setPlainText( "?" if not self.model_item else self.model_item.shortname) if hasattr(self.model_item, "simulate") and self.model_item.simulate: font = QFont() font.setBold(True) self.text.setFont(font) self.text.setDefaultTextColor(Qt.darkGreen) self.line.setPen( QPen(Qt.darkGreen, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) else: self.text.setFont(QFont()) self.text.setDefaultTextColor(constants.LINECOLOR) self.line.setPen( QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) def boundingRect(self): return self.childrenBoundingRect() def paint(self, painter, option, widget): pass
def set_functions_list(self, functionsList, prefix="", sufix=""): self.funtionsList = functionsList self.funtionsListItems = [] self.maxHeight = 0 tempHeight = 0 for element in functionsList: tempElement = QGraphicsTextItem(self) tempElement.setPlainText(prefix + element + sufix) tempElement.setPos(0, tempHeight) tempHeight += tempElement.document().size().height() if self.maxWidth < tempElement.document().size().width(): self.maxWidth = tempElement.document().size().width() self.funtionsListItems.append(tempElement) self.maxHeight = tempHeight
class ParticipantItem(QGraphicsItem): def __init__(self, model_item: Participant, parent=None): super().__init__(parent) self.model_item = model_item self.text = QGraphicsTextItem(self) self.line = QGraphicsLineItem(self) self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) self.refresh() def update_position(self, x_pos=-1, y_pos=-1): if x_pos == -1: x_pos = self.x_pos() if y_pos == -1: y_pos = self.line.line().y2() self.text.setPos(x_pos - (self.text.boundingRect().width() / 2), 0) self.line.setLine(x_pos, 30, x_pos, y_pos) def x_pos(self): return self.line.line().x1() def width(self): return self.boundingRect().width() def refresh(self): self.text.setPlainText("?" if not self.model_item else self.model_item.shortname) if hasattr(self.model_item, "simulate") and self.model_item.simulate: font = QFont() font.setBold(True) self.text.setFont(font) self.text.setDefaultTextColor(Qt.darkGreen) self.line.setPen(QPen(Qt.darkGreen, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) else: self.text.setFont(QFont()) self.text.setDefaultTextColor(constants.LINECOLOR) self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) def boundingRect(self): return self.childrenBoundingRect() def paint(self, painter, option, widget): pass
class CTChartView(QChartView): def __init__(self, parent): super().__init__(parent) self.setRenderHint(QPainter.Antialiasing) self.chart = self.chart() self.chart.legend().setVisible(False) self._chart_loaded = False self._chart_horizontal_line = QGraphicsLineItem(0, 0, 0, 0) pen = self._chart_horizontal_line.pen() pen.setStyle(Qt.DashLine) self._chart_horizontal_line.setPen(pen) self.scene().addItem(self._chart_horizontal_line) self._chart_vertical_line = QGraphicsLineItem(0, 0, 0, 0) self._chart_vertical_line.setPen(pen) self.scene().addItem(self._chart_vertical_line) self._chart_tooltip = QGraphicsTextItem("") self._chart_tooltip.setPos(100, 20) self.scene().addItem(self._chart_tooltip) self._chart_crosshair = QGraphicsTextItem("") self._chart_crosshair.setPos(600, 20) self.scene().addItem(self._chart_crosshair) margins = self.chart.margins() margins.setTop(margins.top() + 80) self.chart.setMargins(margins) def mouseMoveEvent(self, event): self._chart_horizontal_line.setLine(0, event.pos().y(), self.width(), event.pos().y()) self._chart_vertical_line.setLine(event.pos().x(), 0, event.pos().x(), self.height()) crosshair_coordinates = self.chart.mapToValue(event.pos(), self.chart.series()[0]) self._chart_crosshair.setPlainText( " time:\t{0}\n level:\t{1:.8f}".format( datetime.fromtimestamp( int(crosshair_coordinates.x() / 1000)).strftime('%Y-%m-%d %H:%M:%S'), crosshair_coordinates.y())) return QChartView.mouseMoveEvent(self, event)
class Bar(QGraphicsRectItem): def __init__(self, parent=None): super().__init__(parent) self.max_val = 1 self.current_val = 1 self.WIDTH = parent.pixmap().width() if parent else 60 self.setRect(parent.pos().x(), parent.pos().y(), self.WIDTH, 8) self.setBrush(Qt.red) self.text = QGraphicsTextItem(self) self.text.setDefaultTextColor(Qt.white) font = QFont('comic sans', 7) self.text.setFont(font) self.text.setPos(self.x(), self.y() - 7) def update_bar(self): # updates the bar graphics to the current amount of fullnes fill_fraction = float(self.current_val) / self.max_val self.text.setPlainText('{} / {}'.format(self.current_val, self.max_val)) self.setRect(self.rect().x(), self.rect().y(), fill_fraction * self.WIDTH, 8) def get_current_val(self): return self.current_val def set_current_val(self, value): self.current_val = value def set_max_val(self, value): self.max_val = value def increment(self, amount): # increase the amount the bar is filled and updates it self.current_val += amount self.update_bar() def decrement(self, amount): # decreases and updates self.current_val -= amount self.update_bar()
def actually_show_text(self, data): text_item = QGraphicsTextItem() text_item.setZValue(5) if len(data) >= 8 and data[7] != None: text_item.setDefaultTextColor(QColor(data[7])) else: text_item.setDefaultTextColor(QColor("#FFFFFF")) text_item.setX(data[2]) text_item.setY(data[3]) text_item.setTextWidth(data[4]) text_item.setPlainText(data[5]) temp_font = text_item.font() temp_font.setPointSize(data[6]) text_item.setFont(temp_font) self.addItem(text_item) self.texts[data[1]] = text_item self.call_next_action()
def drawAxis(self, data, points): xmin = data['xmin'] xmax = data['xmax'] ymin = data['ymin'] ymax = data['ymax'] xmarg = data['xmarg'] ymarg = data['xmarg'] xscale = data['xscale'] yscale = data['yscale'] scene = self.uiFunctionGraph.scene() scene.addLine(xmarg - 10, ymarg + 10, (xmax - xmin) * xscale + xmarg + 10, ymarg + 10) scene.addLine((xmax - xmin) * xscale + xmarg + 8, ymarg + 8, (xmax - xmin) * xscale + xmarg + 10, ymarg + 10) scene.addLine((xmax - xmin) * xscale + xmarg + 8, ymarg + 13, (xmax - xmin) * xscale + xmarg + 10, ymarg + 11) scene.addLine(xmarg - 10, ymarg + 10, xmarg - 10, (ymax - ymin) * yscale + ymarg - 10) scene.addLine(xmarg - 8, (ymax - ymin) * yscale + ymarg - 9, xmarg - 10, (ymax - ymin) * yscale + ymarg - 11) scene.addLine(xmarg - 12, (ymax - ymin) * yscale + ymarg - 8, xmarg - 10, (ymax - ymin) * yscale + ymarg - 10) y = ymin step = (ymax - ymin) / 4 for i in range(5): scene.addLine(xmarg - 12, (y - ymin) * yscale + ymarg, xmarg - 8, (y - ymin) * yscale + ymarg) text = QGraphicsTextItem() text.setPos(0, (y - ymin) * yscale + ymarg - 7) text.setPlainText('%s' % format(round(y, 3), '.3f')) text.setFont(QFont('Sans', 6)) scene.addItem(text) y += step x = xmin step = (xmax - xmin) / 19 for i in range(20): scene.addLine((x - xmin) * xscale + xmarg, ymarg + 8, (x - xmin) * xscale + xmarg, ymarg + 12) text = QGraphicsTextItem() text.setPos((x - xmin) * xscale + xmarg - 14, ymarg + 10) text.setPlainText('%s' % format(round(x, 3), '.3f')) text.setFont(QFont('Sans', 6)) scene.addItem(text) x += step
class LabelItem(GraphicsItem): font_bold_italic = None def __init__(self, model_item: SimulatorProtocolLabel, parent=None): assert isinstance(model_item, SimulatorProtocolLabel) super().__init__(model_item=model_item, parent=parent) self.name = QGraphicsTextItem(self) self.name.setFont(self.font) def update_flags(self): if self.scene().mode == 1: self.set_flags(is_selectable=True, accept_hover_events=True) def update_numbering(self): pass def paint(self, painter: QPainter, option, widget): style = Qt.DotLine if self.model_item.has_live_input else Qt.SolidLine pen = QPen(constants.LINECOLOR, 1, style) painter.setPen(pen) painter.setBrush(constants.LABEL_COLORS[self.model_item.color_index]) painter.drawRect(self.boundingRect()) if self.scene().mode == 1: super().paint(painter, option, widget) def boundingRect(self): return self.childrenBoundingRect() def refresh(self): self.name.setPlainText(self.model_item.name) if self.model_item.is_checksum_label: value_type = "Checksum" else: value_type = SimulatorProtocolLabel.VALUE_TYPES[ self.model_item.value_type_index] tooltip = "Value type:<br><b>{}</b>".format(value_type) self.setToolTip(tooltip)
class Video(QMainWindow): def __init__(self): super(Video, self).__init__() self.resize(1920, 1080) # ITEM self._item = QGraphicsVideoItem() self._textItem = QGraphicsTextItem() self._view = QGraphicsView() self._scene = QGraphicsScene() self._view.resize(1920, 1080) self._view.setScene(self._scene) self._scene.addItem(self._item) self._scene.addItem(self._textItem) self._textItem.setPlainText('SRT TEXT') self._textItem.setDefaultTextColor(Qt.red) font = self._textItem.font() font.setPixelSize(50) self._textItem.setFont(font) self._view.show() self._item.setSize(QSizeF(1920, 1080)) self._player = QMediaPlayer(self) self._player.setMedia( QMediaContent( QUrl.fromLocalFile( '/Users/huangkai/Documents/PycharmProjects/AllTest/Qt插入背景/AddVideos/Videos/yellow.mov' ))) self._player.setVideoOutput(self._item) self._player.play() self.setCentralWidget(self._view) self._item.setPos(400, 500) # BUTTON self._btn = QPushButton(self) self._btn.resize(100, 50) self._btn.move(500, 500) self._btn.setText('test') self._btn.clicked.connect(self._change_text) def _change_text(self): self._textItem.setPlainText('Fighting')
def mouseReleaseEvent(self, event): x1 = self.orig_point.x() y1 = self.orig_point.y() x2 = event.scenePos().x() y2 = event.scenePos().y() line = (x1, y1, x2, y2) graphic_view = self.get_graphic_view() if self.scene_mode == self.MODE_DRAW: self.vp_eng.add_line(line, self.on_line_added) graphic_view.viewport().setCursor(Qt.ArrowCursor) elif self.scene_mode == self.MODE_PRESS: point = [x1, y1] index = graphic_view.coordinate_index self.vp_eng.add_coordinate(index, point) graphic_view.coordinate_set_callback(point) circle_item = QGraphicsEllipseItem(x1 - 5, y1 - 5, 10, 10) circle_item.setPen( QPen(self.get_pen_color(), 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) circle_item.setBrush(QBrush(Qt.black, Qt.SolidPattern)) text_item = QGraphicsTextItem() text_item.setPos(x1, y1) text_item.setPlainText("Point " + str(index + 1)) if len(self.points) <= index: self.points.append(circle_item) self.point_labels.append(text_item) else: self.removeItem(self.points.pop(index)) self.points.insert(index, circle_item) self.removeItem(self.point_labels.pop(index)) self.point_labels.insert(index, text_item) self.addItem(circle_item) self.addItem(text_item) self.scene_mode = self.MODE_IDLE
class QdGraphicsPixmapItem(QGraphicsPixmapItem): def __init__(self, path, size, parent=None): QGraphicsPixmapItem.__init__(self, parent) self._path = path self._loaded = False self._text = QGraphicsTextItem(self) self._text.setFont(QFont("Arial", 14)) self._text.setPlainText(os.path.basename(path)) self._text.setPos(0, size.height()) self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape) self.setFlags(self.flags() | QGraphicsItem.ItemIsSelectable ) # | QtGui.QGraphicsItem.ItemIsMovable ) def setImage(self, image): self.setPixmap(QPixmap.fromImage(image)) self._text.setPos(0, self.boundingRect().height()) self._loaded = True def setPlainText(self, text): self._text.setPlainText(text) def mouseDoubleClickEvent(self, event): if event.button() == Qt.LeftButton: self.viewImage() #scene = self.scene() #scene.emit(SIGNAL("doubleClicked(QString)"), self._path) #scene.doubleClicked.emit(self._path) QGraphicsPixmapItem.mouseDoubleClickEvent(self, event) def viewImage(self): if os.path.isfile(self._path): OpenFileOrFolder(self._path) else: QMessageBox.warning( self, "Bild", u"Bild unter {0} nicht vorhanden".format(self._path))
class ParticipantItem(QGraphicsItem): def __init__(self, model_item: Participant, parent=None): super().__init__(parent) self.model_item = model_item self.text = QGraphicsTextItem(self) self.line = QGraphicsLineItem(self) self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) self.refresh() def update_position(self, x_pos=-1, y_pos=-1): if x_pos == -1: x_pos = self.x_pos() if y_pos == -1: y_pos = self.line.line().y2() self.text.setPos(x_pos - (self.text.boundingRect().width() / 2), 0) self.line.setLine(x_pos, 30, x_pos, y_pos) def x_pos(self): return self.line.line().x1() def width(self): return self.boundingRect().width() def refresh(self): self.text.setPlainText("?" if not self.model_item else self.model_item.shortname) def boundingRect(self): return self.childrenBoundingRect() def paint(self, painter, option, widget): pass
def addCircle(self, index, points, r): (x, y) = points circleItem = QGraphicsEllipseItem(x - r, y - r, 2 * r, 2 * r) circleItem.setPen(self.pen) # self.scene.addItem(circleItem) #横线 line1 = QGraphicsLineItem() line1.setPen(self.pen) line1.setLine(x - self.lineRadius, y, x + self.lineRadius, y) #竖线 line2 = QGraphicsLineItem() line2.setPen(self.pen) line2.setLine(x, y - self.lineRadius, x, y + self.lineRadius) #文字说明 text = QGraphicsTextItem() text.setDefaultTextColor(Qt.blue) text.setFont(self.font) text.setPlainText(str(self.names[index])) text.setPos(x, y) #放到组中 pointGroup = QGraphicsItemGroup() pointGroup.addToGroup(line1) pointGroup.addToGroup(line2) pointGroup.addToGroup(text) pointGroup.addToGroup(circleItem) #显示该点 self.scene.addItem(pointGroup) self.pointsItem.append(pointGroup)
class KeyWidget(QGraphicsRectItem): def __init__(self, rect: QRect, idx: int, note: str): super().__init__(rect.x(), rect.y(), rect.width(), rect.height()) self.rect = rect self.idx = idx self.note = note self.label = None if note in WHITE_KEYS: self.setBrush(WHITE_KEY_COLOR) # set the label self.label = QGraphicsTextItem() self.label.setDefaultTextColor(Qt.black) # font = self.label.font() # font.setBold(True) # self.label.setFont(font) self.label.setZValue(100) self.label.setPlainText(note) self.label.setPos( self.rect.x() + self.rect.width() / 2 - self.label.boundingRect().width() / 2, self.rect.y() + self.rect.height() * 0.8) else: self.setBrush(Qt.black) def press(self, out_of_range=False): if out_of_range: self.setBrush(Qt.yellow) else: self.setBrush(Qt.gray) def release(self): if self.note in WHITE_KEYS: self.setBrush(WHITE_KEY_COLOR) else: self.setBrush(BLACK_KEY_COLOR)
class MessageItem(GraphicsItem): def __init__(self, model_item: SimulatorMessage, parent=None): assert isinstance(model_item, SimulatorMessage) super().__init__(model_item=model_item, parent=parent) self.setFlag(QGraphicsItem.ItemIsPanel, True) self.arrow = MessageArrowItem(self) self.repeat_text = QGraphicsTextItem(self) self.repeat_text.setFont(self.font) def update_flags(self): if self.scene().mode == 0: self.set_flags(is_selectable=True, is_movable=True, accept_hover_events=True, accept_drops=True) def width(self): labels = self.labels() width = self.number.boundingRect().width() # width += 5 width += sum([lbl.boundingRect().width() for lbl in labels]) width += 5 * (len(labels) - 1) width += self.repeat_text.boundingRect().width() return width def refresh(self): self.repeat_text.setPlainText("(" + str(self.model_item.repeat) + "x)" if self.model_item.repeat > 1 else "") def labels(self): self.refresh_unlabeled_range_marker() unlabeled_range_items = [uri for uri in self.childItems() if isinstance(uri, UnlabeledRangeItem)] result = [] start = 0 i = 0 message = self.model_item if len(message) and not message.message_type: result.append(unlabeled_range_items[0]) else: for lbl in message.message_type: if lbl.start > start: result.append(unlabeled_range_items[i]) i += 1 result.append(self.scene().model_to_scene(lbl)) start = lbl.end if start < len(message): result.append(unlabeled_range_items[i]) return result def refresh_unlabeled_range_marker(self): msg = self.model_item urm = [item for item in self.childItems() if isinstance(item, UnlabeledRangeItem)] if len(msg): num_unlabeled_ranges = len(msg.message_type.unlabeled_ranges) if msg.message_type and msg.message_type[-1].end >= len(msg): num_unlabeled_ranges -= 1 else: num_unlabeled_ranges = 0 if len(urm) < num_unlabeled_ranges: for i in range(num_unlabeled_ranges - len(urm)): UnlabeledRangeItem(self) else: for i in range(len(urm) - num_unlabeled_ranges): self.scene().removeItem(urm[i]) def update_position(self, x_pos, y_pos): labels = self.labels() self.setPos(QPointF(x_pos, y_pos)) p_source = self.mapFromItem(self.source.line, self.source.line.line().p1()) p_destination = self.mapFromItem(self.destination.line, self.destination.line.line().p1()) arrow_width = abs(p_source.x() - p_destination.x()) start_x = min(p_source.x(), p_destination.x()) start_x += (arrow_width - self.width()) / 2 start_y = 0 self.number.setPos(start_x, start_y) start_x += self.number.boundingRect().width() for label in labels: label.setPos(start_x, start_y) start_x += label.boundingRect().width() + 5 self.repeat_text.setPos(start_x, start_y) if labels: start_y += labels[0].boundingRect().height() + 5 else: start_y += 26 self.arrow.setLine(p_source.x(), start_y, p_destination.x(), start_y) super().update_position(x_pos, y_pos) @property def source(self): return self.scene().participants_dict[self.model_item.participant] @property def destination(self): return self.scene().participants_dict[self.model_item.destination]
class RuleConditionItem(GraphicsItem): def __init__(self, model_item: SimulatorRuleCondition, parent=None): assert isinstance(model_item, SimulatorRuleCondition) super().__init__(model_item=model_item, parent=parent) self.number.setFont(self.font_bold) self.text = QGraphicsTextItem(self) self.text.setPlainText(self.model_item.type.value) self.text.setFont(self.font_bold) self.desc = QGraphicsTextItem(self) self.desc.setFont(self.font) def update_flags(self): if self.scene().mode == 0: self.set_flags(is_selectable=True, accept_hover_events=True, accept_drops=True) else: self.set_flags(is_selectable=True, accept_hover_events=True) def labels_width(self): return max(self.number.boundingRect().width() + self.text.boundingRect().width(), self.desc.boundingRect().width()) def refresh(self): if len(self.model_item.condition): if len(self.model_item.condition) > 20: self.desc.setPlainText(self.model_item.condition[:20] + "...") else: self.desc.setPlainText(self.model_item.condition) elif self.model_item.type != ConditionType.ELSE: self.desc.setPlainText("<Condition>") def update_position(self, x_pos, y_pos): self.setPos(x_pos, y_pos) start_y = 0 start_x = ((self.scene().items_width() + 40) - ( self.number.boundingRect().width() + self.text.boundingRect().width())) / 2 self.number.setPos(start_x, start_y) start_x += self.number.boundingRect().width() self.text.setPos(start_x, start_y) start_y += round(self.number.boundingRect().height()) start_x = ((self.scene().items_width() + 40) - self.desc.boundingRect().width()) / 2 self.desc.setPos(start_x, start_y) if self.model_item.type != ConditionType.ELSE: start_y += round(self.desc.boundingRect().height()) start_y += 5 for child in self.get_scene_children(): child.update_position(20, start_y) start_y += round(child.boundingRect().height()) width = self.scene().items_width() self.prepareGeometryChange() self.bounding_rect = QRectF(0, 0, width + 40, self.childrenBoundingRect().height() + 5) def update_drop_indicator(self, pos): rect = self.boundingRect() if pos.y() - rect.top() < rect.height() / 3: self.drop_indicator_position = QAbstractItemView.AboveItem elif rect.bottom() - pos.y() < rect.height() / 3: self.drop_indicator_position = QAbstractItemView.BelowItem else: self.drop_indicator_position = QAbstractItemView.OnItem self.update() def paint(self, painter, option, widget): if self.scene().mode == 1: self.setOpacity(1 if self.model_item.logging_active else 0.3) painter.setOpacity(constants.SELECTION_OPACITY) if self.hover_active or self.isSelected(): painter.setBrush(constants.SELECTION_COLOR) elif not self.is_valid(): painter.setBrush(QColor(255, 0, 0, 150)) else: painter.setBrush(QColor.fromRgb(204, 204, 204, 255)) height = self.number.boundingRect().height() if self.model_item.type != ConditionType.ELSE: height += self.desc.boundingRect().height() painter.drawRect(QRectF(0, 0, self.boundingRect().width(), height)) painter.setBrush(Qt.NoBrush) painter.drawRect(self.boundingRect()) if self.drag_over: self.paint_drop_indicator(painter) def paint_drop_indicator(self, painter): painter.setPen(QPen(Qt.darkRed, 2, Qt.SolidLine)) painter.setBrush(Qt.NoBrush) rect = self.boundingRect() if self.drop_indicator_position == QAbstractItemView.AboveItem: painter.drawLine(QLineF(rect.topLeft(), rect.topRight())) elif self.drop_indicator_position == QAbstractItemView.OnItem: painter.drawRect(rect) else: painter.drawLine(QLineF(rect.bottomLeft(), rect.bottomRight()))
class TcamScreen(QtWidgets.QGraphicsView): new_pixmap = pyqtSignal(QtGui.QPixmap) new_pixel_under_mouse = pyqtSignal(bool, int, int, QtGui.QColor) destroy_widget = pyqtSignal() fit_in_view = pyqtSignal() def __init__(self, parent=None): super(TcamScreen, self).__init__(parent) self.setMouseTracking(True) self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.setDragMode(QGraphicsView.ScrollHandDrag) self.setFrameStyle(0) self.scene = QGraphicsScene(self) self.setScene(self.scene) self.new_pixmap.connect(self.on_new_pixmap) self.fit_in_view.connect(self.fit_view) self.pix = ViewItem() self.scene.addItem(self.pix) self.scene.setSceneRect(self.pix.boundingRect()) self.is_fullscreen = False # Flag to differentiate between actual images # and 'fake images' i.e. color background + text while # waiting for first trigger image self.display_real_image = True self.text_item = None self.fit_in_view_called = False self.mouse_position_x = -1 self.mouse_position_y = -1 self.zoom_factor = 1.0 self.first_image = True self.image_counter = 0 self.capture_roi = False self.roi_obj = None self.roi_origin = None self.roi_widgets = [] self.selection_area = None self.capture_widget = None self.origin = None def fit_view(self): """ """ self.reset_zoom() self.scene.setSceneRect(self.pix.boundingRect()) self.scene.update() self.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio) def reset_zoom(self): self.zoom_factor = 1.0 # this resets the view internal transformation matrix self.setTransform(QtGui.QTransform()) def on_new_pixmap(self, pixmap): self.image_counter += 1 self.pix.setPixmap(pixmap) if not self.display_real_image: self.text_item.hide() self.scene.removeItem(self.text_item) self.display_real_image = True if self.image_counter == 1: self.resize(self.size()) self.scene.setSceneRect(self.pix.boundingRect()) self.update() self.reset_zoom() self.first_image = False # wait for the second image # resizeEvents, etc appear before the scene has adjusted # to the actual image size. By waiting for the 2. image # we circumvent this by having the first image making all # adjustments for us. The only scenario where this will # cause problems is triggering. if self.is_fullscreen and self.image_counter == 2: self.fit_view() self.send_mouse_pixel() # don't call repaint here # it causes problems once the screen goes blank due to screensavers, etc # self.repaint() def wait_for_first_image(self): if not self.display_real_image: return self.reset_zoom() self.display_real_image = False self.text_item = QGraphicsTextItem() self.text_item.setDefaultTextColor(QColor("white")) self.text_item.setPos(100, 70) self.text_item.setPlainText("In Trigger Mode. Waiting for first image...") bg = QPixmap(1280, 720) bg.fill(QColor("grey")) self.pix.setPixmap(bg) self.image_counter += 1 self.scene.addItem(self.text_item) def send_mouse_pixel(self): # mouse positions start at 0 # we want the lower right corner to have the correct coordinates # e.g. an 1920x1080 image should have the coordinates # 1920x1080 for the last pixel self.new_pixel_under_mouse.emit(self.pix.legal_coordinates(self.mouse_position_x, self.mouse_position_y), self.mouse_position_x + 1, self.mouse_position_y + 1, self.pix.get_color_at_position(self.mouse_position_x, self.mouse_position_y)) def mouseMoveEvent(self, event): mouse_position = self.mapToScene(event.pos()) self.mouse_position_x = mouse_position.x() self.mouse_position_y = mouse_position.y() if self.selection_area: # adjust rect since we want to pull in all directions # origin can well be bottom left, thus recalc def calc_selection_rect(): x = min(self.origin.x(), event.pos().x()) y = min(self.origin.y(), event.pos().y()) x2 = max(self.origin.x(), event.pos().x()) y2 = max(self.origin.y(), event.pos().y()) return QPoint(x, y), QPoint(x2, y2) p1, p2 = calc_selection_rect() self.selection_area.setGeometry(QRect(p1, p2)) super().mouseMoveEvent(event) def mousePressEvent(self, event): """""" if self.capture_widget: self.selection_area = QRubberBand(QRubberBand.Rectangle, self) self.selection_area.setGeometry(QRect(event.pos(), QSize())) self.origin = event.pos() self.selection_area.show() super().mousePressEvent(event) def mouseReleaseEvent(self, event): if self.capture_widget: selectionBBox = self.selection_area.rect() rect = QRect(self.selection_area.pos(), selectionBBox.size()) selectionBBox = self.mapToScene(rect).boundingRect().toRect() self.capture_widget.emit(selectionBBox) self.selection_area.hide() self.selection_area = None QApplication.restoreOverrideCursor() self.capture_widget = None self.selection_area = None super().mouseReleaseEvent(event) def is_scene_larger_than_image(self): """ checks if the entire ViewItem is visible in the scene """ port_rect = self.viewport().rect() scene_rect = self.mapToScene(port_rect).boundingRect() item_rect = self.pix.mapRectFromScene(scene_rect) isec = item_rect.intersected(self.pix.boundingRect()) res = self.pix.get_resolution() if (isec.size().width() >= QSizeF(res).width() and isec.size().height() >= QSizeF(res).height()): return True return False def wheelEvent(self, event): if not self.display_real_image: return # Zoom Factor zoomInFactor = 1.25 zoomOutFactor = 1 / zoomInFactor # Set Anchors self.setTransformationAnchor(QGraphicsView.NoAnchor) self.setResizeAnchor(QGraphicsView.NoAnchor) # Save the scene pos oldPos = self.mapToScene(event.pos()) # Zoom if event.angleDelta().y() > 0: zoomFactor = zoomInFactor else: zoomFactor = zoomOutFactor if (self.is_scene_larger_than_image() and zoomFactor < 1.0): return self.zoom_factor *= zoomFactor # we scale the view itself to get infinite zoom # so that we can inspect a single pixel self.scale(zoomFactor, zoomFactor) # Get the new position newPos = self.mapToScene(event.pos()) # Move scene to old position delta = newPos - oldPos self.translate(delta.x(), delta.y()) self.scene.setSceneRect(self.pix.boundingRect()) def set_scale_position(self, scale_factor, x, y): self.scale(scale_factor, scale_factor) self.translate(x, y) def keyPressEvent(self, event): if self.isFullScreen(): if (event.key() == Qt.Key_F11 or event.key() == Qt.Key_Escape or event.key() == Qt.Key_F): self.destroy_widget.emit() elif self.capture_widget and event.key() == Qt.Key_Escape: self.abort_roi_capture() else: # Ignore event so that parent widgets can use it. # This is only called when we are not fullscreen. # Fullscreen causes us to have no parents. event.ignore() def start_roi_capture(self, finished_signal): """ Capture a region of interest """ self.capture_widget = finished_signal QApplication.setOverrideCursor(Qt.CrossCursor) def abort_roi_capture(self): """ Abort the capture of a regoin of interest """ self.capture_widget = None self.origin = None if self.selection_area: self.selection_area.hide() self.selection_area = None QApplication.restoreOverrideCursor() def add_roi(self, roi_widget): """ Add roi_widget to the QGraphicsScene for display """ if not roi_widget: return self.roi_widgets.append(roi_widget) self.scene.addItem(roi_widget) roi_widget.show() def remove_roi(self, roi_widget): """ Remove given roi widget from the scene """ if not roi_widget: return roi_widget.hide() try: self.roi_widgets.remove(roi_widget) except ValueError as e: # This means the widget is not in the list pass
class QGraphicsResizableRect(QGraphicsRectItem): hoverColor = QColor(255, 0, 0) #_hovering and selection color def __init__(self,x,y,h,w, scene=None,parent=None, editor=None): """" This class implements the resizable rectangle item which is dispalied on the scene x y should be the original positions in scene coordinates h,w are the height and the width of the rectangle """ self._editor = editor QGraphicsRectItem.__init__(self,0,0,w,h,parent=parent) self.Signaller=QGraphicsResizableRectSignaller(parent=parent) scene.addItem(self) #Default Appearence Properties self._fontColor=QColor(255, 255, 255) self._fontSize=10 self._lineWidth=1 ##Note: need to do like this because the x,y of the graphics item fix the position # of the zero relative to the scene self.moveBy(x,y) #Flags self.setFlag(QGraphicsItem.ItemIsMovable,True ) self.setFlag(QGraphicsItem.ItemIsSelectable,True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges ,True) self.setAcceptHoverEvents(True) self.setAcceptedMouseButtons(Qt.LeftButton | Qt.RightButton) self._resizeHandles=[] # A bit of flags self._hovering=False self._normalColor = QColor(0, 0, 255) self.updateColor() self._has_moved=False self._selected=False self._dbg=False self._setupTextItem() self._isFixed = False self.initHandles() self.hideHandles() self.setToolTip("Hold CTRL to drag the box") @property def fontColor(self): return self._fontColor @pyqtSlot(int) def setFontColor(self,color): self._fontColor=color self.textItem.setDefaultTextColor(color) self.updateText(self.textItem.toPlainText()) @property def fontSize(self): return self._fontSize @pyqtSlot(int) def setFontSize(self,s): self._fontSize=s font=QFont() font.setPointSize(self._fontSize) self.textItem.setFont(font) self.updateText(self.textItem.toPlainText()) @property def lineWidth(self): return self._lineWidth @pyqtSlot(int) def setLineWidth(self,s): self._lineWidth=s self.updateColor() @property def color(self): return self._normalColor @pyqtSlot(int) def setColor(self,qcolor): self._normalColor=qcolor self.updateColor() @pyqtSlot() def _setupTextItem(self): #Set up the text self.textItem=QGraphicsTextItem("",parent=self) textItem=self.textItem font=QFont() font.setPointSize(self._fontSize) textItem.setFont(font) textItem.setPos(QPointF(0,0)) #upper left corner relative to the father textItem.setDefaultTextColor(self._fontColor) if self._dbg: #another text item only for debug self.textItemBottom=QGraphicsTextItem("",parent=self) self.textItemBottom.setPos(QPointF(self.width,self.height)) self.textItemBottom.setDefaultTextColor(QColor(255, 255, 255)) self._updateTextBottom("shape " +str(self.shape)) @pyqtSlot(str) def _updateTextBottom(self,string): self.textItemBottom.setPlainText(string) def setNewSize(self, constrainAxis, size, flip=False): if constrainAxis == 0: h,w = size, self.rect().width() else: h,w = self.rect().height(), size if flip and constrainAxis ==0: w=-w if flip and constrainAxis ==1: h=-h newrect=QRectF(0, 0, w, h).normalized() self.setRect(newrect) self.width=self.rect().width() self.height=self.rect().height() self.shape=(self.height,self.width) #Ensures that the text is in the upper left corner a=0 b=0 if w<=0: a=w if h<=0: b=h self.textItem.setPos(QPointF(a,b)) if self._dbg: self.textItemBottom.setPos(QPointF(self.width,self.height)) for el in self._resizeHandles: #print "shape = %s , left = %s , right = %s , top = %s , bottm , %s "%(self.shape,self.rect().left(),self.rect().right(),self.rect().top(),self.rect().bottom()) el.resetOffset(el._constrainAxis,rect=newrect) self.Signaller.signalHasResized.emit() def hoverEnterEvent(self, event): event.setAccepted(True) self._hovering = True #elf.setCursor(Qt.BlankCursor) #self.radius = self.radius # modified radius b/c _hovering self.updateColor() self.setSelected(True) self.showHandles() super(QGraphicsResizableRect,self).hoverEnterEvent( event) self._editor.imageViews[2].setFocus() def hoverLeaveEvent(self, event): event.setAccepted(True) self._hovering = False self.setSelected(False) #self.setCursor(CURSOR) #self.radius = self.radius # no longer _hovering self.hideHandles() super(QGraphicsResizableRect,self).hoverLeaveEvent( event) def initHandles(self): for constrAxes in range(2): h = ResizeHandle(self.rect(), constrAxes, self) self._resizeHandles.append( h ) def moveHandles(self): for h, constrAxes in zip(self._resizeHandles, list(range(2))): h.resetOffset(constrAxes, self.rect()) def hideHandles(self): for h in self._resizeHandles: h.hide() def showHandles(self): for h in self._resizeHandles: h.show() @pyqtSlot(int) def setSelected(self, selected): QGraphicsRectItem.setSelected(self, selected) if self.isSelected(): self.Signaller.signalSelected.emit() if not self.isSelected(): self._hovering=False self.updateColor() #self.resetHandles() @pyqtSlot() def updateColor(self): color = self.hoverColor if (self._hovering or self.isSelected()) else self._normalColor self.setPen(QPen(color,self._lineWidth)) self.setBrush(QBrush(color, Qt.NoBrush)) def dataPos(self): dataPos = self.scenePos() pos = [int(dataPos.x()), int(dataPos.y())] return pos def topLeftDataPos(self): dataPos = self.rect().topLeft()+self.scene().scene2data.map(self.scenePos()) pos = [int(dataPos.x()), int(dataPos.y())] return pos def bottomRightDataPos(self): dataPos = self.rect().bottomRight()+self.scene().scene2data.map(self.scenePos()) pos = [int(dataPos.x()), int(dataPos.y())] return pos def mousePressEvent(self,event): modifiers=QApplication.queryKeyboardModifiers() if modifiers == Qt.ControlModifier: QApplication.setOverrideCursor(Qt.ClosedHandCursor) def mouseMoveEvent(self,event): pos=self.dataPos() modifiers=QApplication.queryKeyboardModifiers() if modifiers == Qt.ControlModifier: self._has_moved=True super(QGraphicsResizableRect, self).mouseMoveEvent(event) string=str(self.pos()).split("(")[1][:-1] #self.QResizableRect.signalIsMoving.emit() # dataPos = self.scene().scene2data.map(self.scenePos()) # pos = [dataPos.x(), dataPos.y()] #self.updateText("("+string+")"+" "+str(pos)) def mouseDoubleClickEvent(self, event): logger.debug("DOUBLE CLICK ON ITEM") #FIXME: Implement me event.accept() @pyqtSlot(str) def updateText(self,string): self.textItem.setPlainText(string) def mouseReleaseEvent(self, event): if self._has_moved: self.Signaller.signalHasMoved.emit(self.pos()) #self._has_moved=False self._has_moved=False QApplication.restoreOverrideCursor() return QGraphicsRectItem.mouseReleaseEvent(self, event) def itemChange(self, change,value): if change==QGraphicsRectItem.ItemPositionChange: newPos=value #new position in scene coordinates rect=self.scene().sceneRect() topLeftRectCoords=self.rect().topLeft() bottomRightRectCoords=self.rect().bottomRight() ntl=topLeftRectCoords+newPos nbr=bottomRightRectCoords+newPos if not rect.contains(ntl) or not rect.contains(nbr): ntl.setX(min(rect.right()-self.rect().width(), max(ntl.x(),rect.left()))) ntl.setY(min(rect.bottom()-self.rect().height(), max(ntl.y(), rect.top()))); return ntl-topLeftRectCoords return QGraphicsRectItem.itemChange(self, change,value) def setOpacity(self,float): logger.debug("Resetting Opacity {}".format(float)) self._normalColor.setAlpha(float*255) self.updateColor() def fixSelf(self, isFixed): self._isFixed = isFixed self.setFlag(QGraphicsItem.ItemIsMovable,not isFixed)
class OcrArea(QGraphicsRectItem): ## static data resizeBorder = .0 def __init__(self, pos, size, type_, parent = None, scene = None, areaBorder = 2, index = 0, textSize = 50): QGraphicsRectItem.__init__(self, 0, 0, size.width(), size.height(), parent) self.setPos(pos) self.newEvent = IsClicked() self.newEvent.area = self #self.setAcceptedMouseButtons(QtCore.Qt.NoButton) self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsSelectable) ## set index label self.text = QGraphicsTextItem("%d" % index, self) self.setTextSize(textSize) ## TODO: How to create constants for the type? ## (such as constants in Qt) (enum?) self.kind = type_ pen = QPen(self.color, areaBorder, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) self.setPen(pen) # self.setAcceptsHoverEvents(True) # TODO # self.text.setFlag(QtGui.QGraphicsItem.ItemIgnoresTransformations) def setIndex(self, idx): self.text.setPlainText(str(idx)) def setTextSize(self, size): font = QFont() font.setPointSizeF(size) self.text.setFont(font) def contextMenuEvent(self, event): menu = QMenu() removeAction = menu.addAction(QA.translate('QOcrWidget', "Remove")) #Action = menu.addAction(self.scene().tr("Remove")) menu.addSeparator() textAction = menu.addAction(QA.translate('QOcrWidget', "Text")) graphicsAction = menu.addAction(QA.translate('QOcrWidget', "Graphics")) ## verification of the type of the selection and ## setting a check box near the type that is in use textAction.setCheckable(True) graphicsAction.setCheckable(True) if self.kind == 1: textAction.setChecked(True) elif self.kind == 2: graphicsAction.setChecked(True) selectedAction = menu.exec_(event.screenPos()) if selectedAction == removeAction: self.scene().removeArea(self) elif selectedAction == textAction: self.kind = 1 elif selectedAction == graphicsAction: self.kind = 2 # when the area is selected the signal "isClicked()" is raised def mousePressEvent(self, event): self.newEvent.isClicked.emit() QGraphicsRectItem.mousePressEvent(self, event) # type property def _setType(self, type_): self.__type = type_ if self.__type == 1: self.color = Qt.darkGreen else: ## TODO: else -> elif ... + else raise exception self.color = Qt.blue self.text.setDefaultTextColor(self.color) pen = self.pen() pen.setColor(self.color) self.setPen(pen) def _type(self): return self.__type kind = property(fget=_type, fset=_setType)
class ClassModel(QGraphicsItem): def __init__(self, parent=None, graphicView=None, graphicScene=None): super(ClassModel, self).__init__() self.set_default_data() self.className = QGraphicsTextItem(self) self.functionsItem = FunctionsContainerModel(self) self.className.setPlainText(self.defaultClassName) self.setFlag(self.ItemIsMovable) self.setFlag(self.ItemSendsGeometryChanges) self.functionsItem.setPos(0, self.__get_title_height()) self.attributesItem = FunctionsContainerModel(self) self.attributesItem.setPos(0, self.functionsItem.get_height()) def set_default_data(self): self.maxWidth = 100 self.defaultClassNameHeight = 30 self.defaultClassName = "No name" def set_functions_list(self, functionsList): self.functionsItem.set_functions_list(functionsList, "*", "()") self.update_positions() def set_attributes_list(self, attributesList): self.attributesItem.set_functions_list(attributesList) self.update_positions() def set_class_name(self, className): self.className.setPlainText(className) def _get_width(self): self.__calc_max_width() return self.maxWidth def __get_title_height(self): titleHeight = self.defaultClassNameHeight if titleHeight == self.className.document().size().height(): titleHeight = self.className.document().size().height() return titleHeight def get_height(self): summary = self.defaultClassNameHeight summary += self.functionsItem.get_height() summary += self.attributesItem.get_height() return summary def __calc_max_width(self): if self.maxWidth < self.className.document().size().width(): self.maxWidth = self.className.document().size().width() if hasattr(self, "functionsItem"): if self.maxWidth < self.functionsItem.get_width(): self.maxWidth = self.functionsItem.get_width() if hasattr(self, "attributesItem"): if self.maxWidth < self.attributesItem.get_width(): self.maxWidth = self.attributesItem.get_width() def set_bg_color(self, qColor): self.backgroundColor = qColor def set_method_list(self, itemList): self.methodList = itemList def update_positions(self): self.functionsItem.setPos(0, self.__get_title_height()) self.attributesItem.setPos( 0, self.functionsItem.y() + self.functionsItem.get_height()) def paint(self, painter, option, widget): gradient = QRadialGradient(-3, -3, 10) if option.state & QStyle.State_Sunken: gradient.setCenter(3, 3) gradient.setFocalPoint(3, 3) gradient.setColorAt(0, QColor(Qt.yellow).light(120)) else: gradient.setColorAt(0, QColor(Qt.yellow).light(120)) painter.setBrush(gradient) painter.setPen(QPen(Qt.black, 0)) painter.drawRoundedRect(self.boundingRect(), 3, 3) def boundingRect(self): return QRectF(0, 0, self._get_width(), self.get_height()) def add_edge(self, edge): self.myEdge = edge edge.adjust()