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 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)
class CaptchaDialogue(QDialog): def __init__(self, *args, **kwargs): super(CaptchaDialogue, self).__init__(*args, **kwargs) self.ui = ui.CaptchaDialogue() self.ui.setupUi(self) self.captcha_generator = ImageCaptcha() self.scene = QGraphicsScene() self.ui.captcha_view.setScene(self.scene) self.text = None self.ui.buttons.accepted.connect(self.accept) self.ui.buttons.rejected.connect(self.reject) def open(self): self.generate_captcha() super().open() def done(self, result: QDialog.DialogCode): if result == QDialog.Accepted and self.ui.captcha_input.text( ) != self.text: self.ui.input_label.setText("Incorrect CAPTCHA given. Try again:") self.ui.input_label.setStyleSheet("color: red") self.generate_captcha() else: self.ui.input_label.setText( "Enter the characters displayed above:") self.ui.input_label.setStyleSheet("") self.ui.captcha_input.clear() super().done(result) def generate_captcha(self): self.text = self._generate_text() image_bytes = self.captcha_generator.generate(self.text).getvalue() image = QByteArray(image_bytes) pixmap = QPixmap() pixmap.loadFromData(image, "png") self.scene.clear() self.scene.addPixmap(pixmap) @staticmethod def _generate_text() -> str: """Return a string of random characters to be used for CAPTCHA generation.""" sample = random.sample(CHARACTERS, 6) return "".join(sample)
def __init__(self, params): MWB.__init__(self, params) QGraphicsView.__init__(self) self.setFixedWidth(300); self.setFixedHeight(300); scene = QGraphicsScene(self) scene.setSceneRect(0,0, self.width()-5, self.height()-5) self.setScene(scene) self.setCacheMode(QGraphicsView.CacheBackground) self.setRenderHint(QPainter.Antialiasing) self.setStyleSheet(''' border: none; ''')
def __init__(self): super(MyView, self).__init__() self.setScene(QGraphicsScene()) self.scene().setSceneRect(300, 300) self.scene().addItem(Test())
def __init__(self, width, height, pixel_ratio, path): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # overwrite dimesions specified in slideShow3.py, as they are specific to MacBookPro display, and QTDesigner # has its own idea on what they should be. This code should work on any size display self.resize(width, height) self.ui.graphicsView.setGeometry(QtCore.QRect(0, 0, width, height)) self.ui.menubar.setGeometry(QtCore.QRect(0, 0, width, 0)) self.width = width self.height = height self.pixel_ratio = pixel_ratio self.path = path self.imageFiles = [] self.slideIndex = -1 self.random_index_number = 0 self.random = "" self.imageFiles, self.random_index, self.path, self.max_index = self.getImageNames2() self.helpFile = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "instructions.png") #print(self.helpFile) self.scene = QGraphicsScene(self) #self.scene.setAlignment(QtCore.Qt.AlignCenter) self.ui.actionDir.triggered.connect(self.openFileNameDialog) self.ui.actionStart_Slide_Show.triggered.connect(self.slide_show) self.ui.actionRandom_Slide_Show.triggered.connect(self.random_slide_show) eventFilter = MouseEventFilter(self.scene) self.scene.installEventFilter(eventFilter) self.ui.actionHelp.triggered.connect(self.helpWindow) #self.show() self.showFullScreen()
def __init__(self, parent=None): super(GameWidget, self).__init__(parent) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.m = 150 self.n = 150 self.scene = QGraphicsScene(self) self.setScene(self.scene) self.scene.setSceneRect(0, 0, self.width(), self.height()) self.setAlignment(Qt.AlignLeft | Qt.AlignTop) self.universe = engine.Universe(self.n, self.m) print(Qt.red) self.timer = QTimer(self) self.timer.timeout.connect(self.step)
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 draw_waypoint_info(self, scene: QGraphicsScene, number: int, waypoint: FlightWaypoint, position: Tuple[int, int], flight_plan: FlightPlan) -> None: altitude = int(waypoint.alt.feet) altitude_type = "AGL" if waypoint.alt_type == "RADIO" else "MSL" prefix = "TOT" time = flight_plan.tot_for_waypoint(waypoint) if time is None: prefix = "Depart" time = flight_plan.depart_time_for_waypoint(waypoint) if time is None: tot = "" else: time = datetime.timedelta(seconds=int(time.total_seconds())) tot = f"{prefix} T+{time}" pen = QPen(QColor("black"), 0.3) brush = QColor("white") text = "\n".join([ f"{number} {waypoint.name}", f"{altitude} ft {altitude_type}", tot, ]) item = scene.addSimpleText(text, self.waypoint_info_font) item.setFlag(QGraphicsItem.ItemIgnoresTransformations) item.setBrush(brush) item.setPen(pen) item.moveBy(position[0] + 8, position[1]) item.setZValue(2) self.flight_path_items.append(item)
def setUp(self): #Acquire resources super(ItemRetrieve, self).setUp() self.scene = QGraphicsScene() self.topleft = QGraphicsRectItem(0, 0, 100, 100) self.topright = QGraphicsRectItem(100, 0, 100, 100) self.bottomleft = QGraphicsRectItem(0, 100, 100, 100) self.bottomright = QGraphicsRectItem(100, 100, 100, 100) self.items = [ self.topleft, self.topright, self.bottomleft, self.bottomright ] for item in self.items: self.scene.addItem(item)
def ordenar_distancia(self): self.scene.clear() self.scene = QGraphicsScene() #self.scene.setSceneRect(0,500) self.ui.graphicsView.setScene(self.scene) self.pen = QPen() self.pen.setColor(QColor(0, 0, 0)) self.pen.setWidth(1) self.capturador.ordenar_distancia() y=0 for particula in self.capturador.lista: self.ui.plainTextEdit.insertPlainText(str(particula)) self.pen.setColor(QColor(particula.red, particula.green, particula.blue)) self.scene.addLine(0, y, particula.distancia, y, self.pen) y=y+2
def draw_waypoint(self, scene: QGraphicsScene, position: Tuple[int, int], player: bool, selected: bool) -> None: waypoint_pen = self.waypoint_pen(player, selected) waypoint_brush = self.waypoint_brush(player, selected) self.flight_path_items.append( scene.addEllipse(position[0], position[1], self.WAYPOINT_SIZE, self.WAYPOINT_SIZE, waypoint_pen, waypoint_brush))
def __init__(self, targetGUIModel: 'TargetGuiModel'): """ Construct the TGUIMScene class :param targetGUIModel: get the TargetGuiModel of the project :type targetGUIModel: TargetGuiModel """ QGraphicsScene.__init__(self) self._targetGuiModel = targetGUIModel self._dataToGraphicsMapping = {} # Create all component graphics # WARNING: We create an invisible graphics item for the root, which is a bit weird. If there's a # graphics-related bug, look into this. root = self._targetGuiModel.getRoot() rootGraphics = ComponentGraphics(root, (0, 0, 0, 0), None) self._dataToGraphicsMapping[root] = rootGraphics work = [(root, rootGraphics)] while len(work) > 0: data, parentGraphics = work.pop() # add the root's component to the scene. if data is self._targetGuiModel.getRoot(): self.addItem(parentGraphics) for child in data.getChildren(): graphics = self.createComponentGraphics(child, parentGraphics) work.append((child, graphics)) # Create all visibility behavior graphics for vb in targetGUIModel.getVisibilityBehaviors(): graphics = self.createVisibilityBehaviorGraphics(vb) self.addItem(graphics) def onNewComponent(newComponent): parentGraphics = self.getGraphics(newComponent.getParent()) graphics = self.createComponentGraphics(newComponent, parentGraphics) if parentGraphics is None: print("IS TOP LEVEL") self.addItem(graphics) def onNewBehavior(newBehavior): self.createVisibilityBehaviorGraphics(newBehavior) self._targetGuiModel.newComponent.connect(onNewComponent) self._targetGuiModel.newBehavior.connect(onNewBehavior)
class NetworkView(QGraphicsView): def __init__(self, parent=None): super(NetworkView, self).__init__(parent) self.index = 0 # self.setScene(scene) def random_pos(self): x = random.randint(0, 1920) y = random.randint(0, 1080) return QPointF(x, y) def circle_pos(self): x = R * math.cos(self.index * math.pi * 2 / size) y = R * math.sin(self.index * math.pi * 2 / size) self.index += 1 return QPointF(x, y) def hide_items(self): nodes = self.graph.nodes(data=True) for node in nodes: if node[1]['first'] == 0 and node[1]['co'] == 1: node = self.nodes[node[0]] node.hide_self() def draw_network(self, graph): self.graph = graph self._scene = QGraphicsScene(self) self.nodes = {} self.edges = [] nodes = self.graph.nodes(data=True) print('节点总数:') print(len(nodes)) # degrees = sorted(degrees, key=lambda x: (x[1]), reverse=True) for node in nodes: count = node[1]['first'] + node[1]['co'] #100*count*10/100 new_display_node = Node() self.nodes[node[0]] = new_display_node self._scene.addItem(new_display_node) new_display_node.setPos(self.circle_pos()) edges = self.graph.edges(data='weight') for edge in edges: node_start = self.nodes[edge[0]] node_end = self.nodes[edge[1]] new_display_edge = Edge(node_start, node_end) self._scene.addItem(new_display_edge) self.setScene(self._scene)
def testIt(self): scene = QGraphicsScene() i1 = QGraphicsRectItem() scene.addItem(i1) i2 = QGraphicsRectItem(i1) i3 = QGraphicsRectItem() i4 = QGraphicsRectItem() group = scene.createItemGroup((i2, i3, i4)) scene.removeItem(i1) del i1 # this shouldn't delete i2 self.assertEqual(i2.scene(), scene) scene.destroyItemGroup(group) self.assertRaises(RuntimeError, group.type)
def fill_ui(self): """Configure UI out of our screen data.""" self.scene = QGraphicsScene(self) self.ui.sceneView.setScene(self.scene) self.ui.screenCombo.clear() for name, monitor in self.screen.monitors.items(): self.ui.screenCombo.addItem(name) mon_item = MonitorItem( data=monitor, window=self, name=name, ) self.scene.addItem(mon_item) monitor.item = mon_item self.ui.screenCombo.setCurrentText(self.screen.choose_a_monitor()) self.adjust_view()
class ImageViewer(QWidget): def __init__(self, image_path): super().__init__() self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) layout = QVBoxLayout() layout.addWidget(self.view) self.setLayout(layout) self.load_image(image_path) def load_image(self, image_path): pixmap = QPixmap(image_path) self.scene.addPixmap(pixmap) self.view.fitInView(QRectF(0, 0, pixmap.width(), pixmap.height()), Qt.KeepAspectRatio) self.scene.update()
def draw_shortest_path( self, scene: QGraphicsScene, navmesh: NavMesh, destination: Point, player: bool ) -> None: for line in self.shortest_path_segments: try: scene.removeItem(line) except RuntimeError: pass if player: origin = self.game.theater.player_points()[0] else: origin = self.game.theater.enemy_points()[0] prev_pos = self._transform_point(origin.position) try: path = navmesh.shortest_path(origin.position, destination) except ValueError: return for waypoint in path[1:]: new_pos = self._transform_point(waypoint) flight_path_pen = self.flight_path_pen(player, selected=True) # Draw the line to the *middle* of the waypoint. offset = self.WAYPOINT_SIZE // 2 self.shortest_path_segments.append( scene.addLine( prev_pos[0] + offset, prev_pos[1] + offset, new_pos[0] + offset, new_pos[1] + offset, flight_path_pen, ) ) self.shortest_path_segments.append( scene.addEllipse( new_pos[0], new_pos[1], self.WAYPOINT_SIZE, self.WAYPOINT_SIZE, flight_path_pen, flight_path_pen, ) ) prev_pos = new_pos
def draw_navmesh_neighbor_line( self, scene: QGraphicsScene, poly: Polygon, begin: ShapelyPoint ) -> None: vertex = Point(begin.x, begin.y) centroid = poly.centroid direction = Point(centroid.x, centroid.y) end = vertex.point_from_heading( vertex.heading_between_point(direction), nautical_miles(2).meters ) scene.addLine( QLineF( QPointF(*self._transform_point(vertex)), QPointF(*self._transform_point(end)), ), CONST.COLORS["yellow"], )
def highlight_mouse_navmesh( self, scene: QGraphicsScene, navmesh: NavMesh, mouse_position: Point ) -> None: if self.navmesh_highlight is not None: try: scene.removeItem(self.navmesh_highlight) except RuntimeError: pass navpoly = navmesh.localize(mouse_position) if navpoly is None: return self.navmesh_highlight = self.draw_shapely_poly( scene, navpoly.poly, CONST.COLORS["transparent"], CONST.COLORS["light_green_transparent"], )
def ordenar_velocidad(self): print('click') self.listaparticulas.ordenar_velocidad() self.scene = QGraphicsScene() self.scene.setSceneRect(0, 0, 400, 1000) self.ui.graphicsView.setScene(self.scene) self.pen = QPen() self.pen.setColor(QColor(0,0,0)) self.pen.setWidth(3) i = 1 for particula in self.listaparticulas.lista: self.pen.setColor(QColor(particula.colorR, particula.colorG, particula.colorB)) self.scene.addLine(0, i, particula.velocidad, i, self.pen) i = i+1
def setUp(self): #Acquire resources super(QColorOnSetBrush, self).setUp() self.scene = QGraphicsScene() poly = QPolygonF() self.item = self.scene.addPolygon(poly) self.color = QColor('black')
def uniqueItems(self): items = QGraphicsScene.items(self, order=Qt.SortOrder.DescendingOrder) itemList = [] for item in items: className = str(type(item)) if not className.find("PointItem") >= 0: itemList.append(item) return itemList
def mostarParticulasPuntos(self): self.scene.clear() self.scene = QGraphicsScene() # self.scene.setSceneRect(0,500) self.ui.graphicsView.setScene(self.scene) self.pen = QPen() self.pen.setWidth(1) for particula in self.capturador.lista: print(particula.origenX, particula.origenY) ## Problema ## Si hay un nodo que no tenga origen solo nodos que van hacia el no se dibuja ## Soluccion ## comparar en un nueva lista si el destino se encuentra en la lista de origenes ## si no se encuentra dibujar ##posible solucion self.scene.addEllipse( particula.destinoX, particula.destinoY, 5, 5, self.pen, QBrush(QColor(particula.red, particula.green, particula.blue))) self.scene.addEllipse( particula.origenX, particula.origenY, 5, 5, self.pen, QBrush(QColor(particula.red, particula.green, particula.blue))) self.ui.plainTextEdit.insertPlainText(str(particula)) self.lista.append({ 'x': particula.origenX, 'y': particula.origenY, 'color': { 'red': particula.red, 'green': particula.green, 'blue': particula.blue } }) self.lista.append({ 'x': particula.destinoX, 'y': particula.destinoY, 'color': { 'red': particula.red, 'green': particula.green, 'blue': particula.blue } })
def __init__(self): QWidget.__init__(self) #Paths self.folderPath = "../Crop_Reports/Bengal Crop Reports PNG/" self.index = 0 self.page_index = 0 self.crop_report = "" self.pixmap = QPixmap() self.data = pd.read_csv("../Crop_Reports/Manual Check Crop Reports/crop_reports_verified.csv") #choices self.choices = listdir(self.folderPath) self.scene = QGraphicsScene() self.image = QGraphicsView(self.scene) self.image.show() self.submitButton = QPushButton("Submit") self.dateText = QLineEdit("") self.middle = QVBoxLayout() self.middle.setMargin(10) self.middle.addWidget(self.image) self.middle.addWidget(self.dateText) self.middle.addWidget(self.submitButton) # QWidget Layout self.layout = QHBoxLayout() self.layout.addLayout(self.middle) # Set the layout to the QWidget self.setLayout(self.layout) # Here we connect widgets to functions self.submitButton.clicked.connect(self.submit)
def draw_bezier_frontline( self, scene: QGraphicsScene, pen: QPen, frontline: FrontLine ) -> None: """ Thanks to Alquimista for sharing a python implementation of the bezier algorithm this is adapted from. https://gist.github.com/Alquimista/1274149#file-bezdraw-py """ bezier_fixed_points = [] for segment in frontline.segments: bezier_fixed_points.append(self._transform_point(segment.point_a)) bezier_fixed_points.append(self._transform_point(segment.point_b)) old_point = bezier_fixed_points[0] for point in bezier_curve_range( int(len(bezier_fixed_points) * 2), bezier_fixed_points ): scene.addLine(old_point[0], old_point[1], point[0], point[1], pen=pen) old_point = point
def grafo(self): grafoG = dict() # {} self.scene.clear() self.scene = QGraphicsScene() self.ui.graphicsView.setScene(self.scene) for particula in self.capturador.lista: origen=(particula.origenX,particula.origenY) destino=(particula.destinoX,particula.destinoY) if origen in grafoG: grafoG[origen].append((destino, particula.distancia)) else: grafoG[origen] = [(destino, particula.distancia)] if destino in grafoG: grafoG[destino].append((origen, particula.distancia)) else: grafoG[destino] = [(origen, particula.distancia)] str = pprint.pformat(grafoG, width=40) self.ui.plainTextEdit.insertPlainText(str)
def __init__(self, parent=None, window=None, mode='cursor'): QGraphicsScene.__init__(self, parent) # Set parent view area self.parent = parent # Set grand parent window self.window = window # Set action mode self.mode = mode # mouse move pixels self.points = [] # added line items self.line_items = [] self.lines = [] # added line's pen attribute self.pens = []
def draw_flight_path(self, scene: QGraphicsScene, pos0: Tuple[float, float], pos1: Tuple[float, float], player: bool, selected: bool) -> None: flight_path_pen = self.flight_path_pen(player, selected) # Draw the line to the *middle* of the waypoint. offset = self.WAYPOINT_SIZE // 2 self.flight_path_items.append( scene.addLine(pos0[0] + offset, pos0[1] + offset, pos1[0] + offset, pos1[1] + offset, flight_path_pen))
def __init__(self): super(MainWindow, self).__init__() self.particula = Particula() self.organizador = Organizador() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.abInicio.clicked.connect(self.click_agregar_inicio) self.ui.abFinal.clicked.connect(self.click_agregar_final) self.ui.abMostrar.clicked.connect(self.click_mostrar) self.ui.actionGuardar_.triggered.connect(self.guardar) self.ui.actionAbrir_.triggered.connect(self.abrir) self.ui.abMostrarParticulas.clicked.connect( self.mostrarParticulasTodas) self.ui.abBuscar.clicked.connect(self.buscarParticulaId) self.ui.abLimpiar.clicked.connect(self.limpiar) self.scene = QGraphicsScene() self.ui.graphicsView.setScene(self.scene)
def fill_ui(self): """Load data from xrandr and setup the whole thing.""" self.scene = QGraphicsScene(self) self.ui.sceneView.setScene(self.scene) self.ui.screenCombo.clear() for name, monitor in self.xrandr_info.items(): self.ui.screenCombo.addItem(name) mon_item = MonitorItem( data=monitor, window=self, name=name, ) self.scene.addItem(mon_item) monitor["item"] = mon_item self.ui.screenCombo.setCurrentText(self.choose_a_monitor()) self.adjust_view() self.scale_changed() # Trigger scale labels update
def draw_shapely_poly(self, scene: QGraphicsScene, poly: Polygon, pen: QPen, brush: QBrush) -> Optional[QPolygonF]: if poly.is_empty: return None points = [] for x, y in poly.exterior.coords: x, y = self._transform_point(Point(x, y)) points.append(QPointF(x, y)) return scene.addPolygon(QPolygonF(points), pen, brush)
class ConstructorWithRect(unittest.TestCase): '''QGraphicsScene qrect constructor and related sizes''' def setUp(self): #Acquire resources # PyQt4 doesn't accept a QRect as argument to constructor self.scene = QGraphicsScene(0, 200, 150, 175) def tearDown(self): #Release resources del self.scene def testHeight(self): #QGraphicsScene.height() self.assertEqual(self.scene.height(), 175) def testWidth(self): #QGraphicsScene.width() self.assertEqual(self.scene.width(), 150)
def __init__(self): super().__init__() self.setWindowTitle("Assignment") self.scene = QGraphicsScene() self.resize(800, 600) self.button = QPushButton("Draw Text Boxes") self.scene.addWidget(self.button) self.view = QGraphicsView() self.view.setScene(self.scene) self.setCentralWidget(self.view) self.button.clicked.connect(self.buttonClicked) self.view.viewport().installEventFilter(self) self.drawing = False self.lastPoint = QPoint() self.startPoint = QPoint()
def __init__(self): # main window settings super().__init__() self.setWindowTitle("Snake") self.setGeometry(150, 50, 820, 320) self.setFixedSize(820, 320) self.scene = QGraphicsScene() self.game_loop = False self.scoreboard = None self.hot_seat = 0 self.config = 0 self.against_ai = 0 self.game = snake_map(width, height) self.multi_info = [] self.hex = [] self.grahpicsitem = [] self.end_connection = False self.guicomponents()
class ReferenceCount(UsesQApplication): def setUp(self): super(ReferenceCount, self).setUp() self.scene = QGraphicsScene() def tearDown(self): super(ReferenceCount, self).tearDown() def beforeTest(self): points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)] pol = self.scene.addPolygon(QPolygonF(points)) self.assert_(isinstance(pol, QGraphicsPolygonItem)) self.wrp = weakref.ref(pol, pol_del) #refcount need be 3 because one ref for QGraphicsScene, and one to rect obj self.assertEqual(sys.getrefcount(pol), 3) def testReferenceCount(self): global destroyedRect global destroyedPol self.beforeTest() rect = self.scene.addRect(10.0, 10.0, 10.0, 10.0) self.assert_(isinstance(rect, QGraphicsRectItem)) self.wrr = weakref.ref(rect, rect_del) #refcount need be 3 because one ref for QGraphicsScene, and one to rect obj self.assertEqual(sys.getrefcount(rect), 3) del rect #not destroyed because one ref continue in QGraphicsScene self.assertEqual(destroyedRect, False) self.assertEqual(destroyedPol, False) del self.scene #QGraphicsScene was destroyed and this destroy internal ref to rect self.assertEqual(destroyedRect, True) self.assertEqual(destroyedPol, True)
def setUp(self): #Acquire resources super(ItemRetrieve, self).setUp() self.scene = QGraphicsScene() self.topleft = QGraphicsRectItem(0, 0, 100, 100) self.topright = QGraphicsRectItem(100, 0, 100, 100) self.bottomleft = QGraphicsRectItem(0, 100, 100, 100) self.bottomright = QGraphicsRectItem(100, 100, 100, 100) self.items = [self.topleft, self.topright, self.bottomleft, self.bottomright] for item in self.items: self.scene.addItem(item)
class QColorOnSetBrush(UsesQApplication): '''Test case for passing a QColor directly to setBrush''' def setUp(self): #Acquire resources super(QColorOnSetBrush, self).setUp() self.scene = QGraphicsScene() poly = QPolygonF() self.item = self.scene.addPolygon(poly) self.color = QColor('black') def tearDown(self): #Release resources del self.color del self.item del self.scene super(QColorOnSetBrush, self).tearDown() def testQColor(self): #QGraphicsAbstractShapeItem.setBrush(QColor) self.item.setBrush(self.color) self.assertEqual(QBrush(self.color), self.item.brush())
class ItemRetrieve(UsesQApplication): '''Tests for QGraphicsScene item retrieval methods''' qapplication = True def setUp(self): #Acquire resources super(ItemRetrieve, self).setUp() self.scene = QGraphicsScene() self.topleft = QGraphicsRectItem(0, 0, 100, 100) self.topright = QGraphicsRectItem(100, 0, 100, 100) self.bottomleft = QGraphicsRectItem(0, 100, 100, 100) self.bottomright = QGraphicsRectItem(100, 100, 100, 100) self.items = [self.topleft, self.topright, self.bottomleft, self.bottomright] for item in self.items: self.scene.addItem(item) def tearDown(self): #Release resources del self.scene super(ItemRetrieve, self).tearDown() def testItems(self): #QGraphicsScene.items() items = self.scene.items() for i in items: self.assertTrue(i in self.items) def testItemAt(self): #QGraphicsScene.itemAt() self.assertEqual(self.scene.itemAt(50, 50), self.topleft) self.assertEqual(self.scene.itemAt(150, 50), self.topright) self.assertEqual(self.scene.itemAt(50, 150), self.bottomleft) self.assertEqual(self.scene.itemAt(150, 150), self.bottomright)
class AddItem(UsesQApplication): '''Tests for QGraphicsScene.add*''' qapplication = True def setUp(self): #Acquire resources super(AddItem, self).setUp() self.scene = QGraphicsScene() # While the scene does not inherits from QWidget, requires # an application to make the internals work. def tearDown(self): #Release resources del self.scene super(AddItem, self).tearDown() def testEllipse(self): #QGraphicsScene.addEllipse item = self.scene.addEllipse(100, 100, 100, 100) self.assertTrue(isinstance(item, QGraphicsEllipseItem)) def testLine(self): #QGraphicsScene.addLine item = self.scene.addLine(100, 100, 200, 200) self.assertTrue(isinstance(item, QGraphicsLineItem)) def testPath(self): #QGraphicsScene.addPath item = self.scene.addPath(QPainterPath()) self.assertTrue(isinstance(item, QGraphicsPathItem)) def testPixmap(self): #QGraphicsScene.addPixmap item = self.scene.addPixmap(QPixmap()) self.assertTrue(isinstance(item, QGraphicsPixmapItem)) def testPolygon(self): #QGraphicsScene.addPolygon points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)] item = self.scene.addPolygon(QPolygonF(points)) self.assertTrue(isinstance(item, QGraphicsPolygonItem)) def testRect(self): #QGraphicsScene.addRect item = self.scene.addRect(100, 100, 100, 100) self.assertTrue(isinstance(item, QGraphicsRectItem)) def testSimpleText(self): #QGraphicsScene.addSimpleText item = self.scene.addSimpleText('Monty Python 42') self.assertTrue(isinstance(item, QGraphicsSimpleTextItem)) def testText(self): #QGraphicsScene.addText item = self.scene.addText('Monty Python 42') self.assertTrue(isinstance(item, QGraphicsTextItem)) def testWidget(self): #QGraphicsScene.addWidget # XXX: printing some X11 error when using under PyQt4 item = self.scene.addWidget(QPushButton()) self.assertTrue(isinstance(item, QGraphicsProxyWidget))
def setUp(self): #Acquire resources # PyQt4 doesn't accept a QRect as argument to constructor self.scene = QGraphicsScene(0, 200, 150, 175)
def setUp(self): #Acquire resources super(AddItem, self).setUp() self.scene = QGraphicsScene()
class MyForm(QMainWindow): def __init__(self, width, height, pixel_ratio, path): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # overwrite dimesions specified in slideShow3.py, as they are specific to MacBookPro display, and QTDesigner # has its own idea on what they should be. This code should work on any size display self.resize(width, height) self.ui.graphicsView.setGeometry(QtCore.QRect(0, 0, width, height)) self.ui.menubar.setGeometry(QtCore.QRect(0, 0, width, 0)) self.width = width self.height = height self.pixel_ratio = pixel_ratio self.path = path self.imageFiles = [] self.slideIndex = -1 self.random_index_number = 0 self.random = "" self.imageFiles, self.random_index, self.path, self.max_index = self.getImageNames2() self.helpFile = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "instructions.png") #print(self.helpFile) self.scene = QGraphicsScene(self) #self.scene.setAlignment(QtCore.Qt.AlignCenter) self.ui.actionDir.triggered.connect(self.openFileNameDialog) self.ui.actionStart_Slide_Show.triggered.connect(self.slide_show) self.ui.actionRandom_Slide_Show.triggered.connect(self.random_slide_show) eventFilter = MouseEventFilter(self.scene) self.scene.installEventFilter(eventFilter) self.ui.actionHelp.triggered.connect(self.helpWindow) #self.show() self.showFullScreen() extension = staticmethod(lambda f: f.split('.').pop().lower()) filename = staticmethod(lambda f: f.split('/').pop()) def openFileNameDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog self.fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options) if self.fileName: self.path = os.path.dirname(self.fileName) self.imageFiles = [] self.random_index = [] self.max_index = [] self.imageFiles, self.random_index, self.path, self.max_index = self.getImageNames2() self.slideIndex = self.imageFiles.index(self.fileName) -1 def getImageNames2(self): "get the names of all images on disc or from the web (which are cached locally)" if not self.path: self.path = os.getcwd() if self.path[-1] != '/': self.path += '/' try: os.listdir(self.path) except: error_dialog = QtWidgets.QErrorMessage() error_dialog.showMessage('Error in path' +self.path) # https://stackoverflow.com/questions/40227047/python-pyqt5-how-to-show-an-error-message-with-pyqt5 return [], self.path for i in GlobDirectoryWalker(self.path, "*.*"): if os.path.isfile(i): if self.checkImageType(i): self.imageFiles.append(i) max_index = len(self.imageFiles) - 1 self.imageFiles.sort() random_index = list(range(max_index + 1)) random.shuffle(random_index) return self.imageFiles, random_index, self.path, max_index def slide(self, i): self.pixmap = QtGui.QPixmap() #self.pixmap.setAlignment(QtCore.Qt.AlignCenter) self.pixmap.load(self.imageFiles[i]) self.pixmap.setDevicePixelRatio(self.pixel_ratio) # https://stackoverflow.com/questions/50127246/pyqt-5-10-enabling-high-dpi-support-for-macos-poor-pixmap-quality #self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio, (self.height * self.pixel_ratio)-45, Qt.KeepAspectRatio) self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio, (self.height * self.pixel_ratio), Qt.KeepAspectRatio) try: self.scene.removeItem(self.item) except: print("failed to remove item") self.item = QGraphicsPixmapItem(self.pixmap4) self.scene.addItem(self.item) #myapp.setWindowTitle(os.path.basename(self.imageFiles[i])) self.setWindowTitle(os.path.basename(self.imageFiles[i])) self.ui.graphicsView.setScene(self.scene) def slide_show(self): self.random = 0 self.next_slide() def random_slide_show(self): self.random = 1 self.next_slide() def next_slide(self): if self.random == 0: self.increment_slide() else: self.random_next() def prev_slide(self): if self.random == 0: self.decrement_slide() else: self.random_prev() def random_next(self): "display the next random slide" self.random_index_number += 1 try: self.slideIndex = self.random_index[self.random_index_number] self.slide(self.slideIndex) except IndexError: self.random_index_number = 0 self.slideIndex = self.random_index[self.random_index_number] self.slide(self.slideIndex) return False def random_prev(self): "display the previous random slide" self.random_index_number -= 1 #self.ImageWindow.clear() try: self.slideIndex = self.random_index[self.random_index_number] self.slide(self.slideIndex) except IndexError: self.random_index_number = self.max_index self.slideIndex = self.random_index[self.random_index_number] self.slide(self.slideIndex) return False def increment_slide(self): "display a higher slide" print("in increment_slide") self.slideIndex += 1 if self.slideIndex > self.max_index: self.slideIndex = 0 print('Max index hit') self.slide(self.slideIndex) return False def decrement_slide(self): "display a lower slide" self.slideIndex -= 1 if self.slideIndex < 0: self.slideIndex = self.max_index self.slide(self.slideIndex) return False def checkImageType(self, f): "check to see if we have an file with an image extension" ext = self.extension(f) chk = [i for i in ['jpg','gif','ppm', 'tif', 'png', 'jpeg'] if i==ext] if chk == []: return False return True def helpWindow(self): self.pixmap = QtGui.QPixmap() #self.pixmap.setAlignment(QtCore.Qt.AlignCenter) self.pixmap.load(self.helpFile) self.pixmap.setDevicePixelRatio(self.pixel_ratio) # https://stackoverflow.com/questions/50127246/pyqt-5-10-enabling-high-dpi-support-for-macos-poor-pixmap-quality #self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio, (self.height * self.pixel_ratio)-45, Qt.KeepAspectRatio) self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio, (self.height * self.pixel_ratio), Qt.KeepAspectRatio) try: self.scene.removeItem(self.item) except: print("failed to remove item") self.item = QGraphicsPixmapItem(self.pixmap4) self.scene.addItem(self.item) #myapp.setWindowTitle(os.path.basename("Instructions")) self.setWindowTitle(os.path.basename("Instructions")) self.ui.graphicsView.setScene(self.scene) def keyPressEvent(self, e): if e.key() == Qt.Key_Escape: self.Quit() if e.key() == Qt.Key_Q: self.Quit() if e.key() == Qt.Key_Space: self.next_slide() if e.key() == Qt.Key_N: self.random_next() if e.key() == Qt.Key_P: self.random_prev() if e.key() == Qt.Key_Comma: self.decrement_slide() if e.key() == Qt.Key_Period: self.increment_slide() if e.key() == Qt.Key_H: self.helpWindow = self.helpWindow() if e.key() == Qt.Key_BracketLeft: self.slideIndex = self.decrement_slide() def mousePressEvent(self, e): if e.button() == QtCore.Qt.LeftButton: print("trapped left mouse click") self.next_slide() if e.button() == QtCore.Qt.RightButton: print("trapped right mouse click") self.prev_slide() def Quit(self): sys.exit(app.exec_())
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 __init__(self): super(Foo, self).__init__(None) self.scene = QGraphicsScene(self.rect()) self.setScene(self.scene) self.scene.addItem(Ball(10))
def setUp(self): super(ReferenceCount, self).setUp() self.scene = QGraphicsScene()