def draw_move_2(self): if (self.my_counter == 200): self.my_counter = 0 self.my_counter += 1 self.moveTeta = self.my_counter * np.pi / 100 self.movePhi = np.pi + self.Hook*self.moveTeta*0.5 #Создание кубита. Рисование сферы и осей plt.close() fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_wireframe(self.x, self.y, self.z, color="black", lw=0.5) frame1 = plt.gca() frame1.axes.xaxis.set_ticklabels([]) frame1.axes.yaxis.set_ticklabels([]) frame1.axes.zaxis.set_ticklabels([]) x, y, z = self.convert_3d_plot_move(0, 0, 1) ax.quiver(0, 0, 0, x, y, z, length=1.0, color='red', lw=4) ax.quiver(0, 0, 0, 0, 0, 1.7, length=1.0, color='green', lw=1) ax.text(0, 0, 1.8, 'Z', rotation=38, fontsize=10) ax.text(0, 0, 1.2, '|0>', rotation=38, fontsize=13, color='red') ax.text(0, 0, -1.2, '|1>', rotation=38, fontsize=13, color='red') ax.quiver(0, 0, 0, 0, -1.7, 0, length=1.0, color='green', lw=1) ax.text(0, -1.8, 0, 'X', rotation=38, fontsize=10) ax.quiver(0, 0, 0, 1.7, 0, 0, length=1.0, color='green', lw=1) ax.text(1.8, 0, 0, 'Y', rotation=38, fontsize=10) ax.view_init(elev=self.moveAlpha3D, azim=self.moveBeta3D) ax.dist = 9 ax.grid(False) scene = QGraphicsScene(self) scene.setSceneRect(100, 100, 300, 300) canvas = FigureCanvas(fig) canvas.setGeometry(0, 0, 500, 500) scene.addWidget(canvas) self.graphicsView_2.setScene(scene) self.label_3.setText(f'{round(np.cos(self.moveTeta/2) ** 2, 4)}') self.label_4.setText(f'{round(np.sin(self.moveTeta/2) ** 2, 4)}')
def reset_canvas_action(self): if self.canvas_widget.drawing != 0: return num1, ok1 = QInputDialog.getInt(self, '获取宽度', '输入您的宽度(100~1000)', 600, 100, 1000, 1) if ok1: num2, ok2 = QInputDialog.getInt(self, '获取高度', '输入您的高度(100~1000)', 600, 100, 1000, 1) if ok1 and ok2: # 清空画布 self.list_widget.clear() self.item_cnt = 0 self.canvas_widget.action_stack = [] self.canvas_widget.temp_id = self.get_id() # 更改画布大小 self.scene = QGraphicsScene(self) self.scene.setSceneRect(0, 0, num1, num2) self.canvas_widget.setScene(self.scene) self.canvas_widget.setFixedSize(num1 + 2, num2 + 2)
def __init__(self, diagramType, project, path="", parent=None, initBuilder=True, **kwargs): """ Constructor @param diagramType type of the diagram (one of ApplicationDiagram, ClassDiagram, ImportsDiagram, NoDiagram, PackageDiagram) @param project reference to the project object (Project) @param path file or directory path to build the diagram from (string) @param parent parent widget of the dialog (QWidget) @keyparam initBuilder flag indicating to initialize the diagram builder (boolean) @keyparam kwargs diagram specific data """ super(UMLDialog, self).__init__(parent) self.setObjectName("UMLDialog") self.__diagramType = diagramType self.__project = project from .UMLGraphicsView import UMLGraphicsView self.scene = QGraphicsScene(0.0, 0.0, 800.0, 600.0) self.umlView = UMLGraphicsView(self.scene, parent=self) self.builder = self.__diagramBuilder(self.__diagramType, path, **kwargs) if self.builder and initBuilder: self.builder.initialize() self.__fileName = "" self.__initActions() self.__initToolBars() self.setCentralWidget(self.umlView) self.umlView.relayout.connect(self.__relayout) self.setWindowTitle(self.__diagramTypeString())
def showpic(self, fileName, isCurrent): img = QImage() QImage.load(img, fileName) if img.width() > self.originImg.width(): img = img.scaled( self.originImg.width(), img.height() * self.originImg.width() / img.width()) if img.height() > self.originImg.height(): img = img.scaled( img.width() * self.originImg.height() / img.height(), self.originImg.height()) scene = QGraphicsScene() # 创建场景 scene.addPixmap(QPixmap.fromImage(img)) if isCurrent == True: self.currentImg.setScene(scene) # 将场景添加至视图 self.currentImg.show() else: self.originImg.setScene(scene) # 将场景添加至视图 self.originImg.show()
def __init__(self, parent=None): super(Lighting, self).__init__(parent) self.angle = 0.0 self.m_scene = QGraphicsScene() self.m_lightSource = None self.m_items = [] self.setScene(self.m_scene) self.setupScene() timer = QTimer(self) timer.timeout.connect(self.animate) timer.setInterval(30) timer.start() self.setRenderHint(QPainter.Antialiasing) self.setFrameStyle(QFrame.NoFrame)
def __init__(self, parent): super(PageViewer, self).__init__(parent) self._page = None # todo: add all these constants to preferences dialog self._zoom = 0 self._zoomMaxDistance = 10 self._zoomInFactor = 1.25 self._zoomOutFactor = 0.8 self._panDivisor = 2 self._toolMode = ToolMode.NOTHING self._previousToolModeDrag = ToolMode.NOTHING self._drawing = False self._dragStart = None self._drawPoint = None self._lastPenPos = None self._scene = QGraphicsScene(self) self._pageLayer = None self._drawingLayer = None self._predrawPixmap = None self._eraserSize = 100 self._eraserEllipse = self.getEraserEllipse() pen_brush = QBrush(QColor('red'), Qt.SolidPattern) self._pen = QPen(pen_brush, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) self._increaseSizeAction = QAction('Increase tool size', self) self._increaseSizeAction.setEnabled(False) self._increaseSizeAction.triggered.connect( self.onIncreaseSizeActionTriggered) self._decreaseSizeAction = QAction('Decrease tool size', self) self._decreaseSizeAction.setEnabled(False) self._decreaseSizeAction.triggered.connect( self.onDecreaseSizeActionTriggered) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QGraphicsView.AnchorUnderMouse) self.setMouseTracking(True)
def setup_ui(self): sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) self.stream_item = QGraphicsPixmapItem() self.stream_item.setZValue(-1) self.scene = QGraphicsScene(self) self.scene.setSceneRect(0., 0., float(self.size.width()), float(self.size.height())) self.scene.addItem(self.stream_item) self.widget = QGraphicsView(self.parent) self.widget.setSizePolicy(sizePolicy) self.widget.setMinimumSize(self.size) self.widget.setBaseSize(self.size) self.widget.setObjectName("graphicsViewCameraStream") self.widget.setTransformationAnchor(0) self.widget.setScene(self.scene) self.widget.setInteractive(True) self.widget.setMouseTracking(True)
def initUI(self, fname): # Grab the image filename. self.fname = fname # Set up a QGraphicsScene and QGraphicsView self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) # Create a pixmap of the file and corresponding item self.image = QPixmap(self.fname) self.imageItem = QGraphicsPixmapItem(self.image) self.imageItem.setTransformationMode(Qt.SmoothTransformation) # Set scene dimensions to that of the image. self.scene.setSceneRect(0, 0, self.image.width(), self.image.height()) # Set the view to encompass the image. self.scene.addItem(self.imageItem) self.view.fitInView(self.imageItem, Qt.KeepAspectRatio) # Spinbox for entering the number of pages in the image self.partL = QLabel("Number of pages") self.partSB = QSpinBox() self.partSB.setValue(1) self.partSB.setRange(1, 9) # Buttons and connections to functions self.splitB = QPushButton("Split") self.splitB.clicked.connect(self.splitIt) self.acceptB = QPushButton("Accept") self.acceptB.clicked.connect(self.acceptIt) self.cancelB = QPushButton("Cancel") self.cancelB.clicked.connect(self.reject) # The void button will become a flip button for each page self.voidB = QPushButton() self.voidB.setEnabled(False) # lay out buttons etc self.grid = QGridLayout() self.grid.addWidget(self.partL, 1, 1) self.grid.addWidget(self.partSB, 1, 2) self.grid.addWidget(self.view, 1, 3, 3, 3) self.grid.addWidget(self.voidB, 5, 3, 1, 3) self.grid.addWidget(self.splitB, 2, 1, 2, 1) self.grid.addWidget(self.acceptB, 10, 2) self.grid.addWidget(self.cancelB, 10, 1) self.setLayout(self.grid) self.show()
def init_spec_view(self, parent, label, graph=None): if label: ql = QLabel() ql.setAlignment(QtCore.Qt.AlignTop) ql.setAlignment(QtCore.Qt.AlignCenter) ql.setText(label) parent.addWidget(ql) spc_gv = QGraphicsView() parent.addWidget(spc_gv) scene = QGraphicsScene(self) spc_gv.setScene(scene) spc_gv.setAlignment(QtCore.Qt.AlignCenter) if graph: scene.addItem(graph) # spc_gv.setFixedSize(config.WINDOW_WIDTH/4, config.WINDOW_HEIGHT/4) return scene
def draw(self, reset_scale): scene = QGraphicsScene() scene.addItem(self.pixmap_item) for annotation in self.annotations: score = annotation.get('score') if score is not None: if score < self.threshold: continue bbox = annotation['bbox'] self.preprocess_box(bbox, self.pixmap_item.pixmap().width(), self.pixmap_item.pixmap().height()) text = self.category_id_to_name[annotation['category_id']] if score is not None: text = text + ' {:.2f}'.format(score) rect_item = QGraphicsRectItem(bbox[0], bbox[1], bbox[2], bbox[3]) text_item = QGraphicsTextItem(text) text_item.setPos(bbox[0], bbox[1]) scene.addItem(rect_item) scene.addItem(text_item) self.boxesDrawn.emit(scene, reset_scale)
def init_UI(self): self._zoom = 0 # 定义图片的放大级别 self._empty = True # 定义是否含有图片(点击模式和拖动模式切换) self._contour = False # 定义轮廓拖动模式 0 self._ocr = False # 定义文字识别模式 self._scene = QGraphicsScene(self) # 新建一个场景 self._photo = QGraphicsPixmapItem() # 新建一个图像图元 self._scene.addItem(self._photo) # 图像图元添加到场景中 self.setScene(self._scene) # 场景添加到视图中 self.setTransformationAnchor( QGraphicsView.AnchorUnderMouse) # 坐标转换时以鼠标所在位置为中心 self.setResizeAnchor( QGraphicsView.AnchorUnderMouse) # 视图大小调整时该如何定位其中的场景 self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 垂直滚动条关闭 self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 平行滚动条关闭 self.setBackgroundBrush(QBrush(QColor(30, 30, 30))) # 背景色 self.setFrameShape(QFrame.NoFrame) # 设置QFrame在它的内容周围画一个框
def __init__(self, *, parent: QWidget, color: Qt.GlobalColor = Qt.yellow, num_cols: int = 1, num_rows: int = 1): """ Initialize a `GridView` inside a `GridWindow`, on which che user can draw `AdjustableGrid`s. Parameters ---------- parent : QWidget Qt parent widget (expected type `GridWindow`). color : Qt.GlobalColor Grid colors. Default `Qt.yellow` num_cols : int Grid column number. Default 8. num_rows : int Grid row number. Default 12. """ super().__init__(parent=parent) """Window properties""" self.setGeometry(0, 0, 500, 500) # self.setWindowTitle('Left click to top left grid corner') """W/o the following flag, mouseMove is invoked only w click+move""" self.setMouseTracking(True) """Scene""" self.scene = QGraphicsScene() self.setSceneRect(0, 0, 500, 500) self.setScene(self.scene) """Grids""" self.placed_grids = [] self.color = color self.num_cols = num_cols self.num_rows = num_rows self.current_grid = AdjustableGrid(scene=self.scene, color=self.color, num_cols=self.num_cols, num_rows=self.num_rows) self.parent = self.parentWidget()
def set_signal(self): indx = self.ui.combobox_signals.currentIndex() if indx != 0: self.ui.inpt.setReadOnly(True) else: self.ui.inpt.setReadOnly(False) self.ui.inpt.setText("10010110") self.decoder_update() return signal = self.signals[indx-1] pa = ProtocolAnalyzer(signal) pa.get_protocol_from_signal() self.ui.inpt.setText("".join(pa.decoded_proto_bits_str)) tmp_scene = QGraphicsScene() tmp_scene.addText(self.tr("Loading Signal...")) QApplication.setOverrideCursor(Qt.WaitCursor) self.ui.graphicsView_signal.setScene(tmp_scene) QApplication.processEvents() # scene = ZoomableScene() if signal is not None: last_block = pa.blocks[-1] lookup = pa.bit_sample_pos plot_data = signal.qad[lookup[0][0]:lookup[pa.num_blocks - 1][len(last_block) - 1]] self.ui.graphicsView_signal.plot_data(plot_data) # num_samples = len(plot_data) # minimum = -numpy.max(plot_data) # maximum = -numpy.min(plot_data) # scene.setSceneRect(0, minimum, num_samples, maximum - minimum) # scene.setBackgroundBrush(constants.BGCOLOR) # scene.addLine(0, 0, num_samples, 0, constants.AXISCOLOR) # precise_path = path_creator.create_precise_path(plot_data) # for subpath in precise_path: # scene.addPath(subpath, constants.LINECOLOR) # self.ui.graphicsView_signal.setScene(scene) # self.ui.graphicsView_signal.update() # self.ui.graphicsView_signal.scale(1, 1) self.ui.graphicsView_signal.centerOn(0, 0) QApplication.restoreOverrideCursor()
def __init__(self,winParent): QGraphicsView.__init__(self) self.winParent=winParent self.viewUpdate.connect(self.update) self.m_hour = 0 self.m_min = 0 self.m_sec = 0 self.m_scaleX = 0 self.m_scaleY = 0 self.m_originalHeight = 245 self.m_originalWidth = 245 self.m_originalFdCtr = QPointF(120,120) self.m_originalMarkCtr = QPointF(120, 120) self.m_faceZ = -20 self.m_handZ = -10 self.m_caseZ = 10 self.m_mark1Z = 20 self.m_mark2Z = 30 self.m_mark3Z = 40 self.m_itemHand = None self.m_itemFace = None self.m_itemCase = None self.m_itemMark1 = None self.m_itemMark2 = None self.m_itemMark3 = None self.setStyleSheet("background: transparent; border: none"); self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setInteractive(False) self.setEnabled(False) self.m_scene = QGraphicsScene(self) self.setScene(self.m_scene) self.init()
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 generate_scene(self, m: KLMap) -> None: '''Generate a QGraphicScene object from a map and fills up the scene_item_dict''' new_scene = QGraphicsScene(0, 0, m.w * TILE_SIZE, m.h * TILE_SIZE) self.setScene(new_scene) del self.scene_item_dict if self.m_scene: del self.m_scene self.m_scene = new_scene self.scene_item_dict = {} # set the background color <=> fill self.m_scene.setBackgroundBrush(Qt.black) pix = QPixmap(TILE_SIZE, TILE_SIZE) mask = QBitmap(TILE_SIZE, TILE_SIZE) for x in range(m.w): for y in range(m.h): pid = m.pid(x, y) if pid == Piece.space: continue # We pass the pixmap and bitmap object to avoid recreating them # on each function call self.set_tile_pix(pix, mask, x, y) item = QGraphicsPixmapItem(pix) item.setX(x * TILE_SIZE) item.setY(y * TILE_SIZE) self.m_scene.addItem(item) # moving tiles are above walls, special walls # and goals if pid == Piece.goal or pid == Piece.wall or pid == Piece.s_wall: item.setZValue(1) else: item.setZValue(10) if pid not in self.scene_item_dict: self.scene_item_dict[pid] = [] self.scene_item_dict[pid].append(item) item.show()
def initUI(self): self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.grafickascena = QGraphicsScene() self.grafickascena.setSceneRect(0, 0, 1000, 850) self.setbackground() self.playbutton = StyleButton('PNG/Buttons/Play_BTN.png', 'Play', 40, 40) self.playbutton.clicked.connect(self.drawBoard) self.backbutton = StyleButton('PNG/Buttons/Close_BTN.png', 'Back', 40, 40) self.backbutton.clicked.connect(self.backbuttonClick) self.holder = QVBoxLayout() self.playersLayout = QHBoxLayout() self.buttonsLayout = QHBoxLayout() self.titleLabel = QLabel() self.titleLabel.setText("ENTER A NAME AND CHOOSE A CAR:") self.titleLabel.setStyleSheet( 'color: yellow; font-weight: bold; background: transparent;') self.titleLabel.setAlignment(Qt.AlignCenter) self.buttonsLayout.addWidget(self.playbutton) self.buttonsLayout.addWidget(self.backbutton) self.buttonsLayout.setAlignment(Qt.AlignCenter) self.infoLabel = QLabel() self.infoLabel.setStyleSheet( 'color: yellow; font-weight: bold; background: transparent;') self.infoLabel.setAlignment(Qt.AlignCenter) self.holder.addWidget(self.titleLabel) self.holder.addLayout(self.playersLayout) self.holder.addWidget(self.infoLabel) self.holder.addLayout(self.buttonsLayout) self.setLayout(self.holder) self.setScene(self.grafickascena)
def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) self.ui = uic.loadUi("gui_window/gui_1_quad.ui", self) self.ui.show() self.srv_reset = rospy.ServiceProxy("/gazebo/set_model_state", SetModelState) rospy.Subscriber("/iris_cam_1/image_raw", Image, camera_callback_1) agent1.OT = Offboard_thread(idx_uav=1) self.slider_roll_1 = self.horizontalSlider_roll_1 self.slider_pitch_1 = self.verticalSlider_pitch_1 self.slider_yaw_1 = self.horizontalSlider_yaw_1 self.slider_throttle_1 = self.verticalSlider_throttle_1 self.slider_des_x_1 = self.horizontalSlider_des_x_1 self.slider_des_y_1 = self.horizontalSlider_des_y_1 self.slider_des_z_1 = self.horizontalSlider_des_z_1 self.text_des_x_1 = self.plainTextEdit_des_x_1 self.text_des_y_1 = self.plainTextEdit_des_y_1 self.text_des_z_1 = self.plainTextEdit_des_z_1 self.text_state_x_1 = self.plainTextEdit_state_x_1 self.text_state_y_1 = self.plainTextEdit_state_y_1 self.text_state_z_1 = self.plainTextEdit_state_z_1 self.scene = QGraphicsScene() self.waypoint_run = 0 # timer for periodic update of GUI self.timer = QtCore.QTimer(self) self.timer.setInterval( 100) # Throw event timeout with an interval of 1000 milliseconds self.timer.timeout.connect( self.update_ctrl ) # each time timer counts a second, call self.blink self.color_flag = True self.timer_start()
def initUI(self): self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.grafickascena = QGraphicsScene() self.grafickascena.setSceneRect(0, 0, 1000, 850) self.setbackground() self.playbutton = StyleButton('PNG/Buttons/Play_BTN.png', 'Play', 40, 40) self.playbutton.clicked.connect(self.playbuttonclick) self.tourney2button = StyleButton('PNG/You_Win/Play_Tournament_1.png', '2 Player tournament', 40, 40) self.tourney2button.clicked.connect(self.tournament2click) self.tourney4button = StyleButton('PNG/You_Win/Play_Tournament_2.png', '4 Player tournament', 40, 40) self.tourney4button.clicked.connect(self.tournament4click) self.connectroombutton = StyleButton('PNG/Buttons/Play_BTN.png', 'Connect to host', 40, 40) self.connectroombutton.clicked.connect(self.connectRoomButtonClick) self.hostbutton = StyleButton('PNG/You_Win/Play_BTN.png', 'Host a game', 40, 40) self.hostbutton.clicked.connect(self.hostgame) self.exitbtn = StyleButton('PNG/Buttons/Close_BTN.png', 'Exit', 40, 40) self.exitbtn.clicked.connect(self.closeThis) self.grafickascena.addWidget(self.playbutton) self.grafickascena.addWidget(self.tourney2button) self.grafickascena.addWidget(self.tourney4button) self.grafickascena.addWidget(self.hostbutton) self.grafickascena.addWidget(self.connectroombutton) self.grafickascena.addWidget(self.exitbtn) self.playbutton.move(150, 250) self.tourney2button.move(150, 300) self.tourney4button.move(150, 350) self.hostbutton.move(150, 400) self.connectroombutton.move(150, 450) self.exitbtn.move(150, 500) self.setScene(self.grafickascena)
def __init__(self, preferred_size): QGraphicsView.__init__(self) self.setStyleSheet("background-color: rgb(40,40,40); border:none") self.BORDER = 10 # Image is displayed as a QPixmap in a QGraphicsScene attached to this QGraphicsView. self.scene = QGraphicsScene() self.setScene(self.scene) # Image aspect ratio mode. self.aspectRatioMode = Qt.KeepAspectRatio # Set scrollbar self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Panning is enabled if and only if the image is greater than the viewport. self.panEnabled = False # zoom is always active self.zoom_factor = 1.0 # transparency self.opacity = 1.0 self.HIGHLIGHT_RECT_WIDTH = 10 self.HIGHLIGHT_RECT_HEIGHT = 10 self.HIGHLIGHT_COLOR = QColor(200, 200, 200) self.overlay_image = QImage(self.HIGHLIGHT_RECT_WIDTH, self.HIGHLIGHT_RECT_HEIGHT, QImage.Format_ARGB32) self.overlay_image.fill(self.HIGHLIGHT_COLOR) self.pixmapitem = None self.setFixedWidth(preferred_size) self.setFixedHeight(preferred_size) self.imgwidth = 0 self.imgheight = 0 self.PREFERRED_SIZE = preferred_size
def create_2D_lens_view(self): self.scene2d = QGraphicsScene() self.create_element_model(self.scene2d) self.create_ray_model(self.scene2d) self.scene2d.setBackgroundBrush(QColor(237, 243, 254)) # light blue sceneRect2d = self.scene2d.sceneRect() print("Scene rect1:", sceneRect2d.width() / sceneRect2d.height(), sceneRect2d.x(), sceneRect2d.y(), sceneRect2d.width(), sceneRect2d.height()) # construct the top level widget widget = QWidget() # construct the top level layout layout = QVBoxLayout(widget) # set the layout on the widget widget.setLayout(layout) sub = self.mdi.addSubWindow(widget) sub.setWindowTitle("2D Lens View") view_width = 600 view_ht = 400 view_ratio = view_width / view_ht sub.setGeometry(100, 50, view_width, view_ht) self.gview2d = QGraphicsView(self.scene2d) # self.gview2d.setGeometry(100, 50, view_width, view_ht) scene_ratio = sceneRect2d.width() / sceneRect2d.height() oversize_fraction = 1.2 if scene_ratio > view_ratio: view_scale = view_width / (oversize_fraction * sceneRect2d.width()) else: view_scale = view_ht / (oversize_fraction * sceneRect2d.height()) print(view_ratio, scene_ratio, view_scale) frame_before = self.gview2d.frameGeometry() print("Frame before:", frame_before.x(), frame_before.y(), frame_before.width(), frame_before.height()) self.gview2d.scale(view_scale, view_scale) layout.addWidget(self.gview2d) sub.show()
def initUI(self): self.statusBar() self.show() scene = QGraphicsScene(self) self.graphicsView.setScene(scene) self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scene.setSceneRect(0, 0, 710, 520) pen = QPen(Qt.black, 1) self.scene = scene self.pen = pen self.scene.setBackgroundBrush(Qt.white) self.image = QImage(710, 520, QImage.Format_ARGB32_Premultiplied) self.bg_colour = Qt.white self.pen_colour = Qt.black self.image.fill(self.bg_colour) #self.scene.addLine(0,0, 400, 400, self.pen) self.make_bg_white.clicked.connect(self.colour_bg_white) self.make_bg_blue.clicked.connect(self.colour_bg_blue) self.make_bg_red.clicked.connect(self.colour_bg_red) self.make_bg_green.clicked.connect(self.colour_bg_green) self.make_bg_black.clicked.connect(self.colour_bg_black) self.make_line_black.clicked.connect(self.colour_line_black) self.make_line_blue.clicked.connect(self.colour_line_blue) self.make_line_red.clicked.connect(self.colour_line_red) self.make_line_green.clicked.connect(self.colour_line_green) self.make_line_white.clicked.connect(self.colour_line_white) self.clear_btn.clicked.connect(self.clear) self.add_point_btn.clicked.connect(self.add_point_table) self.end_btn.clicked.connect(self.end_rectangle) self.add_seed_btn.clicked.connect(self.add_seed) self.fill_btn.clicked.connect(self.start)
def __init__(self): QMainWindow.__init__(self) self.setupUi(self) style = open('light.css','r') style = style.read() self.zoomcount = 0 self.Container = Container(self.textBrowser) self.setStyleSheet(style) self.comp =componentSelector(self) self.scene = QGraphicsScene() self.scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex) self.graphicsView.setScene(self.scene) self.graphicsView.setMouseTracking(True) self.comp.show() self.setDockNestingEnabled(True) self.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea) self.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea) self.addDockWidget(Qt.BottomDockWidgetArea,self.dockWidget_2) self.pushButton.clicked.connect(partial(self.component,'MatStm')) self.graphicsView.keyPressEvent=self.deleteCall self.actionZoomIn.triggered.connect(self.zoomin) self.actionNew_Flowsheet.triggered.connect(self.new) self.actionZoomOut.triggered.connect(self.zoomout) self.actionResetZoom.triggered.connect(self.zoomReset) self.actionHelp.triggered.connect(self.help) self.actionSequential_mode.triggered.connect(partial(self.generatef,'SM')) self.actionEquation_oriented.triggered.connect(partial(self.generatef,'EQN')) self.pushButton_7.clicked.connect(partial(self.component,'Mixer')) self.pushButton_14.clicked.connect(partial(self.component,'Pump')) self.pushButton_26.clicked.connect(partial(self.component,'DistCol')) self.pushButton_18.clicked.connect(partial(self.component,'ShortCol')) self.pushButton_11.clicked.connect(partial(self.component,'Heater')) self.actionSelect_compouns.triggered.connect(self.selectCompounds) self.pushButton_10.clicked.connect(partial(self.component,'Splitter')) self.pushButton_9.clicked.connect(partial(self.component,'Flash')) self.pushButton_25.clicked.connect(partial(self.component,'Valve')) self.pushButton_12.clicked.connect(partial(self.component,'Cooler')) self.pushButton_13.clicked.connect(partial(self.component,'CompSep')) self.pushButton_15.clicked.connect(partial(self.component,'AdiaComp')) self.pushButton_16.clicked.connect(partial(self.component,'AdiaExp'))
def __init__(self, eqn: GroupedEquations, *args, my_conn: Optional[dict] = None, t_log: Optional[TimeLogger] = None, verbose: bool = False, **kwargs): super().__init__(*args, **kwargs) loadUi('equation_dialog.ui', self) # Info Widgets self.buttonbox: QDialogButtonBox = self.findChild( QDialogButtonBox, 'buttonBox') equation_list: QListWidget = self.findChild(QListWidget, 'equation_list') self.eqn_group_list: QListWidget = self.findChild( QListWidget, 'eqn_group_list') self.notes_text_edit: QTextEdit = self.findChild( QTextEdit, 'notes_text_edit') self.image_g_view: QGraphicsView = self.findChild( QGraphicsView, 'image_g_view') self.my_conn: Optional[dict] = my_connect(my_conn=my_conn, t_log=t_log, verbose=verbose) self.t_log: Optional[TimeLogger] = t_log self.eqn = eqn self._insert_button('Insert Selected') self._new_eq_button('New Equation') self.buttonbox.addButton(QDialogButtonBox.Cancel) self.scene = QGraphicsScene() self.image_g_view.setScene(self.scene) self.equation_filter_list: EDFilterListWidget = EDFilterListWidget( self) layout = equation_list.parent().layout() layout.replaceWidget(equation_list, self.equation_filter_list) self.populate_equation_list() self.equation_list.close() self.equation_filter_list.list.setSelectionMode( QAbstractItemView.ExtendedSelection) self.equation_filter_list.list.selectionModel( ).selectionChanged.connect(self.select_one_equation)
def __init__(self, parent=None): QObject.__init__(self, parent=parent) self.sliceRect = None self.bb = QRect() #bounding box enclosing the drawing self.brushSize = self.defaultBrushSize self.drawColor = self.defaultColor self._temp_color = None self._temp_number = None self.drawnNumber = self.defaultDrawnNumber self.pos = None self.erasing = False self._hasMoved = False self.drawOnto = None #an empty scene, where we add all drawn line segments #a QGraphicsLineItem, and which we can use to then #render to an image self.scene = QGraphicsScene()
def __init__(self): super(Video, self).__init__() self.resize(1920, 1080) self._item = QGraphicsVideoItem() self._view = QGraphicsView() self._scene = QGraphicsScene() self._view.resize(1920, 1080) self._view.setScene(self._scene) self._scene.addItem(self._item) self._view.show() self._item.setSize(QSizeF(1920, 1080)) self._player = QMediaPlayer(self) self._player.setMedia( QMediaContent( QUrl.fromLocalFile( '/Users/huangkai/Documents/PycharmProjects/AllTest/Qt插入背景/AddVideos/Videos/yellow.mov' ))) self._player.setVideoOutput(self._item) self._player.play() self.setCentralWidget(self._view)
def show_grayimage(self): img_cv = self.gray_image img_width, img_height = img_cv.shape ratio_img = img_width / img_height ratio_scene = self.ui.graphicsView.width( ) / self.ui.graphicsView.height() if ratio_img > ratio_scene: width = int(self.ui.graphicsView.width()) height = int(self.ui.graphicsView.width() / ratio_img) else: width = int(self.ui.graphicsView.height() * ratio_img) height = int(self.ui.graphicsView.height()) img_resize = cv2.resize(img_cv, (height - 5, width - 5), interpolation=cv2.INTER_AREA) h, w = img_resize.shape qimg = QImage(img_resize.data, w, h, w, QImage.Format_Grayscale8) self.scene = QGraphicsScene() pix = QPixmap(qimg) self.scene.addPixmap(pix) self.ui.graphicsView.setScene(self.scene)
def openFile_s(self): default_dir = r"F:" # 设置默认打开目录 global style style = tkinter.filedialog.askopenfilename( title=u"选择文件", initialdir=(os.path.expanduser(default_dir))) print(style) img = cv2.imread(style) # 读取图像 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换图像通道 x = img.shape[1] # 获取图像大小 y = img.shape[0] img_nrows = 200 img_ncols = int(y * img_nrows / x) img = cv2.resize(img, (img_nrows, img_ncols)) frame = QImage(img, img_nrows, img_ncols, QImage.Format_RGB888) #frame = QImage(img, x, y, QImage.Format_RGB888) pix = QPixmap.fromImage(frame) self.item = QGraphicsPixmapItem(pix) self.scene = QGraphicsScene() self.scene.addItem(self.item) self.graphicsView_2.setScene(self.scene)
def test(self): raw = numpy.load( os.path.join(volumina._testing.__path__[0], 'lena.npy')).astype(numpy.uint32) ars = _ArraySource2d(raw) ims = DummyItemSource(ars) req = ims.request(QRect(0, 0, 256, 256)) item = req.wait() assert isinstance(item, QGraphicsItem) DEBUG = False if DEBUG: from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene app = QApplication([]) scene = QGraphicsScene() scene.addItem(item) view = QGraphicsView(scene) view.show() view.raise_() app.exec_()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setAttribute(Qt.WA_QuitOnClose) self.setAttribute(Qt.WA_DeleteOnClose) # create instance variables self._ui = uic.loadUi("mainwindow.ui", self) self.sceneGcode = QGraphicsScene() self._ui.viewGcode.setScene(self.sceneGcode) self._cnc = list() self._geometry = list() self._gcodeModel = GcodeModel(parent=self) self._ui.tableGcode.setModel(self._gcodeModel) self._currentDir = '.' self._init()