def __init__(self): super(MainWindow, self).__init__() self.resize(600, 400) self.view = QMyGraphicsView() # 创建视图窗口 self.setCentralWidget(self.view) # 设置中央控件 self.statusbar = self.statusBar() # 添加状态栏 self.labviewcorrd = QLabel('view坐标:') self.labviewcorrd.setMinimumWidth(150) self.statusbar.addWidget(self.labviewcorrd) self.labscenecorrd = QLabel('scene坐标:') self.labscenecorrd.setMinimumWidth(150) self.statusbar.addWidget(self.labscenecorrd) self.labitemcorrd = QLabel('item坐标:') self.labitemcorrd.setMinimumWidth(150) self.statusbar.addWidget(self.labitemcorrd) rect = QRectF(-200, -100, 400, 200) self.scene = QGraphicsScene(rect) # 创建场景 # 参数:场景区域 # 场景坐标原点默认在场景中心---场景中心位于界面中心 self.view.setScene(self.scene) # 给视图窗口设置场景 item1 = QGraphicsRectItem(rect) # 创建矩形---以场景为坐标 item1.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable) # 给图元设置标志 # QGraphicsItem.ItemIsSelectable---可选择 # QGraphicsItem.ItemIsFocusable---可设置焦点 # QGraphicsItem.ItemIsMovable---可移动 # QGraphicsItem.ItemIsPanel--- self.scene.addItem(item1) # 给场景添加图元 for pos, color in zip([rect.left(), 0, rect.right()], [Qt.red, Qt.yellow, Qt.blue]): item = QGraphicsEllipseItem(-50, -50, 100, 100) # 创建椭圆--场景坐标 # 参数1 参数2 矩形左上角坐标 # 参数3 参数4 矩形的宽和高 item.setPos(pos, 0) # 给图元设置在场景中的坐标(移动图元)--图元中心坐标 item.setBrush(color) # 设置画刷 item.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable) self.scene.addItem(item) self.scene.clearSelection() # 【清除选择】 self.view.sigMouseMovePoint.connect(self.slotMouseMovePoint)
def setupScene(self): self.m_scene.setSceneRect(-300, -200, 600, 460) linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100)) linearGrad.setColorAt(0, QColor(255, 255, 255)) linearGrad.setColorAt(1, QColor(192, 192, 255)) self.setBackgroundBrush(linearGrad) radialGrad = QRadialGradient(30, 30, 30) radialGrad.setColorAt(0, Qt.yellow) radialGrad.setColorAt(0.2, Qt.yellow) radialGrad.setColorAt(1, Qt.transparent) pixmap = QPixmap(60, 60) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) painter.setBrush(radialGrad) painter.drawEllipse(0, 0, 60, 60) painter.end() self.m_lightSource = self.m_scene.addPixmap(pixmap) self.m_lightSource.setZValue(2) for i in range(-2, 3): for j in range(-2, 3): if (i + j) & 1: item = QGraphicsEllipseItem(0, 0, 50, 50) else: item = QGraphicsRectItem(0, 0, 50, 50) item.setPen(QPen(Qt.black, 1)) item.setBrush(QBrush(Qt.white)) effect = QGraphicsDropShadowEffect(self) effect.setBlurRadius(8) item.setGraphicsEffect(effect) item.setZValue(1) item.setPos(i * 80, j * 80) self.m_scene.addItem(item) self.m_items.append(item)
def create_fromDB(self, pos_list=[], obj_type=""): if obj_type == "rois": num_rois = len(pos_list) for i in range(num_rois): points = pos_list[i] rect = QGraphicsRectItem() rect.setPen(QPen(Qt.green)) rect.setRect(points[0], points[1], points[2], points[3]) self.rectgroup.addToGroup(rect) self.scene.addItem(self.rectgroup) elif obj_type == "vector": num_vec = len(pos_list) for i in range(num_vec): points = pos_list[i] vec = QGraphicsLineItem() vec.setPen(QPen(Qt.green)) vec.setLine(points[0][0], points[0][1], points[1][0], points[1][1]) self.linegroup.addToGroup(vec) self.scene.addItem(self.linegroup)
def __init__(self, scene): super(Setbuttons, self).__init__() self.scene = scene self.buttons = {} # Register of buttons as {name: button} buttonParent = QGraphicsRectItem() buttonParent.persistent = True self.playButton, self.acceptButton, self.passButton = None, None, None self.challengeButton, self.exchangeButton, self.quitButton = None, None, None self.nextButton, self.backButton, self.endButton, self.newButton = None, None, None, None self.setup_buttons(buttonParent) self.set_button_pos() # self.reset_tips() self.scene.addItem(buttonParent) buttonParent.setScale(0.75) buttonParent.setPos(200, 200) buttonParent.setZValue(65)
def render_drop_shadow_frame(pixmap, shadow_rect, shadow_color, offset, radius, rect_fill_color): pixmap.fill(QColor(0, 0, 0, 0)) scene = QGraphicsScene() rect = QGraphicsRectItem(shadow_rect) rect.setBrush(QColor(rect_fill_color)) rect.setPen(QPen(Qt.NoPen)) scene.addItem(rect) effect = QGraphicsDropShadowEffect(color=shadow_color, blurRadius=radius, offset=offset) rect.setGraphicsEffect(effect) scene.setSceneRect(QRectF(QPointF(0, 0), QSizeF(pixmap.size()))) painter = QPainter(pixmap) scene.render(painter) painter.end() scene.clear() scene.deleteLater() return pixmap
def __init__(self, strand_item, cap_type, is_drawn5to3): """The parent should be a StrandItem.""" super(EndpointItem, self).__init__(strand_item.virtualHelixItem()) self._strand_item = strand_item self._getActiveTool = strand_item._getActiveTool self._cap_type = cap_type self._low_drag_bound = None self._high_drag_bound = None self._mod_item = None self._initCapSpecificState(is_drawn5to3) self.setPen(QPen()) # for easier mouseclick self._click_area = cA = QGraphicsRectItem(_DEFAULT_RECT, self) self._click_area.setAcceptHoverEvents(True) cA.hoverMoveEvent = self.hoverMoveEvent cA.mousePressEvent = self.mousePressEvent cA.mouseMoveEvent = self.mouseMoveEvent cA.setPen(_NO_PEN) self.setFlag(QGraphicsItem.ItemIsSelectable)
def add_game_grid(self): ''' Adds an QGraphicsItem for each square in the game. Qt uses QGraphicsItems to draw objects in the QGraphicsScene. QGraphicsRectItem is a subclass of QGraphicsItem, and is useful for easily drawing rectangular items. This method should only be called once, otherwise it creates duplicates! ''' x = 0 y = 0 for i in range(self.game.get_width()): for j in range(self.game.get_height()): new_square = QGraphicsRectItem(0, 0, self.square_size, self.square_size) new_square.setPos(x, y) self.square_graphics.append(new_square) self.scene.addItem(new_square) y += self.square_size x += self.square_size y = 0
def __init__(self, mobj, parent): KineticsDisplayItem.__init__(self, mobj, parent) self.bg = QGraphicsRectItem(self) self.bg.setAcceptHoverEvents(True) self.gobj = QtGui.QGraphicsSimpleTextItem(self.mobj.name, self.bg) self.gobj.mobj = self.mobj self._conc = self.mobj.conc self._n = self.mobj.n doc = "Conc\t: " + str(self._conc) + "\nn\t: " + str(self._n) self.gobj.setToolTip(doc) self.gobj.setFont(PoolItem.font) if not PoolItem.fontMetrics: PoolItem.fontMetrics = QtGui.QFontMetrics(self.gobj.font()) self.bg.setRect( 0, 0, self.gobj.boundingRect().width() + PoolItem.fontMetrics.width(' '), self.gobj.boundingRect().height()) self.bg.setPen(Qt.QColor(0, 0, 0, 0)) self.gobj.setPos(PoolItem.fontMetrics.width(' '), 0)
def draw_water(self): if self.proj in ('Spherical', 'ETRS89 - LAEA Europe'): cx, cy = self.to_canvas_coordinates(17, 48) # if the projection is ETRS89, we need the diameter and not the radius R = 6371000 * self.ratio * (1 if self.proj == 'Spherical' else 2) earth_water = QGraphicsEllipseItem(cx - R, cy - R, 2 * R, 2 * R) earth_water.setZValue(0) earth_water.setBrush(self.water_brush) self.polygons.addToGroup(earth_water) else: # we compute the projected bounds of the Mercator (3395) projection # upper-left corner x and y coordinates: ulc_x, ulc_y = self.to_canvas_coordinates(-180, 84) # lower-right corner x and y coordinates lrc_x, lrc_y = self.to_canvas_coordinates(180, -84.72) # width and height of the map (required for the QRectItem) width, height = lrc_x - ulc_x, lrc_y - ulc_y earth_water = QGraphicsRectItem(ulc_x, ulc_y, width, height) earth_water.setZValue(0) earth_water.setBrush(self.water_brush) self.polygons.addToGroup(earth_water)
def display_hotel(self): if self.hotel: width, height = self.color_rect.boundingRect().getRect()[2:] houses = self.color_rect.childItems() for house in houses: house.setParentItem(None) rect_color = QColor() rect_color.setNamedColor("#FF0000") pen_color = QColor() pen_color.setNamedColor("#00A500") pen = QPen() pen.setBrush(QBrush(pen_color)) pen.setWidth(2) hotel = QGraphicsRectItem(width / 4, height / 4, width / 2, height / 2) hotel.setParentItem(self.color_rect) hotel.setBrush(QBrush(rect_color, style=Qt.Dense1Pattern)) hotel.setPen(pen)
def approve_obj(self): self.scene.removeItem(self.rect) self.scene.removeItem(self.line) viewBBox = self.zoomStack[-1] if len( self.zoomStack) else self.sceneRect() selectionBBox = self.scene.selectionArea().boundingRect().intersected( viewBBox) rect = QGraphicsRectItem() rect.setRect(selectionBBox) rect.setPen(QPen(Qt.green)) self.rectgroup.addToGroup(rect) self.scene.addItem(self.rectgroup) line = QGraphicsLineItem() line.setLine(QLineF(self.start, self.current)) line.setPen(QPen(Qt.green)) self.linegroup.addToGroup(line) self.scene.addItem(self.linegroup) return (selectionBBox, self.start, self.current)
def __init__(self, scene): super(Setbuttons, self).__init__() self.scene = scene self.buttons = {} # Register of buttons as {name: button} self.setupButton, self.checkButton, self.loadButton, self.saveButton = None, None, None, None self.clearButton, self.playButton, self.printButton, self.solveButton = None, None, None, None self.printButton, self.solveButton, self.stepButton, self.quitButton = None, None, None, None self.hintButton, self.restartButton = None, None buttonParent = QGraphicsRectItem() self.playButton = None self.checkButton = None self.setup_buttons(buttonParent) self.set_button_pos() self.reset_tips() buttonParent.setScale(0.75) buttonParent.setPos(Cons.BUTTON_X, Cons.BUTTON_Y) buttonParent.setZValue(65) self.scene.addItem(buttonParent)
def createItem(self): # ターゲットマーカの作成 self.target_circle = QGraphicsEllipseItem( QtCore.QRectF(-10, -10, 20, 20)) self.target_circle.setBrush(QBrush(Qt.red)) self.target_circle.setPen(QPen(Qt.black)) self.overlayScene.addItem(self.target_circle) self.setTargetMode(False) # モーダルの作成:モーダルはターゲット位置に追従する self.pop_rect = QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 60), self.target_circle) self.pop_rect.setBrush(QBrush(Qt.gray)) self.pop_rect.setPen(QPen(Qt.gray)) self.pop_rect.setOpacity(0.8) # 透明度を設定 self.operate_text = QGraphicsSimpleTextItem("", self.pop_rect) self.operate_text.setScale(1.7) self.sub_operate_text = QGraphicsSimpleTextItem("", self.pop_rect) self.sub_operate_text.setScale(1.7) self.setTargetPos(400, 180, DirectionEnum.VERTICAL.value)
def __init__(self, tool, parent=None): """Summary Args: tool (TYPE): Description parent (None, optional): Description """ super(GridSelectionGroup, self).__init__(parent) self.tool = tool self.setFiltersChildEvents(True) self.setFlag(QGraphicsItem.ItemIsFocusable) # for keyPressEvents self.setFlag(QGraphicsItem.ItemIsMovable) self.bounding_rect_item = bri = QGraphicsRectItem(tool) bri.hide() bri.setPen(getPenObj(_SELECT_COLOR, _SELECT_PEN_WIDTH)) self.setZValue(styles.ZSELECTION) self.drag_start_position = QPointF() self.drag_last_position = QPointF()
def draw_sep_area(self, centers: np.ndarray, show_symbols=False): x = self.sceneRect().x() y = self.sceneRect().y() w = self.sceneRect().width() h = self.sceneRect().height() reversed_centers = list(reversed(centers)) num_areas = len(centers) + 1 if num_areas != len(self.separation_areas): for area in self.separation_areas: self.removeItem(area) self.separation_areas.clear() for i in range(num_areas): area = QGraphicsRectItem(0, 0, 0, 0) if i % 2 == 0: area.setBrush(settings.ZEROS_AREA_COLOR) else: area.setBrush(settings.ONES_AREA_COLOR) area.setOpacity(settings.SEPARATION_OPACITY) area.setPen(QPen(settings.TRANSPARENT_COLOR, 0)) self.addItem(area) self.separation_areas.append(area) start = y for i, area in enumerate(self.separation_areas): area.show() try: self.separation_areas[i].setRect( x, start, w, abs(start - reversed_centers[i])) start += abs(start - reversed_centers[i]) except IndexError: self.separation_areas[i].setRect(x, start, w, abs(start - h)) if self.noise_area is not None: self.noise_area.hide() self.centers = centers self.redraw_legend(show_symbols)
def display_markers(self): """Add markers on top of first plot.""" for item in self.idx_markers: self.scene.removeItem(item) self.idx_markers = [] window_start = self.parent.value('window_start') window_length = self.parent.value('window_length') window_end = window_start + window_length y_distance = self.parent.value('y_distance') markers = [] if self.parent.info.markers is not None: if self.parent.value('marker_show'): markers = self.parent.info.markers for mrk in markers: if window_start <= mrk['end'] and window_end >= mrk['start']: mrk_start = max((mrk['start'], window_start)) mrk_end = min((mrk['end'], window_end)) color = QColor(self.parent.value('marker_color')) item = QGraphicsRectItem(mrk_start, 0, mrk_end - mrk_start, len(self.idx_label) * y_distance) item.setPen(color) item.setBrush(color) item.setZValue(-9) self.scene.addItem(item) item = TextItem_with_BG(color.darker(200)) item.setText(mrk['name']) item.setPos(mrk['start'], len(self.idx_label) * self.parent.value('y_distance')) item.setFlag(QGraphicsItem.ItemIgnoresTransformations) item.setRotation(-90) self.scene.addItem(item) self.idx_markers.append(item)
def generateMap(self): # save block textures self.blockTextures = self.config.blockTextures # set up the field self.field = QGraphicsRectItem(0, 0, 520, 520) self.field.setZValue(-1) self.field.setBrush(Qt.black) self.field.setX(40) self.field.setY(20) self.scene.addItem(self.field) # save these for later use self.fieldCenterX = self.field.x() + ( self.field.boundingRect().width() - 1) / 2 self.fieldBottom = self.field.y() + self.field.boundingRect().height( ) - 1 self.baseBlocks = [] # set up the map for b in self.config.maps[f"map{self.currentMap}"]["blueprint"]: blockX = b["xCoord"] blockY = b["yCoord"] blockType = b["type"] blockIsBase = b["isBaseBlock"] block = Block(blockX, blockY, blockType, blockIsBase, self.blockTextures) # hold reference to base blocks if block.isBaseBlock: self.baseBlocks.append(block) # setting z value to be higher than others so the tanks would appear under the bush if blockType == BlockType.bush: block.setZValue(2) # setting z value lower than others so the tanks would appear above the ice elif blockType == BlockType.ice: block.setZValue(-1) self.scene.addItem(block) # add the base self.base = Base(self.config.baseTextures["aliveBase"], self.config.baseTextures["deadBase"]) self.base.setX(self.fieldCenterX - self.base.aliveImage.width() / 2) self.base.setY(self.fieldBottom - self.base.aliveImage.height()) self.scene.addItem(self.base)
def drawPiano(self): piano_keys_width = self.piano_width - self.padding labels = ('B','Bb','A','Ab','G','Gb','F','E','Eb','D','Db','C') black_notes = (2,4,6,9,11) piano_label = QFont() piano_label.setPointSize(6) self.piano = QGraphicsRectItem(0, 0, piano_keys_width, self.piano_height) self.piano.setPos(0, self.header_height) self.addItem(self.piano) key = PianoKeyItem(piano_keys_width, self.note_height, 78, self.piano) label = QGraphicsSimpleTextItem('C9', key) label.setPos(18, 1) label.setFont(piano_label) key.setBrush(QColor(255, 255, 255)) for i in range(self.end_octave - self.start_octave, 0, -1): for j in range(self.notes_in_octave, 0, -1): note = (self.end_octave - i + 3) * 12 - j if j in black_notes: key = PianoKeyItem(piano_keys_width/1.4, self.note_height, note, self.piano) key.setBrush(QColor(0, 0, 0)) key.setZValue(1.0) key.setPos(0, self.note_height * j + self.octave_height * (i - 1)) elif (j - 1) and (j + 1) in black_notes: key = PianoKeyItem(piano_keys_width, self.note_height * 2, note, self.piano) key.setBrush(QColor(255, 255, 255)) key.setPos(0, self.note_height * j + self.octave_height * (i - 1) - self.note_height/2.) elif (j - 1) in black_notes: key = PianoKeyItem(piano_keys_width, self.note_height * 3./2, note, self.piano) key.setBrush(QColor(255, 255, 255)) key.setPos(0, self.note_height * j + self.octave_height * (i - 1) - self.note_height/2.) elif (j + 1) in black_notes: key = PianoKeyItem(piano_keys_width, self.note_height * 3./2, note, self.piano) key.setBrush(QColor(255, 255, 255)) key.setPos(0, self.note_height * j + self.octave_height * (i - 1)) if j == 12: label = QGraphicsSimpleTextItem('{}{}'.format(labels[j - 1], self.end_octave - i + 1), key) label.setPos(18, 6) label.setFont(piano_label) self.piano_keys.append(key)
def __init__(self, model_part: NucleicAcidPartT, part_item: PathNucleicAcidPartItemT): """ Args: model_part: part_item: """ super(QGraphicsRectItem, self).__init__(BASE_RECT, part_item.proxy()) self.setAcceptHoverEvents(True) self.setBrush(getBrushObj(styles.BLUE_FILL, alpha=12)) self.setPen(getNoPen()) self.setZValue(styles.ZWORKPLANE) self._model_part = model_part self._part_item = part_item self._low_drag_bound = 0 # idx, not pos self._high_drag_bound = model_part.getProperty( 'max_vhelix_length') # idx, not pos self._moving_via_handle = False self.outline = PathWorkplaneOutline(self) self.resize_handle_group = ResizeHandleGroup(self.rect(), self._HANDLE_SIZE, styles.BLUE_STROKE, True, HandleEnum.LEFT | HandleEnum.RIGHT, self, translates_in=AxisEnum.X) # Minimum size hint (darker internal rect, visible during resizing) self.model_bounds_hint = m_b_h = QGraphicsRectItem(self) m_b_h.setBrush(getBrushObj(styles.BLUE_FILL, alpha=64)) m_b_h.setPen(getNoPen()) m_b_h.hide() # Low and high idx labels self.resize_handle_group.updateText(HandleEnum.LEFT, self._idx_low) self.resize_handle_group.updateText(HandleEnum.RIGHT, self._idx_high)
def init_ui(self): scene = QGraphicsScene() scene.setBackgroundBrush(QColor(100, 100, 100)) scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex) scene.setSceneRect(scene.itemsBoundingRect()) self.setDragMode(QGraphicsView.RubberBandDrag) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) self.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) self.frame_item = QGraphicsPixmapItem() self.text_item_offset = 0 self.rect_item_array = [] self.text_item_array = [] for i in range(0, 5): rect_item = QGraphicsRectItem() rect_item.setVisible(False) rect_item.setZValue(20.0) rect_item.setPen(QPen(Qt.red, 5)) rect_item.setRect(20, 20, 20, 20) scene.addItem(rect_item) self.rect_item_array.append(rect_item) text_item = QGraphicsSimpleTextItem("") text_item.setBrush(QBrush(Qt.red)) text_item.setZValue(20.0) text_item.setPos(10, 50) text_item.setFont(QFont("黑体", 32)) text_item.setVisible(False) scene.addItem(text_item) self.text_item_array.append(text_item) scene.addItem(self.frame_item) self.curr_factor = 1.0 self.setScene(scene)
def __init__(self): QGraphicsView.__init__(self) # Image is displayed as a QPixmap in a QGraphicsScene attached to this QGraphicsView. self.scene = QGraphicsScene() self.setScene(self.scene) self.rectgroup = QGraphicsItemGroup() self.linegroup = QGraphicsItemGroup() self._pixmapHandle = None self.canZoom = True self.canPan = True self.zoomStack = [] self.aspectRatioMode = Qt.KeepAspectRatio self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.begin = QPoint() self.end = QPoint() self.helper_bool = False self.helper_bool2 = False self.rect = QGraphicsRectItem() self.line = QGraphicsLineItem()
def __init__(self): super(MainController, self).__init__() self.ser = Serial(WIFLY_SERIAL_PORT, WIFLY_BAUD_RATE) self.wiflyReceiver = WiflyReceiver(self.ser) self.wiflySender = WiflySender(self.ser) self.rover = Rover() self.mainWidget = MainWidget() self.wiflyReceiverThread = QThread() self.wiflyReceiver.moveToThread(self.wiflyReceiverThread) self.wiflySenderThread = QThread() self.wiflySender.moveToThread(self.wiflySenderThread) self.simState = SIMULATION_STATE_PHASE_1 self.simTimer = QTimer() self.simTimer.setSingleShot(True) self.wiflyReceiver.msgReceived.connect(self.mainWidget.appendMsg) self.wiflyReceiver.msgReceived.connect(self.rover.processData) self.newCommand.connect(self.wiflySender.sendMsg) self.appStart.connect(self.wiflyReceiver.processMsg) self.mainWidget.ui.gearSlider.valueChanged.connect( self.manualGearChange) self.mainWidget.ui.upButton.clicked.connect(self.manualMoveForward) self.mainWidget.ui.downButton.clicked.connect(self.manualMoveBackward) self.mainWidget.ui.leftButton.clicked.connect(self.manualMoveLeft) self.mainWidget.ui.rightButton.clicked.connect(self.manualMoveRight) self.mainWidget.ui.brakeButton.clicked.connect(self.manualStop) self.mainWidget.ui.simulationButton.clicked.connect( self.simulationStart) self.rover.newRoverPosition.connect(self.drawRover) self.rover.newWallDetected.connect(self.drawNewWall) self.simTimer.timeout.connect(self.simulationUpdate) self.mapScene = QGraphicsScene(0, 0, WORLD_X / CANVAS_RATIO, WORLD_Y / CANVAS_RATIO) self.mainWidget.ui.mappingGraphicsView.setScene(self.mapScene) self.roverRect = QGraphicsRectItem() self.mapScene.addItem(self.roverRect) """
def __init__(self, strand_item, virtual_helix_item): """ strand_item is a the model representation of the 5prime most strand of a Xover """ super(XoverItem, self).__init__(virtual_helix_item.partItem()) self._strand_item = strand_item self._virtual_helix_item = virtual_helix_item self._strand5p = None self._node5 = None self._node3 = None self.hide() # for easier mouseclick self._click_area = c_a = QGraphicsRectItem(self) # self._click_area.setAcceptHoverEvents(True) # c_a.hoverMoveEvent = self.hoverMoveEvent c_a.mousePressEvent = self.mousePressEvent c_a.mouseMoveEvent = self.mouseMoveEvent c_a.setPen(QPen(Qt.NoPen)) self._getActiveTool = strand_item._getActiveTool
def animation(self, robot_point=[0, 0]): w,h = self.init_graphicsView() robot_point[0] = robot_point[0] * 100 robot_point[1] = robot_point[1] * 100 """ 砖摆放,从x,y轴出发 """ for j in range(height_num): for i in range(width_num): self.brick_x = i*(self.brick_gap+brick_width) self.brick_y = j*(self.brick_gap+brick_height) rectangle_item = QGraphicsRectItem( self.brick_x, self.brick_y, brick_width, brick_height) scene.addItem(rectangle_item) # print(bricks) # 动态画出铺砖的轨迹 red_brush = QBrush(QColor.fromRgb(255, 0, 0)) white_brush = QBrush(QColor.fromRgb(255,255,255)) for k in range(height_num * width_num): if robot_point[0] >= bricks[k][2] and robot_point[0] <= bricks[k][2] + brick_width and robot_point[1] >= bricks[k][3] and robot_point[1] <= bricks[k][3] + brick_height: bricks[k][4] = 1 self.brickTable.setItem(k, 3, QTableWidgetItem("1")) # else: # bricks[k][4] = 0 for brick in bricks: # 铺完一块砖就覆盖颜色 if brick[4] == 1: scene.addRect(brick[2], brick[3], brick_width, brick_height, brush = red_brush) else: scene.addRect(brick[2], brick[3], brick_width, brick_height, brush = white_brush) # scene.addRect(0, 0, w, h) # 一定要画出最外的矩形区域 robot_item = QGraphicsEllipseItem( robot_point[0], robot_point[1], 10, 10) robot_item.setBrush(QBrush(QColor.fromRgb(0, 255, 255))) scene.addItem(robot_item)
def mousePressEvent(self, event): QGraphicsScene.mousePressEvent(self, event) if self.piano.contains(event.scenePos()): item = self.itemAt(event.scenePos(), QTransform()) if isinstance(item, PianoKeyItem) and item.note is not None: self.last_piano_note = item.note self.noteclicked.emit(self.last_piano_note, True) return if not (any(key.pressed for key in self.piano_keys) or any(note.pressed for note in self.notes)): for note in self.selected_notes: note.setSelected(False) self.selected_notes = [] if event.button() == Qt.LeftButton: if self.insert_mode: self.place_ghost = True else: self.marquee_select = True self.marquee_rect = QRectF(event.scenePos().x(), event.scenePos().y(), 1, 1) self.marquee = QGraphicsRectItem(self.marquee_rect) self.marquee.setBrush(QColor(255, 255, 255, 100)) self.addItem(self.marquee) else: for s_note in self.notes: if s_note.pressed and s_note in self.selected_notes: break elif s_note.pressed and s_note not in self.selected_notes: for note in self.selected_notes: note.setSelected(False) self.selected_notes = [s_note] break for note in self.selected_notes: if not self.velocity_mode: note.mousePressEvent(event)
def __init__(self, tool: SelectGridTool, parent: GridNucleicAcidPartItemT = None): """ Args: tool: the selection tool parent: default is ``None``. a :class:`GridNucleicAcidPartItem` """ super(GridSelectionGroup, self).__init__(parent) self.tool = tool self.setFiltersChildEvents(True) self.setFlag(QGraphicsItem.ItemIsFocusable) # for keyPressEvents self.setFlag(QGraphicsItem.ItemIsMovable) self.bounding_rect_item = bri = QGraphicsRectItem(tool) bri.hide() bri.setPen(getPenObj(_SELECT_COLOR, _SELECT_PEN_WIDTH)) self.setZValue(styles.ZSELECTION) self.drag_start_position = QPointF() self.drag_last_position = QPointF()
def show_tiles(self): """ Show tiles in two files """ self.cells = [] for row in range(Cons.SIZE): for col in range(Cons.SIZE): self.cells.append([ Cons.BOARD[0] + (Cons.MARGIN + Cons.WIDTH) * col + Cons.MARGIN, (Cons.MARGIN + Cons.HEIGHT) * row + Cons.MARGIN, Cons.BOARD[0] + (Cons.MARGIN + Cons.WIDTH) * col + Cons.MARGIN + Cons.WIDTH, (Cons.MARGIN + Cons.HEIGHT) * row + Cons.MARGIN + Cons.HEIGHT ]) square = QGraphicsRectItem( Cons.BOARD[0] + (Cons.MARGIN + Cons.WIDTH) * col + Cons.MARGIN, (Cons.MARGIN + Cons.HEIGHT) * row + Cons.MARGIN, Cons.WIDTH, Cons.HEIGHT) self.scene.addItem(square) self.show_alphabet(0, r"\scrabble_letters.png") self.show_alphabet(4, r"\xscrabble_letters.png")
def pressSnapRight(self): # To remove previous graphics rectangle try: self._ui.selectedSlide_graphicsView.removeItem(self.rightRect) except AttributeError: pass rightWell = self._ui.rightWell_spinBox.value() # To not crash if no slide is selected try: self.rightRect = QGraphicsRectItem( self.slide.rightPositions[rightWell - 1][0], self.slide.rightPositions[rightWell - 1][1], 400, 400) except AttributeError: print("Select a slide first") return self.rightRect.setBrush(QColor("yellow")) # Get xyz positions on Snap self.zPositionRight = self.connx.core.getPosition() self.xPositionRight = self.connx.core.getXPosition() self.yPositionRight = self.connx.core.getYPosition() self.connx.core.snapImage() tagged_image = self.connx.core.getTaggedImage() pixels_flat = tagged_image[0] metadata = tagged_image[1] pixels = np.reshape(pixels_flat, newshape=[metadata['Height'], metadata['Width']]) self.pixelsRight = np.rot90(pixels) self.pixels_imageRight = pg.ImageItem(self.pixelsRight) self._ui.rightImage_graphicsView.view.setMouseEnabled(x=False, y=False) self._ui.rightImage_graphicsView.view.addItem(self.pixels_imageRight) self._ui.selectedSlide_graphicsView.view.addItem(self.rightRect) print('R')
def __init__(self, simu, f, motion_manager): """AircraftItem constructor, creates the ellipse and adds to the scene""" super().__init__(None) self.setZValue(radarview.PLOT_Z_VALUE) # instance variables self.motion_manager = motion_manager self.flight = f self.simulation = simu # list to store the comet elements as ellipses self.comete = [] # create the tooltip tooltip = f.type.name + ' ' + f.call_sign + ' ' + f.qfu time = self.simulation.t for (idx, ti) in enumerate(range(time - 4, time + 1)): if idx < 4: item = QGraphicsRectItem() item.setPen(DEP_PEN if self.flight.type == traffic.Movement.DEP else ARR_PEN) else: item = QGraphicsEllipseItem() item.setBrush(DEP_BRUSH if self.flight.type == traffic.Movement.DEP else ARR_BRUSH) item.setToolTip(tooltip) self.comete.append(item) self.addToGroup(item) position = self.flight.get_position(ti) item.setPos(position.x, position.y) # compute the width of each element self.update_size() # connect to ask_inspection_signal in order to toggle_highlight this item self.motion_manager.radarView.ask_inspection_signal.connect( self.toggle_highlight)
def drawIt(self, ): # get current format as it may have changed self.getFormat() # create the qgraphicsItems if they don't exist if self.TNode is None: # create the rectangle self.TNode = QGraphicsRectItem(QRectF( self.x, self.y, self.nodeFormat.formatDict["nodeWidth"], self.nodeFormat.formatDict["nodeHeight"]), parent=None) self.TNode.setZValue(NODELAYER) self.TNode.setFlag(QGraphicsItem.ItemIsMovable, True) self.TNode.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.TNode.setFlag(QGraphicsItem.ItemIsSelectable, True) self.TNode.setSelected(True) self.TNode.setData(1, self.NZID) # get with self.INode.data(1) self.TNode.setData(ITEMTYPE, NODETEMPLATE) # create the text box self.TNtext = QGraphicsTextItem("", parent=None) self.TNtext.setPos(self.x, self.y) self.TNtext.setFlag(QGraphicsItem.ItemIsMovable, True) self.TNtext.setFlag(QGraphicsItem.ItemIsSelectable, False) self.TNtext.setData(NODEID, self.NZID) self.TNtext.setData(ITEMTYPE, NODETEMPLATETEXT) self.TNtext.setZValue(NODELAYER) # save the location self.x = self.TNode.sceneBoundingRect().x() self.y = self.TNode.sceneBoundingRect().y() # generate the html and resize the rectangle self.formatItem() # add the graphics items to the scene self.scene.addItem(self.TNode) self.scene.addItem(self.TNtext) else: # generate the html and resize the rectangle self.formatItem()