class ActionItem(GraphicsItem): def __init__(self, model_item: SimulatorItem, parent=None): super().__init__(model_item=model_item, parent=parent) self.setFlag(QGraphicsTextItem.ItemIsPanel, True) self.text = QGraphicsTextItem(self) self.text.setFont(GraphicsItem.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 update_position(self, x_pos, y_pos): self.setPos(x_pos, y_pos) start_x = (self.scene().items_width() - self.labels_width()) / 2 self.number.setPos(start_x, 0) start_x += self.number.boundingRect().width() self.text.setPos(start_x, 0) width = self.scene().items_width() self.prepareGeometryChange() self.bounding_rect = QRectF(0, 0, width, self.childrenBoundingRect().height() + 5) #super().update_position(x_pos, y_pos) def labels_width(self): width = self.number.boundingRect().width() #width += 5 width += self.text.boundingRect().width() return width
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 on_actItem_Text_triggered(self): # 添加文字 str, okPressed = QInputDialog.getText(self, "输入文字", "请输入文字") if okPressed == False or not str: return () item = QGraphicsTextItem(str) font = self.font() font.setPointSize(20) font.setBold(True) item.setFont(font) item.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable) item.setPos(-50 + (QtCore.qrand() % 100), -50 + (QtCore.qrand() % 100)) self.view.frontZ = self.view.frontZ + 1 item.setZValue(self.view.frontZ) self.view.seqNum = self.view.seqNum + 1 item.setData(self.view.ItemId, self.view.seqNum) # //自定义数据,ItemId键 item.setData(self.view.ItemDesciption, "文字") self.scene.addItem(item) self.scene.clearSelection() item.setSelected(True)
def draw_word_boxes(self, word_boxes: list) -> None: """Sets up and draws translated words and their corresponding frames :param word_boxes: list of WordBox namedtuples, each representing a word and frame to be drawn. ex: [WordBox('word'=str, 'geometry'=[(int, int)], WordBox('word'=str, 'geometry'=[(int, int)]) """ for wPoly in self.__word_polygons: self.__scene.removeItem(wPoly[0]) self.__scene.removeItem(wPoly[1]) self.__word_polygons = [] for word_box in word_boxes: points = list(map(lambda x: QPoint(x[0], x[1]), word_box.geometry)) text = QGraphicsTextItem(word_box.word) text.setOpacity(0) text.setAcceptHoverEvents(False) font = QFont() font.setPixelSize(abs(points[0].y() - points[3].y())) text.setFont(font) w = text.boundingRect().width() h = text.boundingRect().height() text.setPos( points[0].x() + abs(points[0].x() - points[1].x()) / 2 - w / 2, points[0].y() + abs(points[0].y() - points[3].y()) / 2 - h / 2) frame = WordPolygon(QPolygonF(QPolygon(points)), text) self.__word_polygons.append([text, frame]) self.__scene.addItem(frame) self.__scene.addItem(text)
def update_items(self): rect_cls = QGraphicsRectItem self.item = rect_cls(0, 0, self.width, self.row_h) seq_width = 0 nopen = QPen(Qt.NoPen) font = QFont(self.ftype, self.fsize) for i, letter in enumerate(self.seq): width = self.col_w rectitem = rect_cls(0, 0, width, self.row_h, parent=self.item) rectitem.setX(seq_width) # to give correct X to children item rectitem.setBrush(self.bg_col[letter]) rectitem.setPen(nopen) # write letter if enough space if width >= self.fsize: text = None if self.style == "codon": text = QGraphicsTextItem(parent=rectitem) text.setHtml(self.get_html(i, self.fg_col[letter])) else: text = QGraphicsSimpleTextItem(letter, parent=rectitem) text.setBrush(QBrush(QColor(self.fg_col[letter]))) text.setFont(font) # Center text according to rectitem size txtw = text.boundingRect().width() txth = text.boundingRect().height() text.setPos((width - txtw) / 2, (self.row_h - txth) / 2) seq_width += width self.width = seq_width
class RText(QObject): def __init__(self, text, x, y, size, color): self._pos = QPointF(x - 1.8, y + 1.8) super().__init__() self.text = QGraphicsTextItem(text) transform = QTransform.fromScale(0.3, -0.3) self.text.setTransformOriginPoint(self._pos) self.text.setTransform(transform) self.text.setPos(self._pos) # self.text.setRotation(-180) font = QFont("Times", 2) self.text.setFont(font) self._visible = 1 @pyqtProperty(int) def visible(self): return self._visible @visible.setter def visible(self, value): if value > 0: self.text.show() else: self.text.hide() self._visible = value
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])
def render_items(self, event=None): self.links = self.get_links_dict() self.render_preview() for item in self.settings['items']: text = QGraphicsTextItem() font_color = QColor('black') text.setPos(QPointF(item['x'], item['y'])) font = QFont() font_name = item['params'].get(const.ITEM_DATA_KEY_FONT) if font_name: font.fromString(font_name) font_size = item['params'].get(const.ITEM_DATA_KEY_FONT_SIZE) if font_size: font.setPointSize(font_size) else: font.setPointSize(12) font_color_list = item['params'].get( const.ITEM_DATA_KEY_FONT_COLOR) if font_color_list: font_color.setRgb(*font_color_list) text.setFont(font) text_align = item['params'].get(const.ITEM_DATA_KEY_FONT_ALIGN) text.setFont(font) text.setTextWidth(item['w']) text.setDefaultTextColor(font_color) text.setHtml( f"<div align='{text_align}'>{self.test_row[self.links[item['name']]]}</div>" ) self.scene.addItem(text)
class ReadoutView(View): class Orientation(Enum): horizontal = 1 vertical = 2 def __init__(self, model): super().__init__(model) self.graphics_item = QGraphicsRectItem(0, 0, 9, 9) self.graphics_item.setBrush(Qt.black) inner_rect_item = QGraphicsRectItem(1, 1, 7, 7, self.graphics_item) inner_rect_item.setBrush(Qt.white) self.text_item = None self.orientation = ReadoutView.Orientation.horizontal def line(self): for child in self.graphics_item.childItems(): if isinstance(child, QGraphicsLineItem): return child.line() def line_item(self): for child in self.graphics_item.childItems(): if isinstance(child, QGraphicsLineItem): return child def init_text(self): width = self.graphics_item.boundingRect().width() height = self.graphics_item.boundingRect().height() self.text_item = QGraphicsTextItem(self.graphics_item) self.text_item.setPos(width / 2 + 2, -height)
def _showLetter(self, i, j): """ Graphical representation of a square to fill 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.NoBrush)) square = self.model.grid[i][j] if len(square) == 1: numberTextItem = QGraphicsTextItem(str(square[0])) numberTextItem.setDefaultTextColor(Qt.darkGreen) numberTextItem.setPos(x + self.SQUARE_SIZE / 3, y + self.SQUARE_SIZE / 3) self.scene.addItem(numberTextItem) else: for number in square: numberTextItem = QGraphicsTextItem(str(number)) xPos = x + ((number - 1) % 3) * self.SQUARE_SIZE / 3 yPos = y + ((number - 1) / 3) * self.SQUARE_SIZE / 3 numberTextItem.setPos(xPos, yPos) self.scene.addItem(numberTextItem)
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 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 __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 draw_event(self, event, min_x, max_x, min_y, max_y, pen=QPen(Qt.black, 3, Qt.SolidLine), brush=QBrush(QColor.fromRgb(250, 240, 240))): object_event = self.scene.addRect(event.x1, event.y1, event.x2 - event.x1, event.y2 - event.y1, pen, brush) text = event.description.split() pre = 0 result_text = event.name + '\n\n' for word in text: if pre + len(word) > 50: pre = 0 result_text += '\n' pre += len(word) + 1 result_text += word + ' ' object_event.setToolTip(result_text) self.events.append((event, object_event)) text_event = QGraphicsTextItem(str(event.years)) text_event.setPos(event.x1 + 5, event.y1 + 5) font = QFont() font.setBold(False) font.setPixelSize(25) text_event.setFont(font) text_event.setFont(font) self.scene.addItem(text_event)
class ActionItem(GraphicsItem): def __init__(self, model_item: SimulatorItem, parent=None): super().__init__(model_item=model_item, parent=parent) self.setFlag(QGraphicsTextItem.ItemIsPanel, True) self.text = QGraphicsTextItem(self) self.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 update_position(self, x_pos, y_pos): self.setPos(x_pos, y_pos) start_x = (self.scene().items_width() - self.labels_width()) / 2 self.number.setPos(start_x, 0) start_x += self.number.boundingRect().width() self.text.setPos(start_x, 0) width = self.scene().items_width() self.prepareGeometryChange() self.bounding_rect = QRectF(0, 0, width, self.childrenBoundingRect().height() + 5) def labels_width(self): width = self.number.boundingRect().width() width += self.text.boundingRect().width() return width
def addWP(self, wp): if wp.command in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT, mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS, mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME, mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM, mavutil.mavlink.MAV_CMD_NAV_LAND]: #point rad = self.__wp_diameter * 0.5 ellipse = QGraphicsEllipseItem(wp.y - rad, -wp.x - rad, self.__wp_diameter, self.__wp_diameter, self.__mission_layer) ellipse.setBrush(QBrush(QColor(255, 255, 255))) e_pen = QPen(QColor(255, 255, 255)) e_pen.setWidth(0) ellipse.setPen(e_pen) self.__mission_layer.addToGroup(ellipse) #label label = QGraphicsTextItem(str(wp.seq), self.__mission_layer) label.setZValue(2) label.setDefaultTextColor(Qt.white) label.setPos(wp.y + rad, -wp.x - rad) label.setScale(0.00002) #bit hacky -- really should scale based on #current zoom, but I'm in a hurry. self.__mission_layer.addToGroup(label) label.show()
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 Arc(QGraphicsLineItem): def __init__(self, first_node, second_node, weight, scene): QGraphicsLineItem.__init__(self) pen = QPen(QColor("green"), 5) self.first_node = first_node self.second_node = second_node self.weight = weight self.setZValue(1) self.setPen(pen) self.setLine(self.first_node.x() + 25, self.first_node.y() + 25, self.second_node.x() + 25, self.second_node.y() + 25) self.number = QGraphicsTextItem(str(weight)) self.number.setZValue(6) x = (first_node.x() + second_node.x()) / 2 y = (first_node.y() + second_node.y()) / 2 self.number.setPos(x, y) scene.addItem(self) scene.addItem(self.number) def __str__(self): return "{" + str(self.first_node.getNumber()) + ", " + str( self.second_node.getNumber()) + ", " + str(self.weight) + "}" def reverse(self): temp = self.first_node self.first_node = self.second_node self.second_node = temp
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 select_level(self): #set switches to the correct state self.set_switches_off('level') #self.cancel_button.clicked.connect(self.cancel_level_select) #initialize enter-key value and set correct state to selecting_level self.enter = 0 self.selecting_level = True self.level_text = '' #initialize a scene where to put levels self.level_scene = QGraphicsScene() #view for scene self.level_scene_view = QGraphicsView(self.level_scene, self) self.level_scene_view.adjustSize() self.level_scene_view.show() self.layout.addWidget(self.level_scene_view) level = QGraphicsTextItem('Level') path = os.getcwd() #get the current working dir os.chdir(path) #change dir to the current working dir os.chdir('game_levels') position = 50 levels = [] data = os.listdir() for item in data: if os.path.isfile(item): levels.append(item) #add also item to level_scene to show user what levels there are to choose from level = QGraphicsTextItem(item) #change color, can be changed later level.setDefaultTextColor(QColor(225,100,25)) self.level_scene.addItem(level) level.setPos(0,position) position +=20 self.qline_edit = QLineEdit() #change text color palette = QPalette() palette.setColor(QPalette.Text,QColor(225,100,25)) #the color can be changed self.qline_edit.setPalette(palette) self.layout.addWidget(self.qline_edit) self.qline_edit.textEdited[str].connect(self.qline_edited) os.chdir(path) #remember to change back to the working dir where all classes etc are
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 Node(QGraphicsEllipseItem): def __init__(self, name, rect=QRectF(0, 0, 20, 20), parent=None): QGraphicsEllipseItem.__init__(self, rect, parent) self.setX(random.randrange(0, 1000, 1)) self.setY(random.randrange(0, 300, 1)) self.edges = [] self.setZValue(2) self.brush_color = QColor(153, 153, 153) self.setBrush(self.brush_color) self.setPen(QPen(Qt.NoPen)) self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemSendsGeometryChanges) self.text = QGraphicsTextItem(name) self.text.setDefaultTextColor(self.brush_color) self.text.setPos(-float(len(self.text.toPlainText())), -20.0) self.text.setParentItem(self) self.screen = '' def set_screen(self, screen): self.screen = screen def addEdge(self, edge): self.edges.append(edge) def itemChange(self, change, value): if change == QGraphicsItem.ItemSelectedChange: self.setBrush(QColor("#1976D2") if value else self.brush_color) self.text.setDefaultTextColor( QColor("#1976D2") if value else self.brush_color) for i in range(len(self.edges)): self.edges[i].focus() if value else self.edges[i].defocus() if change == QGraphicsItem.ItemPositionHasChanged: for edge in self.edges: edge.adjust() return QGraphicsItem.itemChange(self, change, value) def mouseDoubleClickEvent(self, event): try: file = open(os.path.join(self.screen.project_folder, self.text.toPlainText()), 'r', encoding='utf-8', errors='ignore') with file: text = file.read() self.screen.new_document(title=self.text.toPlainText()) self.screen.current_editor.setPlainText(text) self.screen.current_editor.set_change_name( self.screen.tab_widget, False) except FileNotFoundError as error: QMessageBox.question(self.screen, 'Error', 'Error occured : ' + str(error), QMessageBox.Close)
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)
class MenuButton(QGraphicsRectItem): def __init__(self, name, height=200, width=50, parent=None): '''name: str ''' super().__init__(parent) # Set locked atribute self.locked = False # create my signal self.s = ButtonSignal() # draw the rect self.setRect(0, 0, height, width) # change color of rect brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(Qt.darkCyan) self.setBrush(brush) # draw the text self.text = QGraphicsTextItem(name, self) x_pos = self.rect().width() / 2 - self.text.boundingRect().width() / 2 y_pos = self.rect().height() / 2 - self.text.boundingRect().height() / 2 self.text.setPos(x_pos, y_pos) # allow responding to hover events self.setAcceptHoverEvents(True) def mousePressEvent(self, event): if not self.locked: self.s.clicked.emit() def hoverEnterEvent(self, event): '''event: QGraphicsSceneHoverEvent ''' # change color to cyan brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(Qt.cyan) self.setBrush(brush) def hoverLeaveEvent(self, event): '''event: QGraphicsSceneHoverEvent ''' # change color to dark cyan brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(Qt.darkCyan) self.setBrush(brush) def unlock(self): self.setOpacity(1) self.locked = False def lock(self): self.setOpacity(0.3) self.locked = True
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)
def displayID(self): if not self.display_id: for item in self.points_canvas.scene.items(): if isinstance(item, EntityPoint.EntityPoint): text = QGraphicsTextItem(str(item.id)) text.setPos(item.x + 2, item.y - 2) self.points_canvas.scene.addItem(text) self.display_id = True else: self.points_canvas.scene.removeIDs() self.display_id = False
def showImage(self): (newImg, newImgInfo) = self.loadImage() # return PicItem(Pixmap(QPixmap(newImg)), -1, -1, xFactor, yFactor, newImgInfo) self.scene.clear() imgSz = newImgInfo.imgSize self.setSceneRect(QRectF(0,0,imgSz.width(), imgSz.height())) pixMap = QPixmap.fromImage(newImg) # # pixMap.setWidth(self.width()) pixMapItem = self.scene.addPixmap(pixMap) # pixMapItem.setPos(50,50) # self.fitInView(QRectF(0, 0, self.width(), self.height()), Qt.KeepAspectRatio) # Add caption caption = QGraphicsTextItem() caption.setDefaultTextColor(QColor(255,255,255)) caption.setPos(0, self.height()*0.94) caption.setFont(QFont("Segoe UI", 30)) caption.setTextWidth(self.width()) # caption.setPos(100, 100) # caption.setTextWidth(1500) # if newImgInfo.createDate is not None: # caption.setPlainText(newImgInfo.createDate.format()); # else: # caption.setPlainText("Image is called bananas"); # print("Tags", newImgInfo.tags) # tagStr = "" # for tag in newImgInfo.tags: # if tag != "Duplicate": # tagStr += (", " if len(tagStr) != 0 else "") + tag # if tagStr == "": # tagStr = "NO TAGS" # captionStr = '<h1 style="text-align:center;width:100%">' + tagStr + '</h1>' # if newImgInfo.createDate is not None: # print(newImgInfo.createDate.format()) # captionStr += '<BR><h2>' + newImgInfo.createDate.format() + '</h2>' captionStr = "" try: if newImgInfo.rating is not None: for i in range(newImgInfo.rating): captionStr += "★" for i in range(5-newImgInfo.rating): captionStr += "☆" if newImgInfo.mainDate is not None: if len(captionStr) != 0: captionStr += " " captionStr += newImgInfo.mainDate.strftime("%d %b %Y") except Exception as excp: print("StaticPhotos: Cannot set caption") captionStr = '<div style="background-color:#000000;text-align: right;padding-right:10dp;">' + captionStr + "</div>" print(captionStr) caption.setHtml(captionStr) self.scene.addItem(caption) self.scene.update()
def __init__(self, parent): super().__init__(parent) self.parent = parent self.setWindowTitle('Notes graph') self.setMinimumHeight(400) self.zoom = 0 self.scene = QGraphicsScene() self.brush = QBrush(QColor(133, 63, 191)) self.pen = QPen(Qt.red) self.graphic_view = QGraphicsView(self.scene, self) self.graphic_view.setGeometry(0, 0, self.size().width(), self.size().height()) self.graphic_view.setDragMode(self.graphic_view.ScrollHandDrag) self.setWidget(self.graphic_view) node_list = [] link_index = BacklinkIndexer(parent.project_folder) if not os.path.isdir(os.path.join(parent.project_folder, '.notes')): label = QGraphicsTextItem('Current project is not a note project') self.scene.addItem(label) else: for files in os.listdir(parent.project_folder): if not files.startswith('.'): node = Node(os.path.basename(os.path.normpath(files))) link_index.add(files, node) node.set_screen(parent) node_list.append(node) print() node.setToolTip( f"Filename: {files}\nFilesize:" f" {convert_size(os.path.getsize(os.path.join(parent.project_folder, files)))}\n\n" f"Double click to open!") self.scene.addItem(node) for key in link_index.get_links(): for i2 in link_index.get_links()[key]: for i in node_list: if i.text.toPlainText() == i2: edge = Edge(key, i) self.scene.addItem(edge) info_text_title = QGraphicsTextItem("Information") info_text_title.setFont(QFont("", weight=QFont.Bold)) info_text = QGraphicsTextItem(f'Files: {len(node_list)}\n' f'Links: {len(link_index.get_links())}') info_text.setPos(0, 15) self.scene.addItem(info_text_title) self.scene.addItem(info_text)
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()
def draw_grid(self): WIDTH = 100 HEIGHT = 60 size = 50 width = (self._nrows + 1) * WIDTH height = (self._ncols + 1) * HEIGHT self.setSceneRect(0, 0, width, height) self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex) # FIXME: cell_size = self._ascii_parser.cell_size # cell_size = self._ascii_parser.cell_size + 500 # Rows start at min coordinate value init_x_val = int(self._ascii_parser.xllcorner) + cell_size // 2 # FIXME: current_x_val = init_x_val # current_x_val = init_x_val + 1000 # Setup row labels for editor for i in range(2, self._ncols + 2): current_x_str = center_num(current_x_val) label = QGraphicsTextItem(current_x_str) label.setPos((i * size), 0) self.addItem(label) current_x_val += cell_size # Columns start at max coordinate value init_y_val = int(self._ascii_parser.yllcorner ) + cell_size * self._nrows - cell_size // 2 current_y_val = init_y_val # Setup row labels for editor for i in range(1, self._nrows + 1): current_y_str = center_num(current_y_val) label = QGraphicsTextItem(current_y_str) label.setPos(0, i * size) self.addItem(label) current_y_val -= cell_size
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 AnimatedClock(): updateTimer = None calDataLock = threading.Lock() calDataUpdated = False curCalendars = None def __init__(self, scene, widthClkTextArea, heightClkTextArea, borders, updateSecs): self.masterScene = scene self.widthClkTextArea = widthClkTextArea self.heightClkTextArea = heightClkTextArea self.borders = borders self.updateSecs = updateSecs # Background self.textBkgd = QGraphicsRectItem(0, 0, self.widthClkTextArea, self.heightClkTextArea) self.textBkgd.setPos(self.borders[3], self.borders[0]) self.textBkgd.setBrush(QColor("light green")) self.textBkgd.setZValue(10) scene.addItem(self.textBkgd) # Text Item self.textItem = QGraphicsTextItem() self.textItem.setFont(QFont("Segoe UI", 80)) self.textItem.setDefaultTextColor(QColor("black")) self.textItem.setPos(QPointF(self.borders[3]+10,self.borders[0]+5)) self.textItem.setHtml("<B>Clock</B>") self.textItem.setZValue(20) self.textItem.setTextWidth(self.widthClkTextArea-20) scene.addItem(self.textItem) def start(self): self.updateTimer = QTimer() self.updateTimer.setInterval(self.updateSecs * 1000) self.updateTimer.timeout.connect(self.updateClock) self.updateTimer.start() def stop (self): if self.updateTimer != None: self.updateTimer.stop() def updateClock(self): localtime = time.localtime() # dateString = time.strftime("%a %d %b %Y", localtime) timeString = time.strftime("%H:%M:%S", localtime) self.textItem.setHtml(timeString) # self.textItem.setTextWidth(self.widthCalTextArea-20) self.textItem.update()
def create_map_points(self): self.map_points_text_items = [] self.map_points_items = [] for map_point in self.map_data.map_points: color = QColor().fromRgb(map_point.r, map_point.g, map_point.b) rect = QGraphicsRectItem( QRectF( QPointF(map_point.x, map_point.y), QSizeF(5 / self.scale_ratio, 5 / self.scale_ratio) ) ) rect.setPen(QPen(Qt.black, 1 / self.scale_ratio)) rect.setBrush(color) self.map_points_items.append(rect) text = QGraphicsTextItem(map_point.text) text.setDefaultTextColor(color) text.setPos(map_point.x, map_point.y) text.setFont(QFont('Times New Roman', 8 / self.scale_ratio, 2)) self.map_points_text_items.append(text)
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
def define(self, cells): index = 0 cell_sum = 0 for y in range(self.height): for x in range(self.width): try: required_bridges = int(cells[y][x]) new_island = Island(index, x, y, required_bridges) self.islands.append(new_island) self.grid[y][x] = new_island text_item = QGraphicsTextItem(str(required_bridges)) text_item.setFont(self.font) text_item.setPos(30*x+5, 30*y-2) self.scene.addItem(text_item) cell_sum += required_bridges index += 1 except ValueError: pass if cell_sum % 2 == 0: self.total_required_bridges = int(cell_sum / 2) print("Found {} islands that require a total of {} bridges".format(index, self.total_required_bridges)) else: print("The grid is not valid!")
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 Node(QGraphicsRectItem): class io(QGraphicsRectItem): class BezierCurve(QGraphicsPathItem): def __init__(self, iostart=None, ioend=None): super().__init__() self.setEnabled(False) # Make it ignore events. Links can't be interacted with. self.iostart = iostart self.ioend = ioend if iostart is not None and ioend is not None: self.update() else: self.update(QPointF(0, 0)) def update(self, pos=None): path = QPainterPath() if pos is not None: if self.ioend is None: startpos = self.iostart.pos() + self.iostart.parent.pos() endpos = pos elif self.iostart is None: startpos = pos endpos = self.ioend.pos() + self.ioend.parent.pos() else: startpos = self.iostart.pos() + self.iostart.parent.pos() endpos = self.ioend.pos() + self.ioend.parent.pos() controlpoint = QPointF(abs((endpos - startpos).x()) * 0.8, 0) path.moveTo(startpos) path.cubicTo(startpos + controlpoint, endpos - controlpoint, endpos) self.setPath(path) def __init__(self, parent, index, iotype, iodir): self.parent = parent self.index = index self.iotype = iotype self.iodir = iodir super().__init__(-8, -8, 16, 16, self.parent) # Size of io-boxes is 16x16 self.setAcceptHoverEvents(True) self.iobrush = QBrush(QColor(70, 70, 70, 255)) self.setBrush(self.iobrush) self.newbezier = None # Variable for temporary storage of bezier curve while it's still being dragged self.bezier = [] def mousePressEvent(self, event): if event.button() == Qt.LeftButton: if self.iodir == "output": self.newbezier = Node.io.BezierCurve(self, None) elif self.iodir == "input": self.newbezier = Node.io.BezierCurve(None, self) if self.newbezier is not None: self.newbezier.update(QPointF(event.pos() + self.pos() + self.parent.pos())) self.parent.parent.scene.addItem(self.newbezier) elif event.button() == Qt.RightButton: self.delAllBezier() def mouseMoveEvent(self, event): if self.newbezier is not None: self.newbezier.update(QPointF(event.pos() + self.pos() + self.parent.pos())) def mouseReleaseEvent(self, event): if self.newbezier is not None: self.parent.parent.scene.removeItem(self.newbezier) self.newbezier = None # Find out if an io box lies under the cursor pos = event.pos() + self.pos() + self.parent.pos() pos = self.parent.parent.mapFromScene(pos) target = self.parent.parent.itemAt(pos.x(), pos.y()) # If io box is found, spawn a bezier curve if target is None: if self.iodir == "output": ns = NodeSelector(self.parent.parent.modman, modfilter={"type": {"type": self.iotype, "dir": "input"}}) elif self.iodir == "input": ns = NodeSelector(self.parent.parent.modman, modfilter={"type": {"type": self.iotype, "dir": "output"}}) if ns.exec(): if issubclass(ns.data["node"], baseModule.BaseNode): newNode = Node(self.parent.parent, ns.data["node"]) newNode.setPos(event.pos() + self.pos() + self.parent.pos()) self.parent.parent.scene.addItem(newNode) if self.iodir == "output": target = newNode.inputIO[ns.data["pin"]] elif self.iodir == "input": target = newNode.outputIO[ns.data["pin"]] if target is not None and isinstance(target, Node.io): bezier = None if self.iodir == "output" and target.iodir == "input" and (self.iotype == target.iotype or not self.iotype or not target.iotype): bezier = Node.io.BezierCurve(self, target) if not self.iotype == "exec": target.delAllBezier() elif self.iotype == "exec": if len(self.bezier) >= 1: self.delAllBezier() elif self.iodir == "input" and target.iodir == "output" and (self.iotype == target.iotype or not self.iotype or not target.iotype): bezier = Node.io.BezierCurve(target, self) if not self.iotype == "exec": self.delAllBezier() elif self.iotype == "exec": if len(target.bezier) >= 1: target.delAllBezier() if bezier is not None: self.bezier.append(bezier) target.bezier.append(bezier) self.parent.parent.scene.addItem(bezier) def hoverEnterEvent(self, event): self.parent.setPen(QPen(QColor("black"))) # For some f*****g reason QGraphicsSceneHoverEvents can't be accepted, so this dirty workaround has to be used... self.setPen(QPen(QColor("yellow"))) def hoverLeaveEvent(self, event): self.parent.setPen(QPen(QColor("yellow"))) # See above self.setPen(QPen(QColor("black"))) def updateBezier(self): for bezier in self.bezier: bezier.update() def delAllBezier(self): beziercpy = self.bezier[:] for bezier in beziercpy: bezier.iostart.bezier.remove(bezier) bezier.ioend.bezier.remove(bezier) self.parent.parent.scene.removeItem(bezier) def __init__(self, parent, nodedata=None, id=None): if nodedata is None: raise ValueError("Nodetype must not be 'None'") self.nodedata = nodedata self.parent = parent self.width = 32 self.height = 0 super().__init__(-self.width / 2, -self.height / 2, self.width, self.height) self.setAcceptHoverEvents(True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.extraNodeData = {} if id is not None: self.id = id else: self.id = uuid.uuid4().hex # Random ID to identify node self.nodebrush = QBrush(QColor(100, 100, 100, 255)) self.setBrush(self.nodebrush) # Node Title self.nodetitle = self.nodedata.name self.nodetitleTextItem = QGraphicsTextItem(self.nodetitle, self) self.width = max(self.width, self.nodetitleTextItem.boundingRect().width()) self.height += self.nodetitleTextItem.boundingRect().height() # Create all the text items for the IO self.inputTextItems = [] self.outputTextItems = [] for i in range(max(len(self.nodedata.inputDefs), len(self.nodedata.outputDefs))): linewidth = 0 lineheight = 0 try: self.inputTextItems.append(QGraphicsTextItem(self.nodedata.inputDefs[i][0], self)) linewidth += self.inputTextItems[i].boundingRect().width() lineheight = max(lineheight, self.inputTextItems[i].boundingRect().height()) except IndexError: pass try: self.outputTextItems.append(QGraphicsTextItem(self.nodedata.outputDefs[i][0], self)) linewidth += self.outputTextItems[i].boundingRect().width() lineheight = max(lineheight, self.outputTextItems[i].boundingRect().height()) except IndexError: pass linewidth += 12 # Keep atleast 12px distance between the input and output text self.width = max(self.width, linewidth) self.height += lineheight # Set correct positions for all text items self.nodetitleTextItem.setPos(-self.width / 2, -self.height / 2) self.inputIO = [] heightPointer = 0 for i in range(max(len(self.nodedata.inputDefs), len(self.nodedata.outputDefs))): try: self.inputTextItems[i].setPos(-self.width / 2, -self.height / 2 + self.nodetitleTextItem.boundingRect().height() + heightPointer) heightPointer += self.inputTextItems[i].boundingRect().height() newinput = Node.io(self, i, self.nodedata.inputDefs[i][1], "input") self.inputIO.append(newinput) newinput.setPos(-self.width / 2 - newinput.rect().width() / 2, -self.height / 2 + heightPointer + self.inputTextItems[i].boundingRect().height() / 2) except IndexError: pass self.outputIO = [] heightPointer = 0 for i in range(max(len(self.nodedata.inputDefs), len(self.nodedata.outputDefs))): try: self.outputTextItems[i].setPos(self.width / 2 - self.outputTextItems[i].boundingRect().width(), -self.height / 2 + self.nodetitleTextItem.boundingRect().height() + heightPointer) heightPointer += self.outputTextItems[i].boundingRect().height() newoutput = Node.io(self, i, self.nodedata.outputDefs[i][1], "output") self.outputIO.append(newoutput) newoutput.setPos(self.width / 2 + newoutput.rect().width() / 2, -self.height / 2 + heightPointer + self.outputTextItems[i].boundingRect().height() / 2) except IndexError: pass # Set rect to correct size self.setRect(-self.width / 2, -self.height / 2, self.width, self.height) # Additional stuff self.setFlag(QGraphicsItem.ItemIsMovable, True) def delete(self): for io in self.inputIO + self.outputIO: io.delAllBezier() io.parent = None io.bezier = None del self.inputIO del self.outputIO def mouseMoveEvent(self, event): super().mouseMoveEvent(event) for io in self.inputIO + self.outputIO: io.updateBezier() def hoverEnterEvent(self, event): self.setPen(QPen(QColor("yellow"))) def hoverLeaveEvent(self, event): self.setPen(QPen(QColor("black")))
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 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 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
"<p>" "Tell the stickman what to do!" "</p>" "<p><i>" '<li>Press <font color="purple">J</font> to make the stickman jump.</li>' '<li>Press <font color="purple">D</font> to make the stickman dance.</li>' '<li>Press <font color="purple">C</font> to make him chill out.</li>' '<li>When you are done, press <font color="purple">Escape</font>.</li>' "</i></p>" "<p>If he is unlucky, the stickman will get struck by lightning, and never jump, dance or chill out again." "</p></font>" ) w = textItem.boundingRect().width() stickManBoundingRect = stickMan.mapToScene(stickMan.boundingRect()).boundingRect() textItem.setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0) scene = QGraphicsScene() scene.addItem(stickMan) scene.addItem(textItem) scene.setBackgroundBrush(Qt.black) view = GraphicsView() view.setRenderHints(QPainter.Antialiasing) view.setTransformationAnchor(QGraphicsView.NoAnchor) view.setScene(scene) view.show() view.setFocus() # Make enough room in the scene for stickman to jump and die. sceneRect = scene.sceneRect()
class AnimatedCalendar(): updatesRunning = False updateTimer = None listUpdateThread = None calDataLock = threading.Lock() calDataUpdated = False curCalendars = None def __init__(self, scene, widthCalTextArea, heightCalTextArea, borders, calFeeds, calUpdateSecs): self.masterScene = scene self.widthCalTextArea = widthCalTextArea self.heightCalTextArea = heightCalTextArea self.borders = borders self.calFeeds = calFeeds self.calendarUpdateSecs = calUpdateSecs # Background self.textBkgd = QGraphicsRectItem(0, 0, self.widthCalTextArea, self.heightCalTextArea) self.textBkgd.setPos(self.borders[3], self.borders[0]) self.textBkgd.setBrush(QColor("light green")) self.textBkgd.setZValue(10) scene.addItem(self.textBkgd) # Text Item self.textItem = QGraphicsTextItem() self.textItem.setFont(QFont("Segoe UI", 24)) self.textItem.setDefaultTextColor(QColor("black")) self.textItem.setPos(QPointF(self.borders[3]+10,self.borders[0]+10)) self.textItem.setHtml("<B>Hello</B>Hello") self.textItem.setZValue(20) self.textItem.setTextWidth(self.widthCalTextArea-20) scene.addItem(self.textItem) def start(self): self.updatesRunning = True QTimer.singleShot(100, self.updateCalendar) self.listUpdateThread = CalendarUpdateThread(self, self.calFeeds, self.calendarUpdateSecs) self.listUpdateThread.start() # print("CalStarted") def stop (self): self.updatesRunning = False if self.updateTimer != None: self.updateTimer.stop() if self.listUpdateThread != None: self.listUpdateThread.stop() def setNewCalendarEntries(self, calendars): with self.calDataLock: self.curCalendars = calendars self.calDataUpdated = True def updateCalendar(self): # print("Update cal") with self.calDataLock: if self.calDataUpdated and self.curCalendars != None: for calEvents in self.curCalendars: calStr = "" lastDay = -1 for anEvent in calEvents: # date, duration, summary, location, UID eventDate = anEvent[0] duration = anEvent[1] summary = anEvent[2] location = anEvent[3] if lastDay != eventDate.day: if lastDay != -1: calStr += "<br/>" calStr += "<b>" + anEvent[0].strftime("%a") + " (" + anEvent[0].strftime("%d %B)") + ")</b><br/>" lastDay = eventDate.day strDurTime = str(duration).rpartition(":")[0] durStr = (str(duration.days) + "day" + ("s" if duration.days != 1 else "")) if duration.days > 0 else strDurTime locStr = "<small>("+location+")</small>" if location != "" else "" calStr += anEvent[0].strftime("%H:%M") + " <small>(" + durStr + ")</small> " + summary + " " + locStr + "<br/>" # print (anEvent) # print(date) self.textItem.setHtml(calStr) self.textItem.setTextWidth(self.widthCalTextArea-20) self.textItem.update() self.calDataUpdated = False if not self.updatesRunning: return self.updateTimer = QTimer() self.updateTimer.setInterval(5000) self.updateTimer.setSingleShot(True) self.updateTimer.timeout.connect(self.updateCalendar) self.updateTimer.start()