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_()
Ejemplo n.º 2
0
class MoveHistoryView(QGraphicsView):
    """A widget containing a view of the move history."""
    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 set_move_history(self, move_history):
        """
        Sets the move history according to a list of moves.

        :param move_history: List of half moves
        """
        text = ''
        half_move_number = 1
        full_move_number = 1
        for half_move in move_history:
            if half_move_number % 2 == 1:
                text += str(full_move_number) + '. ' + half_move
                half_move_number += 1
            else:
                text += ' ' + half_move + '\n'
                half_move_number += 1
                full_move_number += 1

        self.text_item.setText(text)
Ejemplo n.º 3
0
class NodeWidget(QWidget):
    def __init__(self, parent):
        super(NodeWidget, self).__init__(parent)
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)

        self.node_editor = NodeEditor(self)
        self.scene = QGraphicsScene()
        self.view = View(self)
        self.view.setScene(self.scene)
        self.node_editor.install(self.scene)

        main_layout.addWidget(self.view)

        self.create_random_nodes(10)

    def create_random_nodes(self, num):

        for i in range(num):
            node = Node()
            for i in range(random.randrange(2, 10)):
                word = lorem.sentence().split(" ")[0]
                node.add_port(name=word, is_output=bool(random.getrandbits(1)))
                node.title = "Title"
                node.type = "example"
            node.build()
            self.scene.addItem(node)
Ejemplo n.º 4
0
    def draw_ground_objects(self, scene: QGraphicsScene, cp: ControlPoint) -> None:
        added_objects = []
        for ground_object in cp.ground_objects:
            if ground_object.obj_name in added_objects:
                continue

            go_pos = self._transform_point(ground_object.position)
            if not ground_object.airbase_group:
                buildings = self.game.theater.find_ground_objects_by_obj_name(
                    ground_object.obj_name
                )
                scene.addItem(
                    QMapGroundObject(
                        self,
                        go_pos[0],
                        go_pos[1],
                        14,
                        12,
                        cp,
                        ground_object,
                        self.game,
                        buildings,
                    )
                )

            should_display = self.should_display_ground_objects_at(cp)
            if ground_object.might_have_aa and should_display:
                for group in ground_object.groups:
                    self.draw_threat_range(scene, group, ground_object, cp)
            added_objects.append(ground_object.obj_name)
Ejemplo n.º 5
0
    def __init__(self, player_1: Player, player_2: Player, size: int = 600):
        super().__init__()
        self.setWindowTitle("Ultimate Tic-Tac-Toe")
        self.player_1 = player_1
        self.player_2 = player_2
        self.game = UltimateTicTacToe()
        self.size = size  # size of window
        self.maxi_size = size
        self.mini_size = int(self.size / 3 * 0.8)
        self.click_needed = False
        self.clear = True

        scene = QGraphicsScene()
        self.board = TicTacToeBoard(state=self.game.get_maxiboard(),
                                    point=(self.size // 2, self.size // 2),
                                    size=self.maxi_size,
                                    board_thickness=6,
                                    token_thickness=4)
        scene.addItem(self.board)
        self.mini_centers = self._find_miniboard_centers()
        self.miniboards = [
            TicTacToeBoard(state=self.game.get_miniboard(i),
                           point=self.mini_centers[i],
                           size=self.mini_size,
                           board_thickness=3,
                           token_thickness=8) for i in range(9)
        ]
        for miniboard in self.miniboards:
            scene.addItem(miniboard)
            miniboard.setPos(miniboard.get_point()[0],
                             miniboard.get_point()[1])
        scene.setSceneRect(0, 0, self.size, self.size)
        self.setScene(scene)
Ejemplo n.º 6
0
 def plot(self, filename):
     image = QPixmap()
     image.load(filename)
     item = QGraphicsPixmapItem(image)
     scene = QGraphicsScene()
     scene.addItem(item)
     self.ui.graphicsView.setScene(scene)
Ejemplo n.º 7
0
class MainWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.scene = None
        self.populateScene()

        self.h1Splitter = QSplitter()
        self.h2Splitter = QSplitter()

        vSplitter = QSplitter()
        vSplitter.setOrientation(Qt.Vertical)
        vSplitter.addWidget(self.h1Splitter)
        vSplitter.addWidget(self.h2Splitter)

        view = View("Top left view", self)
        view.view().setScene(self.scene)
        self.h1Splitter.addWidget(view)

        view = View("Top right view", self)
        view.view().setScene(self.scene)
        self.h1Splitter.addWidget(view)

        view = View("Bottom left view", self)
        view.view().setScene(self.scene)
        self.h2Splitter.addWidget(view)

        view = View("Bottom right view", self)
        view.view().setScene(self.scene)
        self.h2Splitter.addWidget(view)

        layout = QHBoxLayout()
        layout.addWidget(vSplitter)
        self.setLayout(layout)

        self.setWindowTitle(self.tr("Chip Example"))

    def populateScene(self):

        self.scene = QGraphicsScene(self)

        image = QImage(":/qt4logo.png")
        xx: int = 0
        nitems: int = 0
        for i in range(-11000, 11000, 110):
            xx += 1
            yy: int = 0
            for j in range(-7000, 7000, 70):
                yy += 1
                x = (i + 11000) / 22000.0
                y = (j + 7000) / 14000.0

                color = QColor(
                    image.pixel(int(image.width() * x),
                                int(image.height() * y)))
                item = Chip(color, xx, yy)
                item.setPos(QPointF(i, j))
                self.scene.addItem(item)
                nitems += 1
Ejemplo n.º 8
0
class Schematic:
    def __init__(self):
        self.root = Composite()
        self.scene = QGraphicsScene()

    def add_element(self, element):
        self.root.add_child(element.desc)
        self.scene.addItem(element)
Ejemplo n.º 9
0
 def _add(
         self,
         to: QtWidgets.QGraphicsScene,
         what: QtWidgets.QGraphicsObject,
         where: tuple = (0, 0),
 ):
     to.addItem(what)
     what.setPos(*where)
Ejemplo n.º 10
0
 def map_View_Update(self, msg):
     try:
         item = QGraphicsPixmapItem(msg)
         scene = QGraphicsScene()
         scene.addItem(item)
         self.ui.Map_View.setScene(scene)
         self.ui.Map_View.show()
     except:
         pass
Ejemplo n.º 11
0
def showLogo(win, logoName):

    logoPath = str(sessionVars.assetPath / logoName)

    ico = QGraphicsSvgItem(logoPath)
    scene = QGraphicsScene()
    scene.addItem(ico)

    win.logo.setScene(scene)
Ejemplo n.º 12
0
 def view_Clear(self):
     try:
         clear = QPixmap(1, 1)
         clear.fill(QColor("white"))
         clear = QGraphicsPixmapItem(clear)
         scene = QGraphicsScene()
         scene.addItem(clear)
         return scene
     except:
         pass
Ejemplo n.º 13
0
    def __init__(self):
        QWidget.__init__(self)

        layout = QVBoxLayout(self)
        layout.addWidget(QVideoWidget())

        graphicsScene = QGraphicsScene()
        graphicsView = QGraphicsView(graphicsScene)
        graphicsScene.addItem(QGraphicsVideoItem())
        layout.addWidget(graphicsView)
 def draw_frontline_approximation(self, frontline: FrontLine,
                                  scene: QGraphicsScene, pen: QPen) -> None:
     posx = frontline.position
     h = frontline.attack_heading
     pos2 = self._transform_point(posx)
     self.draw_bezier_frontline(scene, pen, frontline)
     p1 = point_from_heading(pos2[0], pos2[1], h + 180, 25)
     p2 = point_from_heading(pos2[0], pos2[1], h, 25)
     scene.addItem(
         QFrontLine(p1[0], p1[1], p2[0], p2[1], frontline, self.game_model))
Ejemplo n.º 15
0
class Main_Window(QMainWindow):
    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 draw_actual_frontline(self, frontline: FrontLine,
                           scene: QGraphicsScene, pen: QPen) -> None:
     self.draw_bezier_frontline(scene, pen, frontline)
     vector = Conflict.frontline_vector(frontline.control_point_a,
                                        frontline.control_point_b,
                                        self.game.theater)
     left_pos = self._transform_point(vector[0])
     right_pos = self._transform_point(vector[0].point_from_heading(
         vector[1], vector[2]))
     scene.addItem(
         QFrontLine(left_pos[0], left_pos[1], right_pos[0], right_pos[1],
                    frontline, self.game_model))
class UiVScreenOverview:

    def __init__(self, view, vscreen):
        """
        :type view: PySide2.QtWidgets.QGraphicsView.QGraphicsView
        :param vscreen: hwmonitor.vscreen.vscreen.VScreen
        """
        self.view = view
        self.vscreen = vscreen

        self.view_margin = 10
        self.background_color = QColor(100, 100, 100)

        view.setInteractive(False)
        view.setStyleSheet('border: 0px;')
        view.setRenderHint(QPainter.Antialiasing)
        view.setCacheMode(QGraphicsView.CacheBackground)
        view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.scene = QGraphicsScene(view)
        self.scene.setBackgroundBrush(self.background_color)

        for monitor in self.vscreen.monitors:
            item = MonitorRepresentation(index_from_device_name(monitor.device_name), monitor)
            item.update_position()
            self.scene.addItem(item)

        view.setScene(self.scene)

    def update_position(self):
        for item in self.scene.items():
            item.update_position()

    def resize_scene(self):
        """Resize the scene to fit inside the available space of the viewport with an given margin.

        Update the scene rect, since it probably changes when changing the layout.
        """
        rect = self.scene.itemsBoundingRect()
        self.view.setSceneRect(rect)

        view_rect = self.view.viewport().rect().adjusted(self.view_margin, self.view_margin,
                                                         -self.view_margin, -self.view_margin)
        scene_rect = self.view.matrix().mapRect(rect)

        x_factor = view_rect.width() / scene_rect.width()
        y_factor = view_rect.height() / scene_rect.height()
        factor = min(x_factor, y_factor)

        self.view.scale(factor, factor)
        self.view.centerOn(rect.center())
Ejemplo n.º 18
0
 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)
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
    def __init__(self, start_state: GridGameState):
        super().__init__(start_state)
        self.start_state: GridGameState = start_state
        self.spaces = []  # self.spaces[i][j] holds row i, column j
        self.column_dividers = []
        self.row_dividers = []
        self.column_labels = []
        self.row_labels = []
        self.text_x = self.text_y = 0

        ui = self.ui = Ui_GridControls()
        ui.setupUi(self)
        scene = QGraphicsScene()
        ui.game_display.setScene(scene)
        scene.setBackgroundBrush(self.background_colour)
        self.player1_icon = self.create_icon(self.player1_colour)
        self.player2_icon = self.create_icon(self.player2_colour)
        ui.black_count_pixmap.setText('')
        ui.white_count_pixmap.setText('')
        ui.black_count.setText('')
        ui.white_count.setText('')

        for _ in range(start_state.board_height - 1):
            self.row_dividers.append(scene.addLine(0, 0, 1, 1))
        for _ in range(start_state.board_width - 1):
            self.column_dividers.append(scene.addLine(0, 0, 1, 1))
        for i in range(start_state.board_height):
            self.row_labels.append(scene.addSimpleText(f'{i + 1}'))
        for j in range(start_state.board_width):
            self.column_labels.append(scene.addSimpleText(chr(65 + j)))
        self.to_move = scene.addEllipse(0,
                                        0,
                                        1,
                                        1,
                                        brush=self.get_player_brush(
                                            self.start_state.X_PLAYER))
        self.to_move.setVisible(False)
        self.move_text = ui.move_text
        for i in range(self.start_state.board_height):
            row: typing.List[QGraphicsItem] = []
            self.spaces.append(row)
            for j in range(self.start_state.board_width):
                piece = GraphicsPieceItem(i, j, self)
                scene.addItem(piece)
                piece.setBrush(self.background_colour)
                piece.setPen(self.background_colour)
                row.append(piece)
        self.debug_message = ''
Ejemplo n.º 21
0
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)
Ejemplo n.º 22
0
    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_()
Ejemplo n.º 23
0
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, QTransform()), self.topleft)
        self.assertEqual(self.scene.itemAt(150, 50, QTransform()),
                         self.topright)
        self.assertEqual(self.scene.itemAt(50, 150, QTransform()),
                         self.bottomleft)
        self.assertEqual(self.scene.itemAt(150, 150, QTransform()),
                         self.bottomright)
Ejemplo n.º 24
0
class MainWindow(QMainWindow):
    def __init__(self):
        # super(MainWindow, self).__init__()
        super().__init__()

        # self.ui = QMainWindow()
        self.label = QLabel(f'<h1>Hello World</h1>')
        self.setGeometry(10, 70, 1000, 700)
        
        self.view = QGraphicsView()
        self.scene = QGraphicsScene()
        self.scene.setSceneRect(0, 0, 800, 520)
        self.view.setScene(self.scene)

        # greenBrush = QBrush(Qt.green)
        # blueBrush = QBrush(Qt.blue)
        # outlinePen = QPen(Qt.black)
        # outlinePen.setWidth(2)

        # self.rectangle = self.scene.addRect(100, 0, 80, 100, outlinePen, blueBrush)
        # self.ellipse = self.scene.addEllipse(0, -100, 300, 60, outlinePen, greenBrush)
        # self.text = self.scene.addText('Hello World')

        # item = SlotItem(1);
        # self.scene.addItem(item)
        self.bracket1 = BracketItem(1)
        self.bracket1.setPos(10, 10)
        self.bracket2 = BracketItem(2)
        self.bracket2.setPos(10, 300)

        self.bracket3 = BracketItem(3)
        self.bracket3.setPos(450, 10)
        self.bracket4 = BracketItem(4)
        self.bracket4.setPos(450, 300)

        self.scene.addItem(self.bracket1)
        self.scene.addItem(self.bracket2)
        self.scene.addItem(self.bracket3)
        self.scene.addItem(self.bracket4)
        # self.bracket1.drawNodes()
        self.setCentralWidget(self.view)
Ejemplo n.º 25
0
 def __init__(self,
              targetImage=None,
              axeSize=500,
              layer=None,
              parent=None,
              mainForm=None):
     super().__init__(parent=parent)
     self.layer = layer
     # additional inactive curve to draw (QPolyLineF or list of QPointF)
     self.baseCurve = None
     self.setMinimumSize(axeSize + 60, axeSize + 140)
     self.setAttribute(Qt.WA_DeleteOnClose)
     graphicsScene = QGraphicsScene()
     self.setScene(graphicsScene)
     # back links to image
     graphicsScene.targetImage = weakProxy(targetImage)
     graphicsScene.layer = weakProxy(layer)
     graphicsScene.bgColor = QColor(200, 200, 200)
     self.mainForm = mainForm
     graphicsScene.axeSize = axeSize
     # add axes and grid
     graphicsScene.defaultAxes = self.drawPlotGrid(axeSize)
     graphicsScene.addItem(graphicsScene.defaultAxes)
     # connect layer colorPicked signal
     self.scene().layer.colorPicked.sig.connect(self.colorPickedSlot)
     # default WhatsThis for interactive curves
     self.setWhatsThis("""
         The background histogram is the <i>input</i> histogram; it is refreshed only
         when the curve is reset.<br>
         <b>Drag control points</b> with the mouse.<br>
         <b>Add a control point</b> by clicking on the curve.<br>
         <b>Remove a control point</b> by clicking it.<br>
         <b>Zoom</b> with the mouse wheel.<br>
         <b>Set black, white and neutral points</b> in the image by clicking the corresponding pixels
         while pressing one of the following key combination (RGB and Lab curves only):<br>
         &nbsp;&nbsp;<b>Black Point</b> : Ctrl+Shift<br>
         &nbsp;&nbsp;<b>White Point</b> : Ctrl<br>
         &nbsp;&nbsp;<b>Grey Neutral Point (Lab only)</b></br> : Shift<br>
         <b>Caution</b> : Selecting a black, white or neutral point in an image is enabled only when
         the Color Chooser is closed.
         """)  # end setWhatsThis
Ejemplo n.º 26
0
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_()
Ejemplo n.º 27
0
    def dispaly_image(self):
        '''在 ModifyQGraphicsView 显示一张图片

        在 ModifyQGraphicsView 显示一张图片       

        @参数说明: 
            无

        @返回值: 
            无

        @注意: 
            无
        '''

        # 根据图片的维度,进行不同的处理
        if self._image_shape is 2:
            # 如果是二维灰度图片,读取方式为QImage.Format_Grayscale8
            temp_q_image = QImage(self._image_data, self._image_h,
                                  self._image_w, QImage.Format_Grayscale8)
        elif self._image_shape is 3:
            # 由于QImage读取方式为RGB,但 opencv 读取图片形式为BGR,所以要进行色彩转换
            temp_q_image = cv2.cvtColor(self._image_data, cv2.COLOR_BGR2RGB)

            # 如果是三维灰度图片,读取方式为QImage.Format_RGB888
            temp_q_image = QImage(temp_q_image, self._image_h, self._image_w,
                                  QImage.Format_RGB888)
        else:
            return None

        # 2. 像素映射
        temp_q_image_pix = QPixmap.fromImage(temp_q_image)  # 将给定图像转换为像素映射

        # 3. 在graphics_view中显示图片
        temp_item = QGraphicsPixmapItem(temp_q_image_pix)
        temp_q_sece = QGraphicsScene()
        temp_q_sece.addItem(temp_item)
        self.setScene(temp_q_sece)
        temp_q_sece.clearSelection()
Ejemplo n.º 28
0
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)
Ejemplo n.º 29
0
class Stats:
    def __init__(self):
        # 从文件中加载UI定义
        qfile_stats = QFile("classifier.ui")
        qfile_stats.open(QFile.ReadOnly)
        qfile_stats.close()
        self.ui = QUiLoader().load(qfile_stats)

        self.ui.button1.clicked.connect(self.click_button1)
        self.ui.button2.clicked.connect(self.click_button2)

    def click_button1(self):
        global pic_path
        pic_path = tkinter.filedialog.askopenfilename()
        root = tkinter.Tk()  # 创建一个Tkinter.Tk()实例
        root.withdraw()  # 将Tkinter.Tk()实例隐藏
        print(pic_path)

        link = pic_path
        # request.urlretrieve(link,'F:/Pycharm/PyCharm Community Edition 2020.2.3/ServiceInnovate/CNN/inputs')
        copyfile(pic_path, 'inputs/01.jpg')

        img = cv2.imread(pic_path)  # 读取图像
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 转换图像通道
        x = img.shape[1]  # 获取图像大小
        y = img.shape[0]
        self.zoomscale = 1  # 图片放缩尺度
        frame = QImage(img, x, y, QImage.Format_RGB888)
        pix = QPixmap.fromImage(frame)
        self.item = QGraphicsPixmapItem(pix)  # 创建像素图元
        self.item.setScale(self.zoomscale)
        self.scene = QGraphicsScene()  # 创建场景
        self.scene.addItem(self.item)
        self.ui.graphicsView.setScene(self.scene)  # 将场景添加至视图

    def click_button2(self):

        os.system('python inference.py')
Ejemplo n.º 30
0
class GameStateView(QGraphicsView):
    """A widget displaying a view of the chess game state."""
    def __init__(self, parent):
        QGraphicsView.__init__(self, parent)
        self.setMinimumSize(180, 115)
        self.setMaximumSize(180, 115)
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.text_item = QGraphicsSimpleTextItem()
        self.scene.addItem(self.text_item)
        self.show()

    def set_game_state(self, game_state):
        """
        Updates the game state view with the provided values.

        :param game_state: Dictionary containing {topic:value} pairs
        """
        text = ''
        for topic in game_state:
            text += topic + ': ' + game_state[topic] + '\n'

        self.text_item.setText(text)
Ejemplo n.º 31
0
	def __init__(self, parent: QWidget = None) -> None:
		"""
		Create a GraphicsView for Facile.
		:param parent: The widget to embed the graphics view into
		:type parent: QWidget
		:return: None
		:rtype: NoneType
		"""
		super(FacileGraphicsView, self).__init__(parent)

		# set flags
		self.setDragMode(QGraphicsView.ScrollHandDrag)
		self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
		
		# show initial message
		scene = QGraphicsScene()
		box = QGraphicsRectItem(0, 0, 100, 100)
		box.setPen(QColor(Qt.transparent))
		box.setBrush(QColor(Qt.transparent))
		QGraphicsTextItem("Nothing to show here yet!", box)
		scene.addItem(box)
		
		self.setScene(scene)
Ejemplo n.º 32
0
class GameWindow(QGraphicsView):
    def __init__(self, parent=None):
        super(GameWindow, self).__init__(parent=parent)
        self.screen = None
        self.scene = QGraphicsScene()
        self.scene.setSceneRect(
            QRect(left=0,
                  top=0,
                  width=PLAYGROUND_SIZEX * SCALE_FACTORX,
                  height=PLAYGROUND_SIZEY * SCALE_FACTORY))
        self.setFrameStyle(4)
        self.setScene(self.scene)
        self.snake = []
        # define SnakeHead
        self.snake.append(QGraphicsRectItem())
        self.snake[0].setRect(QRect(0, 0, SCALE_FACTORX, SCALE_FACTORY))

        self.snake[0].setBrush(brushHead)
        self.scene.addItem(self.snake[0])
        # define rest of the snake
        for i in range(1, MAX_LENGTH_SNAKE):
            self.snake.append(QGraphicsRectItem())
            self.snake[i].setRect(QRect(0, 0, SCALE_FACTORX, SCALE_FACTORY))
            self.snake[i].setBrush(brushBody)
            self.snake[i].setVisible(False)
            self.scene.addItem(self.snake[i])
        # Create the graphic item for apple
        self.goal = QGraphicsRectItem()
        self.goal.setRect(QRect(0, 0, SCALE_FACTORX, SCALE_FACTORY))
        self.goal.setBrush(brushGoal)
        self.scene.addItem(self.goal)

        self.show()

    def draw(self, state):
        self.goal.setPos(state.goal.x * SCALE_FACTORX,
                         state.goal.y * SCALE_FACTORY)
        self.goal.setVisible(True)
        self.snake[0].setPos(float(state.snake[0].x * SCALE_FACTORX),
                             float(state.snake[0].y * SCALE_FACTORY))
        for i in range(1, state.snake_length):
            self.snake[i].setPos(state.snake[i].x * SCALE_FACTORX,
                                 state.snake[i].y * SCALE_FACTORY)
            self.snake[i].setVisible(True)
        for i in range(state.snake_length, MAX_LENGTH_SNAKE):
            self.snake[i].setVisible(False)

    def screenshot(self):
        self.screen = self.grab()
        self.screen.save("./snake_screen.png")
Ejemplo n.º 33
0
class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.layout = QVBoxLayout(self)
        rect = QRectF(0, 0, 800, 800)
        self.scene = QGraphicsScene(rect)
        item = Node()
        self.scene.addItem(item)
        item1 = Node()
        item1.setPos(QPoint(50, 50))
        self.scene.addItem(item1)
        item2 = QGraphicsRectItem(10, 10, 50, 50)
        self.scene.addItem(item2)
        line = Edge(item, item1)
        self.scene.addItem(line)
        self.view = NetworkView(self.scene, self)
        self.view.setCacheMode(QGraphicsView.CacheBackground)
        self.view.setViewportUpdateMode(
            QGraphicsView.BoundingRectViewportUpdate)
        print(item1.scenePos())
        print(item1.pos())
        self.layout.addWidget(self.view)
        self.setLayout(self.layout)
Ejemplo n.º 34
0
class Foo(QGraphicsView):
    def __init__(self):
        super(Foo, self).__init__(None)
        self.scene = QGraphicsScene(self.rect())
        self.setScene(self.scene)
        self.scene.addItem(Ball(10))
Ejemplo n.º 35
0
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_())