Example #1
0
class MainWindow(QMainWindow):
    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):
        self.setWindowTitle('QTank')
        self.resize(content_width + 20, content_height + 20)
        self.game_scene.setSceneRect(0, 0, content_width, content_height)
        self.graph_view.setGeometry(
            QRect(5, 5, content_width + 5, content_height + 5))
        self.graph_view.setScene(self.start_scene)

        self.mask_view.setSceneRect(0, 0, content_width, content_height)
        self.mask_view.setGeometry(
            QRect(5, 5, content_width + 5, content_height + 5))
        self.mask_view.setStyleSheet('background: transparent')
        self.mask_view.setScene(self.mask_scene)
        self.setCentralWidget(self.main_widget)

    def enter_game_scene(self):
        self.graph_view.setScene(self.game_scene)

    def start_game(self, players: int):
        self.game_scene.start(players)
Example #2
0
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)
Example #3
0
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Pyside2 Graphics Scene")
        self.setGeometry(300, 200, 640, 520)
        self.create_ui()

    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 rotateMinus(self):
        self.view.rotate(-14)

    def rotatePlus(self):
        self.view.rotate(14)
Example #4
0
class DesktopWideOverlay(QMainWindow):
    _instances: Dict[int, QGraphicsItem]
    view: QGraphicsView
    scene: QGraphicsScene

    def __init__(self):
        super().__init__(flags=Qt.Widget
                         | Qt.FramelessWindowHint
                         | Qt.BypassWindowManagerHint
                         | Qt.WindowTransparentForInput
                         | Qt.WindowStaysOnTopHint)
        self.logger = logging.getLogger(__name__ + "." +
                                        self.__class__.__name__)
        self.setAttribute(Qt.WA_NoSystemBackground, True)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.setStyleSheet("background: transparent")
        self._instances = {}

        virtual_screen = QRect(0, 0, 0, 0)

        for screen in QGuiApplication.screens():
            # TODO: Handle screen change
            geom = screen.virtualGeometry()
            virtual_screen = virtual_screen.united(geom)

        self.scene = QGraphicsScene(0,
                                    0,
                                    virtual_screen.width(),
                                    virtual_screen.height(),
                                    parent=self)

        self.view = QGraphicsView(self.scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setStyleSheet("background: transparent")
        self.view.setGeometry(0, 0, virtual_screen.width(),
                              virtual_screen.height())
        self.view.setInteractive(False)

        self.transparent_pen = QPen()
        self.transparent_pen.setBrush(Qt.NoBrush)

        self.setGeometry(virtual_screen)

    def add_instance(
            self, instance: "GameInstance"
    ) -> Tuple[QGraphicsItem, Callable[[], None]]:
        """Add instance to manage, return a disconnect function and the canvas"""
        positionChanged = lambda rect: self.on_instance_moved(instance, rect)
        instance.positionChanged.connect(positionChanged)

        focusChanged = lambda focus: self.on_instance_focus_change(
            instance, focus)
        instance.focusChanged.connect(focusChanged)

        instance_pos = instance.get_position()
        gfx = QGraphicsRectItem(rect=instance_pos)
        gfx.setPen(self.transparent_pen)
        gfx.setPos(instance_pos.x(), instance_pos.y())
        self.scene.addItem(gfx)
        self._instances[instance.wid] = gfx

        def disconnect():
            gfx.hide()
            self.scene.removeItem(gfx)
            instance.positionChanged.disconnect(positionChanged)
            instance.focusChanged.disconnect(focusChanged)

        return gfx, disconnect

    def on_instance_focus_change(self, instance, focus):
        # self._instances[instance.wid].setVisible(focus)
        pass

    def on_instance_moved(self, instance, pos: QRect):
        rect = self._instances[instance.wid]
        rect.setRect(0, 0, pos.width(), pos.height())
        rect.setPos(pos.x(), pos.y())

    def check_compatibility(self):
        QTimer.singleShot(300, self._check_compatibility)

    def _check_compatibility(self):
        # If we cause black screen then hide ourself out of shame...
        screenshot = QGuiApplication.primaryScreen().grabWindow(0)
        image = qpixmap_to_np(screenshot)
        black_pixels = np.count_nonzero(
            np.all(image[:, :, :3] == [0, 0, 0], axis=-1))
        total_pixels = len(image[:, :, 0].flatten())
        black_percent = black_pixels / total_pixels

        self.logger.debug("Screen black ratio %.2f%%", black_percent * 100)
        if black_percent > 0.95:
            self.logger.warning(
                "Detected black screen at %.2f%%. Disabling overlay",
                black_percent * 100,
            )
        self.hide()
Example #5
0
class DesktopWideOverlay(QMainWindow):
    _instances: Dict[int, QGraphicsItem]
    view: QGraphicsView
    scene: QGraphicsScene

    def __init__(self):
        super().__init__(flags=Qt.Widget
                         | Qt.FramelessWindowHint
                         | Qt.BypassWindowManagerHint
                         | Qt.WindowTransparentForInput
                         | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_NoSystemBackground, True)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self._instances = {}

        virtual_screen = QRect(0, 0, 0, 0)

        for screen in QGuiApplication.screens():
            # TODO: Handle screen change
            geom = screen.virtualGeometry()
            virtual_screen = virtual_screen.united(geom)

        self.scene = QGraphicsScene(0,
                                    0,
                                    virtual_screen.width(),
                                    virtual_screen.height(),
                                    parent=self)

        self.view = QGraphicsView(self.scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setStyleSheet("background: transparent")
        self.view.setGeometry(0, 0, virtual_screen.width(),
                              virtual_screen.height())
        self.view.setInteractive(False)

        self.transparent_pen = QPen()
        self.transparent_pen.setBrush(Qt.NoBrush)

        self.setGeometry(virtual_screen)

    def add_instance(
            self, instance: "GameInstance"
    ) -> Tuple[QGraphicsItem, Callable[[], None]]:
        """Add instance to manage, return a disconnect function and the canvas"""
        positionChanged = lambda rect: self.on_instance_moved(instance, rect)
        instance.positionChanged.connect(positionChanged)

        focusChanged = lambda focus: self.on_instance_focus_change(
            instance, focus)
        instance.focusChanged.connect(focusChanged)

        instance_pos = instance.get_position()
        gfx = QGraphicsRectItem(rect=instance_pos)
        gfx.setPen(self.transparent_pen)
        gfx.setPos(instance_pos.x(), instance_pos.y())
        self.scene.addItem(gfx)
        self._instances[instance.wid] = gfx

        def disconnect():
            gfx.hide()
            self.scene.removeItem(gfx)
            instance.positionChanged.disconnect(positionChanged)
            instance.focusChanged.disconnect(focusChanged)

        return gfx, disconnect

    def on_instance_focus_change(self, instance, focus):
        # self._instances[instance.wid].setVisible(focus)
        pass

    def on_instance_moved(self, instance, pos: QRect):
        rect = self._instances[instance.wid]
        rect.setRect(0, 0, pos.width(), pos.height())
        rect.setPos(pos.x(), pos.y())
Example #6
0
class window(QWidget):
    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()

    # key listener for a gameplay that is not provided by tcp
    def keyPressEvent(self, event: PySide2.QtGui.QKeyEvent):
        if self.game_loop:
            if self.against_ai is 0:
                if event.text() in p1_controls:
                    p1_keys.append(event.text())
                if event.text() in p2_controls:
                    p2_keys.append(event.text())
            else:
                if event.text() in p1_controls:
                    p1_keys.append(event.text())

    # main window graphic layout
    def guicomponents(self):
        button_exit = QPushButton("Exit", self)
        button_start = QPushButton("1 player", self)
        button_hot_seat = QPushButton("2 players", self)
        button_multi = QPushButton("Multiplayer", self)
        button_replay = QPushButton("Replay", self)
        button_ai = QPushButton("Against bot", self)
        self.connection_info = QLabel(self)
        self.controls_info = QLabel(self)
        self.scoreboard = QLabel(self)
        self.config_info = QLabel(self)
        self.config_info.setText("")
        self.scoreboard.setText("")
        self.config_info.setFont(PySide2.QtGui.QFont("Courier", 9))
        self.scoreboard.setFont(PySide2.QtGui.QFont("Courier", 10))
        self.scoreboard.setGeometry(QRect(10, 225, 500, 30))
        self.config_info.setGeometry(QRect(10, 225, 790, 30))
        button_start.setGeometry(QRect(10, 250, 100, 30))
        button_exit.setGeometry(QRect(510, 250, 100, 30))
        button_hot_seat.setGeometry(QRect(110, 250, 100, 30))
        button_multi.setGeometry(QRect(210, 250, 100, 30))
        button_replay.setGeometry(QRect(410, 250, 100, 30))
        button_ai.setGeometry(QRect(310, 250, 100, 30))
        self.connection_info.setGeometry(10, 280, 200, 30)
        self.controls_info.setGeometry(220, 280, 200, 30)
        button_hot_seat.clicked.connect(self.prepare_hot_seat)
        button_exit.clicked.connect(exit_app)
        button_start.clicked.connect(self.prepare_single)
        button_multi.clicked.connect(self.prepare_multi)
        button_replay.clicked.connect(self.prepare_replay)
        button_ai.clicked.connect(self.prepare_ai)
        self.view = QGraphicsView(self.scene, self)
        self.view.setGeometry(10, 10, 10 * (width + 2), 10 * (height + 2))
        self.scene.setBackgroundBrush(QBrush(QColor(0, 120, 0, 255)))
        self.grass = QPixmap(":/map/grass.png").scaled(20, 20)
        self.snake = QPixmap(":/map/orange.png").scaled(20, 20)
        self.black = QPixmap(":/map/black.png").scaled(20, 20)
        self.apple = QPixmap(":/map/apple.png").scaled(20, 20)
        self.white = QPixmap(":/map/white.png").scaled(20, 20)
        self.clear_map()

    # load configuration from h5 file and map history from xml file
    def prepare_replay(self):
        try:
            self.scoreboard.setText("")
            with open("config.json", "r") as f:
                self.config = json.load(f)
            output = []
            for k in self.config:
                output.append([k, self.config[k]])
            output = [item for sublist in output for item in sublist]
            self.config_info.setText("".join(output))
            tree = ET.parse("replay.xml")
            root = tree.getroot()
            game_history = []
            rounds = []
            for turn in root:
                for cells in turn:
                    for row in cells:
                        if cells.attrib["indexes"] == "19" and row.attrib[
                                "indexes"] == "77":
                            game_history.append(row.text)
                            copy_history = deepcopy(game_history)
                            rounds.append(copy_history)
                            game_history.clear()
                        else:
                            game_history.append(row.text)
            for round in rounds:
                round = np.reshape(round, (20, 78))
                self.game.map = round
                Snake.get_hex(self.hex, self.game)
                self.initialize_map()
                self.update_map()
                myApp.processEvents()
                time.sleep(0.5)
        except:
            self.config_info.setText("Failed to load a replay!")

    # key listener for multiplayer
    def send_key(self, number, socket):
        self.game_loop = True
        while True:
            time.sleep(0.3)
            if number == "0" and len(p1_keys) > 0:
                try:
                    socket.send(bytes(p1_keys[-1], "utf-8"))
                except:
                    break
            elif number == "1" and len(p2_keys) > 0:
                try:
                    socket.send(bytes(p2_keys[-1], "utf-8"))
                except:
                    break
            if self.end_connection:
                break

    # receive map configuration from the server
    def prepare_multi(self):
        self.end_connection = False
        root = ET.Element("game")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("127.0.0.1", 1235))
        self.connection_info.setText("Connected to server!")

        msg = s.recv(1024).decode("utf-8")
        init_msg = msg.split()
        score_1, score_2 = 0, 0

        if init_msg[0] == "Start":
            if init_msg[1] == "0":
                self.controls_info.setText("Controls Q, A, Z, E, D, C")
            elif init_msg[1] == "1":
                self.controls_info.setText("Controls T, G, B, U, J, M")
            Thread(target=self.send_key, args=(init_msg[-1], s)).start()
            end = False
            frames = 0

            while end is False:
                myApp.processEvents()
                msg = s.recv(4096)
                msg = pickle.loads(msg)

                if msg[0] == 'end':
                    end = True
                    self.config = {
                        "mode-": "Multiplayer",
                        " Client 1 -": str(msg[1]),
                        " Client 2 -": str(msg[-1]),
                        " P1 points-": str(score_1),
                        " P2 points-": str(score_2)
                    }
                    with open("config.json", "w") as f:
                        json.dump(self.config, f)
                    continue

                self.game.map = msg[0]
                doc = ET.SubElement(root, "turn", name=str(frames))
                for i in range(height):
                    row = ET.SubElement(doc, "cell", indexes=str(i))
                    for j in range(width):
                        ET.SubElement(
                            row, "row",
                            indexes=str(j)).text = self.game.map[i][j]

                if len(msg) == 3:
                    score_1, score_2 = msg[1], msg[2]

                if msg[0] != "end":
                    if init_msg[1] == "0":
                        self.scoreboard.setText("Your score - " + str(msg[1]) +
                                                " | " + "Enemy - " +
                                                str(msg[2]))
                    if init_msg[1] == "1":
                        self.scoreboard.setText("Your score - " + str(msg[2]) +
                                                " | " + "Enemy - " +
                                                str(msg[1]))

                if frames == 0:
                    Snake.get_hex(self.hex, self.game)
                    self.initialize_map()

                self.update_map()
                myApp.processEvents()
                frames = frames + 1
                time.sleep(0.25)

            if init_msg[1] == "0":
                if score_1 > score_2:
                    self.scoreboard.setText("You won!")
                elif score_2 > score_1:
                    self.scoreboard.setText("Enemy won!")
                else:
                    self.scoreboard.setText("Draw!")

            if init_msg[1] == "1":
                if score_1 < score_2:
                    self.scoreboard.setText("You won!")
                elif score_2 < score_1:
                    self.scoreboard.setText("Enemy won!")
                else:
                    self.scoreboard.setText("Draw!")

        self.connection_info.setText("Disconnected!")
        tree = ET.ElementTree(root)
        tree.write("replay.xml")
        self.end_connection = True

    def prepare_hot_seat(self):
        self.hot_seat = 1
        self.against_ai = 0
        self.clear_map()
        self.start_game()

    def prepare_single(self):
        self.hot_seat = 0
        self.against_ai = 0
        self.clear_map()
        self.start_game()

    def prepare_ai(self):
        self.against_ai = 1
        self.hot_seat = 0
        self.clear_map()
        self.start_game()

    def clear_map(self):
        self.game.init_map()
        Snake.get_hex(self.hex, self.game)
        self.initialize_map()

    def initialize_map(self):
        self.grahpicsitem = []
        self.scene.clear()
        for i in self.hex:
            if self.game.map[i[0]][i[1]] == " ":
                cell = QGraphicsPixmapItem(self.grass)
                cell.setPos(QPointF(i[1] * 10, i[0] * 10))
                self.grahpicsitem.append(cell)
                self.scene.addItem(cell)
            elif self.game.map[i[0]][i[1]] == "#":
                cell = QGraphicsPixmapItem(self.black)
                cell.setPos(QPointF(i[1] * 10, i[0] * 10))
                self.grahpicsitem.append(cell)
                self.scene.addItem(cell)
            elif self.game.map[i[0]][i[1]] == "+":
                cell = QGraphicsPixmapItem(self.white)
                cell.setPos(QPointF(i[1] * 10, i[0] * 10))
                self.grahpicsitem.append(cell)
                self.scene.addItem(cell)
            if self.game.map[i[0]][i[1]] == "@":
                cell = QGraphicsPixmapItem(self.apple)
                cell.setPos(QPointF(i[1] * 10, i[0] * 10))
                self.grahpicsitem.append(cell)
                self.scene.addItem(cell)

    def update_map(self):
        for i in range(len(self.hex)):
            if self.game.map[self.hex[i][0]][self.hex[i][1]] == " ":
                self.grahpicsitem[i].setPixmap(self.grass)
            elif self.game.map[self.hex[i][0]][self.hex[i][1]] == "#":
                self.grahpicsitem[i].setPixmap(self.black)
            elif self.game.map[self.hex[i][0]][self.hex[i][1]] == "@":
                self.grahpicsitem[i].setPixmap(self.apple)
            elif self.game.map[self.hex[i][0]][self.hex[i][1]] == "+":
                self.grahpicsitem[i].setPixmap(self.white)

    def start_game(self):
        self.config_info.setText("")
        self.game_loop, spawn_fruit = False, False

        if self.game_loop is not True:
            p1_keys.clear(), p2_keys.clear()

        root = ET.Element("game")
        spawn_animal1, spawn_animal2, self.game_loop = False, False, True
        p1_can_play, p2_can_play = True, True
        animal1, animal2 = [], []
        points1, points2 = 0, 0

        # find free space on the map and spawn snake (or snakes)
        if (self.hot_seat and self.against_ai is 0) or (self.hot_seat is 0
                                                        and self.against_ai):
            self.scoreboard.setText("1.P1 points - " + str(points1) +
                                    " | 2.P2 points - " + str(points2))
            while (spawn_animal1 is False) and (spawn_animal2 is False):
                if not spawn_animal1:
                    x = np.random.randint(0, len(self.hex))
                    spawn_animal1, _ = Snake.check_space(
                        self.game.map, self.hex[x], 1, [0, 0, "#", "+"], 0)
                if not spawn_animal2:
                    y = np.random.randint(0, len(self.hex))
                    spawn_animal2, _ = Snake.check_space(
                        self.game.map, self.hex[y], 1, [0, 0, "#", "+"], 0)
            animal1.insert(0, snake(self.hex[x], self.game.map, "#"))
            animal2.insert(0, snake(self.hex[y], self.game.map, "+"))
        elif self.hot_seat is 0 and self.against_ai is 0:
            self.scoreboard.setText("Points - " + str(points1))
            while not spawn_animal1:
                x = np.random.randint(0, len(self.hex))
                spawn_animal1, _ = Snake.check_space(self.game.map,
                                                     self.hex[x], 1,
                                                     [0, 0, "#"], 0)
            animal1.insert(0, snake(self.hex[x], self.game.map, "#"))

        #main game loop
        index = 0
        while self.game_loop:

            # save actual map to xml file
            doc = ET.SubElement(root, "turn", name=str(index))
            for i in range(height):
                row = ET.SubElement(doc, "cell", indexes=str(i))
                for j in range(width):
                    ET.SubElement(row, "row",
                                  indexes=str(j)).text = self.game.map[i][j]

            # spawn fruit on the map
            if not spawn_fruit:
                while not spawn_fruit:
                    x = np.random.randint(0, len(self.hex))
                    spawn_fruit, _ = Snake.check_space(self.game.map,
                                                       self.hex[x], 1,
                                                       [0, 0, "@"], 0)

            fruit_on_map = fruit(self.hex[x], self.game.map, "@")

            spawn_fruit, points1, points2, p1_can_play, p2_can_play, self.game_loop = \
                Snake.move_anim(p1_can_play, p2_can_play, spawn_fruit, animal1, animal2, points1, points2, fruit_on_map,
                                p1_keys, p2_keys, self.hot_seat, self.against_ai, self.game, self.hex, self.scoreboard,
                                self.game_loop)

            self.update_map()
            index = index + 1
            myApp.processEvents()
            time.sleep(0.5)

        # prepare configuration and map history
        if self.hot_seat is 0 and self.against_ai is 0:
            self.config = {"mode-": "Singleplayer", " points-": str(points1)}
        elif self.hot_seat and self.against_ai is 0:
            self.config = {
                "mode-": "Hotseat",
                " P1 points-": str(points1),
                " P2 points-": str(points2)
            }
        elif self.hot_seat is 0 and self.against_ai:
            self.config = {
                "mode-": "Against Bot",
                " P1 points-": str(points1),
                " P2 points-": str(points2)
            }
        with open("config.json", "w") as f:
            json.dump(self.config, f)

        tree = ET.ElementTree(root)
        tree.write("replay.xml")

        if (self.hot_seat and self.against_ai is 0) or (self.hot_seat is 0
                                                        and self.against_ai):
            if points1 == points2:
                self.scoreboard.setText("It's draw! 1.P1 score - " +
                                        str(points1) + " | 2.P2 score - " +
                                        str(points2))
            elif points1 > points2:
                self.scoreboard.setText("P1 won! 1.P1 score - " +
                                        str(points1) + " | 2.P2 score - " +
                                        str(points2))
            else:
                self.scoreboard.setText("P2 won! 1.P1 score - " +
                                        str(points1) + " | 2.P2 score - " +
                                        str(points2))
        else:
            self.scoreboard.setText("You lost! Your score - " + str(points1))
Example #7
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Network Designer")
        self.setGeometry(300, 200, 840, 720)
        self.current_id = 1
        self.createLayout()

        self.couple = []
        self.show()

    def makeButtonsLayout(self):
        self.button = QPushButton("Add Node", self)
        self.button.clicked.connect(self.addNode)

        self.btn_connection = QPushButton("Add Connection:", self)
        self.btn_connection.clicked.connect(self.addConnection)

        self.button3 = QPushButton("Export Network", self)
        self.button3.clicked.connect(self.file_save)

        self.lbl_connection = QLabel("Connection")

        self.l_btns = QHBoxLayout()
        self.l_btns.addWidget(self.button3)
        self.l_btns.addStretch()
        self.l_btns.addWidget(self.btn_connection)
        self.l_btns.addWidget(self.lbl_connection)
        self.l_btns.addStretch()
        self.l_btns.addWidget(self.button)
        self.btns = QWidget()
        self.btns.setLayout(self.l_btns)
        self.btns.setFixedHeight(40)

    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 createOrderList(self):
        self.orderList = QListWidget()
        # Enable drag & drop ordering of items.
        self.orderList.setDragDropMode(QAbstractItemView.InternalMove)

    def createLayout(self):
        self.makeButtonsLayout()
        self.initializeGview()
        self.createOrderList()

        l_network = QHBoxLayout()
        l_network.addWidget(self.view)
        l_network.addStretch()
        l_network.addWidget(self.orderList)

        self.l_root = QVBoxLayout()
        self.l_root.addLayout(l_network)
        self.l_root.addStretch()
        self.l_root.addWidget(self.btns)

        # self.l_root.addWidget(self.view)
        self.setLayout(self.l_root)

    def addNode(self):
        greenBrush = QBrush(Qt.green)
        blackPen = QPen(Qt.black)
        # blueBrush = QBrush(Qt.blue)

        blackPen.setWidth(5)
        ellipse = GraphicsEllipse(str(self.current_id), blackPen, greenBrush, 100, 100, NODE_D, NODE_D)
        self.scene.addItem(ellipse)
        self.current_id += 1

    def keepNode(self, node):
        if len(self.couple) < 2:
            self.couple.append(node)
        else:
            self.couple.pop(0)
            self.couple.append(node)
        if len(self.couple) == 2:
            self.lbl_connection.setText(self.couple[0].label + " --> " + self.couple[1].label)

    def addConnection(self):
        line = GraphicsLine(self.couple[0], self.couple[1], NODE_R)
        self.scene.addItem(line)

        for v in self.couple:
            v.add_connection(line)
        self.orderList.addItem(self.lbl_connection.text())

    def getNodes(self):
        positions = {}
        for i in self.scene.items():
            if type(i) is GraphicsEllipse:
                positions[int(i.label)] = i.getPosition()
        return positions

    def getConnections(self):
        connections = []
        for i in range(self.orderList.count()):
            conn = self.orderList.item(i).text().split(" --> ")
            connections.append((int(conn[0]), int(conn[1]), {"label": str(i + 1)}))
        return connections

    def file_save(self):
        positions = self.getNodes()
        connections = self.getConnections()
        network = {}
        network["labels"] = {i: i for i in sorted(list(positions.keys()))}
        network["edges"] = connections
        network["pos"] = positions
        text = json.dumps(network)
        name = QFileDialog.getSaveFileName(self, 'Save File')
        file = open(name[0], 'w')
        # text = "something"
        file.write(text)
        file.close()
Example #8
0
    def contextMenuEvent(self, event: QGraphicsSceneContextMenuEvent) -> None:
        """
		Opens a context menu (right click menu) for the component.

		:param event: The event that was generated when the user right-clicked on this item.
		:type event: QGraphicsSceneContextMenuEvent
		:return: None
		:rtype: NoneType
		"""
        return QGraphicsItem.contextMenuEvent(event)

        # if not self._menuEnabled:
        # 	return QGraphicsItem.contextMenuEvent(self, event)
        #
        # self.setSelected(True)
        # self.menu.exec_(event.screenPos())

    def mousePressEvent(self, event):
        event.ignore()


if __name__ == "__main__":
    app = QApplication()
    v = QGraphicsView()
    v.setGeometry(500, 500, 500, 500)
    s = QGraphicsScene()
    v.setScene(s)
    p = PortGraphics(port.Port())
    s.addItem(p)
    v.show()
    sys.exit(app.exec_())