def testQGraphicsProxyWidget(self): scene = QGraphicsScene() proxy = QGraphicsProxyWidget(None, Qt.Window) widget = QLabel('Widget') proxy.setWidget(widget) proxy.setCacheMode(QGraphicsItem.DeviceCoordinateCache) scene.addItem(proxy) scene.setSceneRect(scene.itemsBoundingRect()) view = QGraphicsView(scene) view.setRenderHints(QPainter.Antialiasing|QPainter.SmoothPixmapTransform) view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate) view.show() timer = QTimer.singleShot(100, self.app.quit) self.app.exec_()
def create_ui(self): button = QPushButton("Rotate - ", self) button.setGeometry(200, 450, 100, 50) button.clicked.connect(self.rotateMinus) button2 = QPushButton("Rotate + ", self) button2.setGeometry(320, 450, 100, 50) button2.clicked.connect(self.rotatePlus) scene = QGraphicsScene(self) greenBrush = QBrush(Qt.green) blueBrush = QBrush(Qt.blue) blackPen = QPen(Qt.black) blackPen.setWidth(5) ellipse = scene.addEllipse(10, 10, 200, 200, blackPen, greenBrush) rect = scene.addRect(-100, -100, 200, 200, blackPen, blueBrush) scene.addText("antoine-libert.com", QFont("Sanserif", 15)) ellipse.setFlag(QGraphicsItem.ItemIsMovable) rect.setFlag(QGraphicsItem.ItemIsMovable) self.view = QGraphicsView(scene, self) self.view.setGeometry(0, 0, 640, 440)
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) # Store a local handle to the scene's current image pixmap. self._pixmapHandle = None # Image aspect ratio mode. # !!! ONLY applies to full image. Aspect ratio is always ignored when zooming. # Qt.IgnoreAspectRatio: Scale image to fit viewport. # Qt.KeepAspectRatio: Scale image to fit inside viewport, preserving aspect ratio. # Qt.KeepAspectRatioByExpanding: Scale image to fill the viewport, preserving aspect ratio. self.aspectRatioMode = Qt.KeepAspectRatio # Scroll bar behaviour. # Qt.ScrollBarAlwaysOff: Never shows a scroll bar. # Qt.ScrollBarAlwaysOn: Always shows a scroll bar. # Qt.ScrollBarAsNeeded: Shows a scroll bar only when zoomed. self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) # Stack of QRectF zoom boxes in scene coordinates. self.zoomStack = [] # Flags for enabling/disabling mouse interaction. self.canZoom = True self.canPan = True
def wheelEvent(self, event): if event.modifiers() == Qt.CTRL and event.angleDelta().x() == 0: self.zoom(event.pos(), self.mapToScene(event.pos()), event.angleDelta().y()) event.accept() return True QGraphicsView.wheelEvent(self, event)
def main(argv): app = QApplication(argv) scene = QGraphicsScene(0, 0, 500, 500) scene.setItemIndexMethod(QGraphicsScene.NoIndex) brush = QBrush(Qt.red) brush_brics = QBrush(QPixmap('brick_texture.jpg')) brush_brics.setStyle(Qt.TexturePattern) pen = QPen() pen.setWidth(5) pen.setStyle(Qt.DashLine) rectItem = RectItem('r1', 20, 10, 200, 100) rectItem.setBrush(brush) rectItem2 = RectItem('r2', 20, 10, 150, 250) rectItem2.setPen(pen) rectItem2.setBrush(brush_brics) rectItem2.setOpacity(70) arrowItem = ArrowItem(QLine(50, 200, 300, 400)) scene.addItem(arrowItem) scene.addItem(rectItem) scene.addItem(rectItem2) view = QGraphicsView(scene) view.show() return app.exec_()
def __init__(self, parent): super().__init__(parent) self._scene = QGraphicsScene(self) self._graphics_view = QGraphicsView(self._scene, self) layout = QVBoxLayout(self) layout.addWidget(self._graphics_view) self._pixmap_item = SpriteGraphicsItem(self) self._scene.addItem(self._pixmap_item) self._image = QImage(SPRITE_SIZE, SPRITE_SIZE, QImage.Format_ARGB32) self.sprite = [[0] * SPRITE_SIZE] * SPRITE_SIZE button_layout = QHBoxLayout(self) layout.addLayout(button_layout) self._color_button_group = QButtonGroup(self) for color in COLORS: button = QPushButton(self) button.setCheckable(True) button.setText(f"{color}") self._color_button_group.addButton(button, color) button_layout.addWidget(button) self._selected_color = 0 self._color_button_group.button(self._selected_color).setChecked(True) QObject.connect(self._color_button_group, SIGNAL("buttonClicked(int)"), self._color_selected) self._update_scaling()
def build_core_ui(self): """Sets up the core elements of this window. Notes: Setting up QGraphicsScene: https://stackoverflow.com/questions/23174481/pyside-qt-layout-not-working """ self.base_widget = QWidget(self) self.layout_base = QHBoxLayout(self.base_widget) self.layout_canvas = QVBoxLayout() self.setContentsMargins(0, 0, 0, 0) # Setup the QGraphics items to display out zones as active elements. scene_zone = QRect(0, 0, self.canvas_width, self.canvas_height) self.scene = QGraphicsScene(scene_zone, self) self.canvas = QGraphicsView(self.scene, self) self.canvas.setFixedSize(self.canvas_width + 1, self.canvas_height + 1) # Draw faint bullseye for target. self.scene.addEllipse(self.get_center_rect(300), Qt.NoPen, self.brush_overlay) self.scene.addEllipse(self.get_center_rect(200), Qt.NoPen, self.brush_innerlay) self.scene.addEllipse(self.get_center_rect(100), Qt.NoPen, self.brush_overlay) self.layout_canvas.addWidget(self.canvas) self.lbl_island = QLabel("Island Areas:") self.layout_canvas.addWidget(self.lbl_island) self.layout_base.addLayout(self.layout_canvas) # Set the core widget to the window. self.setCentralWidget(self.base_widget)
def find_display_size(display: GameDisplay, view: QGraphicsView, target_size: QSize) -> QSize: max_width = None max_height = None min_width = min_height = 1 display_width = display.width() display_height = display.height() while True: scene_size = view.contentsRect().size() if scene_size.width() == target_size.width(): min_width = max_width = display_width elif scene_size.width() < target_size.width(): min_width = display_width + 1 else: max_width = display_width - 1 if scene_size.height() == target_size.height(): min_height = max_height = display_height elif scene_size.height() < target_size.height(): min_height = display_height + 1 else: max_height = display_height - 1 if max_width is None: display_width *= 2 else: display_width = (min_width + max_width) // 2 if max_height is None: display_height *= 2 else: display_height = (min_height + max_height) // 2 if min_width == max_width and min_height == max_height: return QSize(display_width, display_height) display.resize(display_width, display_height) view.grab() # Force layout recalculation.
def initUI(self): self.setWindowTitle(self.tr("Game of Life")) self.setLayout(QVBoxLayout()) self.layout().setSpacing(0) self.layout().setContentsMargins(0, 0, 0, 0) self.comboBox = QComboBox() self.comboBox.addItems([*QGameOfLife.Games.keys()]) self.comboBox.currentTextChanged.connect(self.select) self.layout().addWidget(self.comboBox) self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) self.view.setFrameShape(QFrame.NoFrame) self.layout().addWidget(self.view) self.item = None self.timer = QTimer() self.timer.setInterval(10) self.timer.timeout.connect(self.tick) initialGame = random.choice([*QGameOfLife.Games.keys()]) self.select(initialGame) self.view.fitInView(self.item, Qt.KeepAspectRatioByExpanding) self.comboBox.setCurrentText(initialGame)
def __init__(self, parent): QGraphicsView.__init__(self, parent) self.setMinimumSize(BoardScene.BOARD_WIDTH, BoardScene.BOARD_WIDTH) self.setMaximumSize(BoardScene.BOARD_WIDTH, BoardScene.BOARD_WIDTH) self.scene = BoardScene() self.setScene(self.scene) self.show()
def test_click_insn(self): main_window = self._open_a_project() func = main_window.workspace.instance.project.kb.functions['main'] self.assertIsNotNone(func) # display function main disasm_view = main_window.workspace._get_or_create_disassembly_view() disasm_view._t_flow_graph_visible = True disasm_view.display_function(func) # get and click the first bbl of function main block = disasm_view.current_graph._insaddr_to_block.get(func.addr) insn = block.addr_to_insns[func.addr] scene = QGraphicsScene() scene.addItem(insn) view = QGraphicsView(scene) QTest.mouseClick(view.viewport(), Qt.MouseButton.LeftButton) # assert that slacrs logged the information sleep(5) self.session = Slacrs(database=Conf.checrs_backend_str).session() result = self.session.query(HumanActivity).filter( HumanActivity.project_md5 == self.project_md5, HumanActivity.addr == insn.addr, ).one() self.session.close() self.assertIsNotNone(result)
def mouseDoubleClickEvent(self, event): if event.button() == Qt.LeftButton: if self.next_fit: self.zoom_fit() else: self.zoom_full() QGraphicsView.mouseDoubleClickEvent(self, event)
def __init__(self, parent=None): super().__init__(parent) self.show_buttons_layout = QHBoxLayout() self.show_buttons_layout.setAlignment(QtGui.Qt.AlignCenter) self.show_st_button = QPushButton(text="Show ST") self.show_bu_button = QPushButton(text="Show BU") self.show_buttons_layout.addWidget(self.show_st_button) self.show_buttons_layout.addWidget(self.show_bu_button) self.display = QGraphicsView() self.display.setMinimumSize(256, 256) self.portrait_name_label = QLabel(text="(None)") self.portrait_name_label.setAlignment(QtGui.Qt.AlignCenter) self.navigation_buttons_layout = QHBoxLayout() self.navigation_buttons_layout.setAlignment(QtGui.Qt.AlignCenter) self.back_button = QPushButton("<") self.current_image_label = QLabel(text="0 / 0") self.forward_button = QPushButton(">") self.navigation_buttons_layout.addWidget(self.back_button) self.navigation_buttons_layout.addWidget(self.current_image_label) self.navigation_buttons_layout.addWidget(self.forward_button) self.main_layout = QVBoxLayout() self.main_layout.setAlignment(QtGui.Qt.AlignCenter) self.main_layout.addLayout(self.show_buttons_layout) self.main_layout.addWidget(self.display) self.main_layout.addWidget(self.portrait_name_label) self.main_layout.addLayout(self.navigation_buttons_layout) self.setLayout(self.main_layout)
def pickColor(self): "pick a color on the screen, part 1" # screenshot desktop self._img = QApplication.primaryScreen().grabWindow(0) self._view = QGraphicsView(self) scene = QGraphicsScene(self) # display screenshot at full size self._view.setWindowFlags(Qt.FramelessWindowHint) self._view.setWindowFlags(Qt.WindowType_Mask) self._view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scene.addPixmap(self._img) #; self._view.setScene(scene) self._mag = magnifier() self._mag.setBackground(self._img) self._mag.setSize(11, 11) scene.addItem(self._mag) self._view.setScene(scene) self._appview = QApplication self._appview.setOverrideCursor(Qt.CrossCursor) self._view.showFullScreen() self._view.mousePressEvent = self._pickedColor
def resizeEvent(self, event): """ ResiczeEvent do nadpisania w qgraphicsView """ self.graphics_view.fitInView(self._camera_item.boundingRect(), Qt.KeepAspectRatio) QGraphicsView.resizeEvent(self.graphics_view, event)
class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Pyside2 QGraphic View") self.setGeometry(300, 200, 640, 520) self.create_ui() self.show() def create_ui(self): scene = QGraphicsScene(self) greenBrush = QBrush(Qt.red) blueBrush = QBrush(Qt.blue) blackPen = QPen(Qt.black) blackPen.setWidth(1) ellipse = scene.addEllipse(0, 0, 20, 20, blackPen, greenBrush) ellipse2 = scene.addEllipse(-30, -30, 20, 20, blackPen, blueBrush) ellipse.setFlag(QGraphicsItem.ItemIsMovable) ellipse2.setFlag(QGraphicsItem.ItemIsMovable) self.view = QGraphicsView(scene, self) self.view.setGeometry(0, 0, 640, 440)
def resizeEvent(self, event): # FIXME: Se la finestra viene massimizzata, il valore di fit_scale non si aggiorna if self.matrix().m11() <= self.fit_scale: self.zoom_fit() else: self.notify_change() QGraphicsView.resizeEvent(self, event)
def start(self): # Layout for single images self.single_image = QWidget() self.single_image_layout = QGridLayout() self.single_image_view = QGraphicsView() self.single_image_scene = QGraphicsScene() self.single_image_view.setScene(self.single_image_scene) self.single_image_layout.addWidget(self.single_image_view) self.single_image.setLayout(self.single_image_layout) # Layout for multiple images self.multiple_image = QWidget() self.multiple_image_view_layout = QVBoxLayout() self.multiple_image_layout = QGraphicsGridLayout() self.multiple_image_view = QGraphicsView() self.multiple_image_scene = QGraphicsScene() self.multiple_image_view.setScene(self.multiple_image_scene) self.panel = QGraphicsWidget() self.multiple_image_scene.addItem(self.panel) self.multiple_image_view_layout.addWidget(self.multiple_image_view) self.panel.setLayout(self.multiple_image_layout) self.multiple_image.setLayout(self.multiple_image_view_layout) self.addWidget(self.single_image) self.addWidget(self.multiple_image)
def _init_widgets(self): self.view = QTabWidget() # QGraphicsView() self.traceTab = QWidget() tracelayout = QVBoxLayout() self.traceView = QGraphicsView() self.traceScene = QGraphicsScene() self.traceView.setScene(self.traceScene) self.listView = QTableWidget(0, 2) # row, col self.listView.setHorizontalHeaderItem(0, QTableWidgetItem("Trace ID")) self.listView.setHorizontalHeaderItem(1, QTableWidgetItem("Input ID")) self.listView.setSelectionMode(QAbstractItemView.SingleSelection) self.listView.setSelectionBehavior(QAbstractItemView.SelectRows) # self.listView.horizontalHeader().setStretchLastSection(True) # self.listView.horizontalHeader().setSectionResizeModel(0, QHeaderView.Stretch) self.listView.cellClicked.connect(self._switch_current_trace) self.traceSeedButton = QPushButton("View Input Seed") self.traceSeedButton.clicked.connect(self._view_input_seed) tracelayout.addWidget(self.traceView) tracelayout.addWidget(self.listView) tracelayout.addWidget(self.traceSeedButton) self.traceTab.setLayout(tracelayout) self.multiView = QWidget() multiLayout = QVBoxLayout() self.multiTraceList = QTableWidget(0, 2) # row, col self.multiTraceList.setSelectionMode(QAbstractItemView.MultiSelection) self.multiTraceList.setSelectionBehavior(QAbstractItemView.SelectRows) self.multiTraceList.setHorizontalScrollMode( self.multiTraceList.ScrollPerPixel) self.multiTraceList.setHorizontalHeaderItem( 0, QTableWidgetItem("Trace ID")) self.multiTraceList.setHorizontalHeaderItem( 1, QTableWidgetItem("Input ID")) self.selectMultiTrace = QPushButton("Refresh Heatmap") self.selectMultiTrace.clicked.connect(self._refresh_heatmap) multiLayout.addWidget(self.multiTraceList) multiLayout.addWidget(self.selectMultiTrace) self.multiView.setLayout(multiLayout) self.view.addTab(self.traceTab, "SingleTrace") self.view.addTab(self.multiView, "MultiTrace HeatMap") self.SINGLE_TRACE = 0 self.MULTI_TRACE = 1 self.view.currentChanged.connect(self._on_tab_change) self._reset() layout = QVBoxLayout() layout.addWidget(self.view) layout.setContentsMargins(0, 0, 0, 0) layout.setAlignment(self.view, Qt.AlignLeft) self.setLayout(layout)
def __init__(self, parent): super(AbstractStateGraphScene, self).__init__(parent) self._stateIdToNodeDict = {} self.view = QGraphicsView() self.view.setScene(self) self.view.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) self.setSceneRect(0, 0, 800, 600)
def initializeGview(self): self.scene = GraphicsScene() self.scene.setSceneRect(0, 0, 480, 480) self.scene.click.connect(self.keepNode) self.addNode() self.view = QGraphicsView(self.scene) self.view.setGeometry(0, 0, 500, 500) self.view.scale(1, 1)
def mousePressEvent(self, evt): # do nothing if we don't click on an item if not self.itemAt(evt.pos()): return # only one item can be selected at a time, so deselect if any for item in self.scene().selectedItems(): item.setSelected(False) QGraphicsView.mousePressEvent(self, evt)
def mouseReleaseEvent(self, event): """ Stop mouse pan or zoom mode (apply zoom if valid). """ QGraphicsView.mouseReleaseEvent(self, event) scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: self.setDragMode(QGraphicsView.NoDrag) self.leftMouseButtonReleased.emit(scenePos.x(), scenePos.y())
def wheelEvent(self, e: QWheelEvent): if e.modifiers() & Qt.ControlModifier: if e.delta() > 0: self.view.zoomIn(6) else: self.view.zoomOut(6) else: QGraphicsView.wheelEvent(e)
def __init__(self, parent): QGraphicsView.__init__(self, parent) self.setMinimumWidth(180) self.setMaximumWidth(180) self.scene = QGraphicsScene() self.setScene(self.scene) self.text_item = QGraphicsSimpleTextItem() self.scene.addItem(self.text_item) self.show()
def mousePressEvent(self, event): """ Start mouse pan or zoom mode. """ scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: if self.canPan: self.setDragMode(QGraphicsView.ScrollHandDrag) self.leftMouseButtonPressed.emit(scenePos.x(), scenePos.y()) QGraphicsView.mousePressEvent(self, event)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Assignment") self.scene = QGraphicsScene() self.button = QPushButton("Draw Text Boxes") # self.image = QImage(self.size(), QImage.Format_RGB32) # self.image.fill(Qt.black) self.scene.addWidget(self.button) self.view = QGraphicsView(self.scene) # self.view.resize(800, 600) self.setCentralWidget(self.view) self.button.clicked.connect(self.buttonClicked) self.view.viewport().installEventFilter(self) self.drawing = False self.brushSize = 2 self.brushColor = Qt.black self.lastPoint = QPoint() def mousePressEvent(self, event): # super(MainWindow, self).mousePressEvent(event) if event.button() == Qt.LeftButton: self.drawing = True self.startPoint = event.pos() print(self.drawing) def mouseReleaseEvent(self, event): if (Qt.LeftButton & self.drawing): self.lastPoint = event.pos() print(self.startPoint) painter = QPainter() painter.setPen( QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawRect(QtCore.QRect(self.startPoint, self.lastPoint)) self.update() # def paintEvent(self, event): # canvasPainter = QPainter(self) # canvasPainter.drawImage(self.rect()) def buttonClicked(self): self.button.hide() def eventFilter(self, obj, event): if obj is self.view.viewport(): if event.type() == QEvent.MouseButtonPress: print('mouse press event = ', event.pos()) elif event.type() == QEvent.MouseButtonRelease: self.mouseReleaseEvent(event) print('mouse release event = ', event.pos()) return QWidget.eventFilter(self, obj, event)
def graphics_view_on_key_press(self, event): key = event.key() if key in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down, Qt.Key_PageUp, Qt.Key_PageDown): # This causes the graphics view to ignore these keys so they can be caught by the bag_widget keyPressEvent event.ignore() else: # Maintains functionality for all other keys QGraphicsView implements QGraphicsView.keyPressEvent(self.graphics_view, event)
def __init__(self): QMainWindow.__init__(self) self.game_scene = GameScene() self.mask_scene = MaskScene(self) self.start_scene = StartScene(self.mask_scene) self.main_widget = QWidget() self.graph_view = QGraphicsView(self.main_widget) self.mask_view = QGraphicsView(self.main_widget) self.init()
def __init__(self,pslScene): QGraphicsView.__init__(self) self.setScene(pslScene) self.scene=pslScene self.drawingPolygonEnabled = False self.polygonIndex = 0 self.polygon=[] self.polygonArray=[] self.polygonArray.append(self.polygon)
def __init__(self): QMainWindow.__init__(self) self.image = QPixmap("sec_shield.png") self.item = QGraphicsPixmapItem(self.image) self.scene = QGraphicsScene() self.scene.addItem(self.item) self.view = QGraphicsView() self.view.setScene(self.scene) self.view.show()
def test_setParentItem(self): global qgraphics_item_painted scene = QGraphicsScene() scene.addText("test") view = QGraphicsView(scene) rect = self.createRoundRect(scene) view.show() QTimer.singleShot(1000, self.quit_app) self.app.exec_() self.assert_(qgraphics_item_painted)
def resizeEvent(self, event): if self.scene(): self.scene().setSceneRect(QRectF(QPointF(0, 0), event.size())) self._chart.resize(event.size()) self._coordX.setPos( self._chart.size().width()/2 - 50, self._chart.size().height() - 20) self._coordY.setPos( self._chart.size().width()/2 + 50, self._chart.size().height() - 20) for callout in self._callouts: callout.updateGeometry() QGraphicsView.resizeEvent(self, event)
def testIt(self): scene = QGraphicsScene() minSize = QSizeF(30, 100) prefSize = QSizeF(210, 100) maxSize = QSizeF(300, 100) a = createItem(minSize, prefSize, maxSize, "A") b = createItem(minSize, prefSize, maxSize, "B") c = createItem(minSize, prefSize, maxSize, "C") d = createItem(minSize, prefSize, maxSize, "D") view = QGraphicsView(scene) view.show() self.app.exec_()
def initUI(self): self.setWindowTitle(self.tr("Game of Life")) self.setLayout(QVBoxLayout()) self.layout().setSpacing(0) self.layout().setContentsMargins(0, 0, 0, 0) self.comboBox = QComboBox() self.comboBox.addItems([*QGameOfLife.Games.keys()]) self.comboBox.currentTextChanged.connect(self.select) self.layout().addWidget(self.comboBox) self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) self.view.setFrameShape(QFrame.NoFrame) self.layout().addWidget(self.view) self.item = None self.timer = QTimer() self.timer.setInterval(10) self.timer.timeout.connect(self.tick) initialGame = random.choice([*QGameOfLife.Games.keys()]) self.select(initialGame) self.view.fitInView(self.item, Qt.KeepAspectRatioByExpanding) self.comboBox.setCurrentText(initialGame)
class QGameOfLife(QWidget): Games = { "Game of Life": (GameOfLife, {'fill_rate': 0.50}), "Bacteria": (GrayScottDiffusion, {'coeffs': (0.16, 0.08, 0.035, 0.065)}), "Coral": (GrayScottDiffusion, {'coeffs': (0.16, 0.08, 0.062, 0.062)}), "Fingerprint": (GrayScottDiffusion, {'coeffs': (0.19, 0.05, 0.060, 0.062)}), "Spirals": (GrayScottDiffusion, {'coeffs': (0.10, 0.10, 0.018, 0.050)}), "Unstable": (GrayScottDiffusion, {'coeffs': (0.16, 0.08, 0.020, 0.055)}), "Worms": (GrayScottDiffusion, {'coeffs': (0.16, 0.08, 0.050, 0.065)}), "Zebrafish": (GrayScottDiffusion, {'coeffs': (0.16, 0.08, 0.035, 0.060)}), } def __init__(self, size=(400, 400)): super(QGameOfLife, self).__init__() self.size = size self.game = None self.initUI() self.show() def initUI(self): self.setWindowTitle(self.tr("Game of Life")) self.setLayout(QVBoxLayout()) self.layout().setSpacing(0) self.layout().setContentsMargins(0, 0, 0, 0) self.comboBox = QComboBox() self.comboBox.addItems([*QGameOfLife.Games.keys()]) self.comboBox.currentTextChanged.connect(self.select) self.layout().addWidget(self.comboBox) self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) self.view.setFrameShape(QFrame.NoFrame) self.layout().addWidget(self.view) self.item = None self.timer = QTimer() self.timer.setInterval(10) self.timer.timeout.connect(self.tick) initialGame = random.choice([*QGameOfLife.Games.keys()]) self.select(initialGame) self.view.fitInView(self.item, Qt.KeepAspectRatioByExpanding) self.comboBox.setCurrentText(initialGame) def select(self, name: str): self.timer.stop() Game, args = QGameOfLife.Games[name] self.game = Game(self.size, **args) self.tick() self.timer.start() def tick(self): self.game.tick() bitmap = self.game.visualize() image = QImage(bitmap.data, bitmap.shape[1], bitmap.shape[0], QImage.Format_Grayscale8) self.scene.removeItem(self.item) pixmap = QPixmap.fromImage(image) self.item = self.scene.addPixmap(pixmap) def resizeEvent(self, event: QResizeEvent): self.view.fitInView(self.item, Qt.KeepAspectRatioByExpanding) def sizeHint(self) -> QSize: return QSize(self.size[0], self.size[1])
def mouseMoveEvent(self, event): self._coordX.setText("X: {0:.2f}" .format(self._chart.mapToValue(event.pos()).x())) self._coordY.setText("Y: {0:.2f}" .format(self._chart.mapToValue(event.pos()).y())) QGraphicsView.mouseMoveEvent(self, event)