示例#1
0
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel(
            "Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")
示例#2
0
    def __init__(self, color, ip, connected_ip, name):
        super().__init__()

        self.setWindowTitle("LAN Chess")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.svgX = 50  # top left x-pos of chessboard
        self.svgY = 50  # top left y-pos of chessboard
        self.cbSize = 600  # size of chessboard
        self.widgetSvg.setGeometry(self.svgX, self.svgY, self.cbSize,
                                   self.cbSize)
        self.coordinates = True
        self.color = color  #True for white, False for black
        self.margin = 0.05 * self.cbSize if self.coordinates == True else 0
        self.squareSize = (self.cbSize - 2 * self.margin) / 8.0
        self.chessboard = chess.Board()
        self.squareToMove = None  #square of the selected piece as a string
        self.selectedPiece = None  #selected piece
        self.squares = None  #squares to be selected to show possible moves
        self.lastMove = None  #last move to highlight
        self.check = None  # not None if a player is in check
        self.connected_ip = connected_ip  #opponents ip
        self.ip = ip  #own ip
        self.port = 5000  #tcp port for sending moves
        self.name = name  #name of the player
示例#3
0
    def __init__(self):
        """
        Initialize the chessboard.
        """
        super().__init__()

        self.setWindowTitle("DeepChess")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 600, 600)

        self.label = QLabel('---', parent=self)
        self.label.setGeometry(10, 600, 600, 100)

        self.boardSize = min(self.widgetSvg.width(), self.widgetSvg.height())
        self.coordinates = True
        self.margin = 0.05 * self.boardSize if self.coordinates else 0
        self.squareSize = (self.boardSize - 2 * self.margin) / 8.0
        self.playerMove = True

        self.engine = DeepChess('b')
        #self.board = chess.Board()
        self.pieceToMove = [None, None]
        self.updateBoard()
    def __init__(self):
        """
        Initialize the chessboard.
        """
        super().__init__()

        self.setWindowTitle("Chess GUI")
        self.setGeometry(300, 300, 610, 610)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 600, 600)

        self.boardSize = min(self.widgetSvg.width(), self.widgetSvg.height())
        self.coordinates = True
        self.margin = 0.05 * self.boardSize if self.coordinates else 0
        self.squareSize = (self.boardSize - 2 * self.margin) / 8.0
        self.pieceToMove = [None, None]

        self.board = chess.Board()

        self.game = chess.pgn.Game()
        self.game.headers["Event"] = "test"
        self.game.headers["White"] = "user"
        self.game.headers["Black"] = "homemade engine"
        self.game.setup(self.board)
        self.node = self.game

        self.drawBoard()
示例#5
0
 def visualizeAI(self):
     svgBytes = self.ai.visualize()
     dialog = QDialog(self)
     dialog.setWindowTitle("AI Algorithm Visualization")
     svgWidget = QSvgWidget(dialog)
     svgWidget.load(QByteArray(svgBytes))
     dialog.show()
    def __init__(self, sysdat, parent=None, testcase=None):
        '''Setup the Lotto Settings Dialog

        :param parent:
        :param testcase:
        :return:
        '''
        super(LottoSettingsDialog, self).__init__(parent)

        def loadpath(*path):
            if not testcase:
                return (os.path.abspath(
                    os.path.join(os.path.dirname(sys.argv[0]), *path)))
            else:
                return os.path.join(*path)

        # Set up the user interface from Designer.
        self.ui = uic.loadUi(
            loadpath("pylottosimu", "dialog", "lottosystem.ui"))

        self.ui.setWindowIcon(QtGui.QIcon(loadpath("misc", "pyLottoSimu.svg")))
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(
            loadpath("pylottosimu", "lottokugel.svg"))
        self.ui.scrollArea.setWidget(self.imageLabel)

        self.systemdata = sysdat
        for systemname in self.systemdata.data:
            self.ui.combo_name.addItem(systemname['name'])
        self.ui.combo_name.currentIndexChanged.connect(self.set_values)
        self.ui.check_with_addit.clicked.connect(self.with_addit)
        self.ui.check_sep_addit_numbers.clicked.connect(self.sep_addit_numbers)

        self.set_values()
示例#7
0
    def __init__(self):
        super().__init__()

        self.setGeometry(500, 50, 1000, 1000)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(0, 0, 1000, 1000)

        if args.board is not None:
            self.chessboard = chess.Board(args.board)
        else:
            self.chessboard = chess.Board()

        self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)
        self.widgetSvg.mousePressEvent = self.onclick
        self.human_first_click = True
        self.human_move = ''

        with open(os.path.join(os.getcwd(), 'config.json'), 'r') as f:
            self.config = json.load(f)

        self.use_nn = args.nn
        self.use_database = args.database
        self.use_mcts = args.mcts
示例#8
0
 def __init__(self, parent, command_dict):
     QWidget.__init__(self, parent)
     # gets the current theme
     self.active_theme = parent.active_theme
     # gets the font
     self.custom_font = parent.custom_font
     # setting height the row
     height, width = [parent.width(), 114]
     self.resize(height, width)
     # makes command dictionary a class variable
     self.command_dict = command_dict  # Stores information about the command the row will hold
     # widget creation
     self.icon = None  # This can either be an svg or jpg file
     icon_path = command_dict["icon"]  # gets the icon path
     if "svg" in icon_path:
         self.icon = QSvgWidget(self)
         self.icon.load(icon_path)
     else:
         pixmap = QPixmap(icon_path)
         icon = QLabel(self)
         icon.setPixmap(pixmap)
         self.icon = icon
     self.title_lbl = QLabel(command_dict["title"], self)
     self.description_lbl = QLabel(command_dict["description"], self)
     self.set_style()
示例#9
0
 def __init__(self, parent, suggestion: Suggestion):
     QWidget.__init__(self, parent)
     # defines whether the command has associated options
     self.has_options = True if hasattr(suggestion,
                                        "option_suggestions") else False
     # gets the current theme
     self.active_theme = parent.active_theme
     # gets the font
     self.custom_font = parent.custom_font
     # setting height the row
     width, height = [parent.width(), 57]
     self.resize(width, height)
     # makes command dictionary a class variable
     self.suggestion = suggestion  # Stores information about the command the row will hold
     # widget creation
     self.icon = None  # This can either be an svg or jpg file
     icon_path = self.suggestion.icon_name  # gets the icon path
     if "svg" in icon_path:
         self.icon = QSvgWidget(self)
         self.icon.load(icon_path)
     else:
         pixmap = QPixmap(icon_path)
         icon = QLabel(self)
         icon.setPixmap(pixmap)
         self.icon = icon
     self.title_lbl = QLabel(self.suggestion.title, self)
     self.description_lbl = QLabel(self.suggestion.description, self)
     self.option_icon = QSvgWidget(self)
     self.option_icon.load(f"{ASSETS_DIR}svg{sep}ellipsis.svg")
     self.set_style()
示例#10
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 1100, 1100)
        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 1000, 1000)
示例#11
0
class MainWindow(QWidget):
    def draw(self, mainlineMove):
        self.i += 1
        self.chessboard.push(mainlineMove)
        self.chessboardSvg = chess.svg.board(self.chessboard).encode('UTF-8')
        self.widgetSvg.load(self.chessboardSvg)

    def __init__(self, game):

        super().__init__()
        self.i = 0
        if game == None:
            self.chessboard = chess.Board()
        else:
            self.chessboard = game.board()
            self.MOVES = [x for x in game.mainline_moves()]
            print(self.MOVES)

        self.setGeometry(100, 100, 1000, 1000)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 960, 960)

        self.button = QPushButton("Next Move")
        self.button.clicked.connect(self.draw(self.MOVES[self.i]))

        self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)
示例#12
0
    def paintEvent(self, event):
        if len(self.main_element) > 0:
            renderer = self.renderer()
            bounds = renderer.boundsOnElement(self.main_element)
            svg_dx = bounds.width()
            svg_dy = bounds.height()
            svg_ratio = svg_dy / svg_dx

            widget_dx = self.width()
            widget_dy = self.height()
            widget_ratio = widget_dy / widget_dx

            if widget_ratio > svg_ratio:
                # widget is taller than svg item so pick taller view
                height = svg_dx * widget_ratio
                extra = (height - svg_dy) / 2
                margins = QMarginsF(0, extra, 0, extra)
            elif widget_ratio < svg_ratio:
                # widget is wider than svg item so pick wider view
                width = svg_dy / widget_ratio
                extra = (width - svg_dx) / 2
                margins = QMarginsF(extra, 0, extra, 0)
            else:
                margins = QMarginsF()

            bounds = bounds.marginsAdded(margins)

            renderer.setViewBox(bounds)

        QSvgWidget.paintEvent(self, event)
示例#13
0
    def __init__(self, svg_board, **kwargs):
        super().__init__(**kwargs)
        self.svgWidget = QSvgWidget()
        layout = EvenLayout(self)
        layout.addWidget(self.svgWidget, 0, 0)

        self.press_pos = None
        self.refresh(svg_board)
    def __init__(self, parent=None):
        super(DisplayImageWidget, self).__init__(parent)

        self.image_frame = QSvgWidget()

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.image_frame)
        self.setLayout(self.layout)
示例#15
0
文件: play.py 项目: robertmrk1/chai
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 1000, 1000)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 900, 900)

        self.chessboard = chess.Board()
示例#16
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.movehistory = []
        self.game = chess.pgn.Game()

        self.setGeometry(1050, 200, 500, 500)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(0, 0, 500, 500)

        self.boardSize = min(self.widgetSvg.width(), self.widgetSvg.height())
        self.squareSize = self.boardSize / 8.0
        self.pieceToMove = [None, None]

        self.board = chess.Board()

        self.drawBoard()

    @pyqtSlot(QWidget)
    def mousePressEvent(self, event):
        if self.board.is_game_over(claim_draw=True) is False:
            if not self.board.turn:
                move = select_move(self.board, DEPTH)
                self.board.push(move)
                self.movehistory.append(move)
            elif event.x() <= self.boardSize and event.y() <= self.boardSize:
                if event.buttons() == Qt.LeftButton:
                    file = int((event.x()) / self.squareSize)
                    rank = 7 - int((event.y()) / self.squareSize)
                    square = chess.square(file, rank)
                    piece = self.board.piece_at(square)
                    coordinates = "{}{}".format(chr(file + 97), str(rank + 1))
                    if self.pieceToMove[0] is not None:
                        move = chess.Move.from_uci("{}{}".format(
                            self.pieceToMove[1], coordinates))
                        if move in self.board.legal_moves:
                            self.board.push(move)
                            self.movehistory.append(move)
                        piece = None
                        coordinates = None
                    self.pieceToMove = [piece, coordinates]
            self.drawBoard()
        else:
            self.game.add_line(self.movehistory)
            print(self.game, file=open("gameresult.pgn", "w"), end="\n\n")
            print("Game over")
            exit()

    def drawBoard(self):
        lastmove = self.board.peek() if self.board.move_stack else None
        self.boardSvg = chess.svg.board(board=self.board,
                                        lastmove=lastmove).encode("UTF-8")
        self.drawBoardSvg = self.widgetSvg.load(self.boardSvg)

        return self.boardSvg
示例#17
0
 def __init__(self, left=100, top=100, width=500, height=500):
     super().__init__()
     self.left = max(0, left)
     self.top = max(0, top)
     self.width = max(20, width)
     self.height = max(20, height)
     self.update_geometry()
     self.widgetSvg = QSvgWidget(parent=self)
     self.widgetSvg.setGeometry(10, 10, self.width - 20, self.height - 20)
示例#18
0
    def _createIconLayout(self, iconSize):
        iconLayout = QHBoxLayout()
        iconLayout.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        svgWidget = QSvgWidget(':loader.svg')
        svgWidget.setFixedSize(iconSize, iconSize)
        iconLayout.addWidget(svgWidget)

        return iconLayout
示例#19
0
    def _setupPanel(self, iconSize):
        layout = QHBoxLayout()
        layout.setAlignment(Qt.AlignHCenter)

        svgWidget = QSvgWidget(':spinnerLoader.svg')
        svgWidget.setFixedSize(iconSize, iconSize)
        layout.addWidget(svgWidget)

        self.setLayout(layout)
示例#20
0
class SourceWidget(QWidget):
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel(
            "Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")

    def createData(self, mimeType):
        if mimeType != 'image/png':
            return

        image = QImage(self.imageLabel.size(), QImage.Format_RGB32)
        painter = QPainter()
        painter.begin(image)
        self.imageLabel.renderer().render(painter)
        painter.end()

        data = QByteArray()
        buffer = QBuffer(data)
        buffer.open(QIODevice.WriteOnly)
        image.save(buffer, 'PNG')
        buffer.close()
        self.mimeData.setData('image/png', data)

    def startDrag(self):
        self.mimeData = MimeData()
        self.mimeData.dataRequested.connect(self.createData,
                                            Qt.DirectConnection)

        drag = QDrag(self)
        drag.setMimeData(self.mimeData)
        drag.setPixmap(QPixmap(':/images/drag.png'))
        drag.exec_(Qt.CopyAction)
示例#21
0
    def __init__(self, board):
        super().__init__()

        self.setGeometry(100, 100, 520, 520)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 500, 500)

        self.set_board(board)
示例#22
0
class BoardView(QWidget):
    def __init__(self, svg_board, **kwargs):
        super().__init__(**kwargs)
        self.svgWidget = QSvgWidget()
        layout = EvenLayout(self)
        layout.addWidget(self.svgWidget, 0, 0)

        self.press_pos = None
        self.refresh(svg_board)

    def refresh(self, svg_board):
        data = createQByteArray(svg_board)
        self.svgWidget.load(data)

    def mousePressEvent(self, event):
        self.press_pos = self.calculate_board_position(event)

    def mouseReleaseEvent(self, event):
        if self.press_pos:
            release_pos = self.calculate_board_position(event)
            if release_pos:
                piece = self.parent().game.get_piece_at_pos(self.press_pos)
                move = self.press_pos + release_pos

                if ((piece == 'P' and release_pos[1] == '8'
                     and self.press_pos[1] == '7'
                     and self.parent().game.board.turn)
                        or (piece == 'p' and release_pos[1] == '1'
                            and self.press_pos[1] == '2'
                            and not self.parent().game.board.turn)):
                    # Promotion
                    # TODO: player input - await, asyncio
                    move += 'q'
                elif self.press_pos == release_pos:
                    move = '0000'  # uci null move
                self.parent().execute_game_command(move)

    def mouseMoveEvent(self, event):
        # TODO: Implement drag piece-icon
        pass

    # Returns a tuple with the board position as uci and the piece at that position,
    # or None.
    def calculate_board_position(self, event):
        margin = self.svgWidget.size() * 0.05 + QSize(2, 2)
        square = (self.svgWidget.size() - 2 * margin) / 8
        offset = (self.size() - self.svgWidget.size()) / 2. + margin
        x_coordinate = event.pos().x() - offset.width()
        y_coordinate = offset.height() + 8 * square.height() - event.pos().y()
        x_pos = int(1 + x_coordinate / square.width())
        y_pos = int(1 + y_coordinate / square.height())

        if (x_pos > 8 or x_pos < 1 or y_pos > 8 or y_pos < 1):
            return None
        else:
            return 'abcdefgh'[x_pos - 1] + str(y_pos)
 def create_widget_galvanometer(self):
     """
     Создаёт свг_виджет, устанавливает стрелку прибора на 0 градусов,
     тобишь на 0 вольт
     :return: готовый к интеграции виджет
     """
     svg_widget = QSvgWidget()
     svg_bytes = bytearray(self.svg_str.format('0'), encoding='utf-8')
     svg_widget.renderer().load(svg_bytes)
     return svg_widget
    def add_usb_image(self):

        self.usb_image = QSvgWidget(parent=self)
        self.usb_image.image0 = './images/usb-0.svg'
        self.usb_image.image1 = './images/usb-1.svg'
        self.usb_image.max_height = self.h / 2
        self.grid.addWidget(self.usb_image, 1, 0, Qt.AlignHCenter)
        self.spacing_label = QLabel(parent=self)
        self.grid.addWidget(self.spacing_label, 2, 0, Qt.AlignCenter)
        self.update_usb_image()
    def get_svg_widget(self, element: Gui_Element, height: int,
                       width: int) -> QSvgWidget:

        filename = self.case[element.value]
        cwd = os.getcwd()
        directory = ""
        if sys.platform == 'win32':
            directory = strWinDirectory
        else:
            directory = strLinuxDirectory

        print(sys.platform)

        file_all = cwd + directory + filename
        # print("filename: " + cwd + strDirectory + filename)
        file = open(file_all, "r")
        data = file.read()
        strbackground = "{fill:" + '#ff9900;}'
        data = data.format(background=strbackground)
        file.close()

        svg_bytes = bytearray(data, encoding='utf-8')
        svg_widget = QSvgWidget()
        svg_widget.renderer().load(svg_bytes)
        if height > 0 and width > 0:
            size = QSize(width, height)
            svg_widget.setFixedSize(size)
        else:
            print("else")
            svg_widget.setFixedSize(svg_widget.renderer().defaultSize())

        return svg_widget
示例#26
0
class SourceWidget(QWidget):
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel("Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")

    def createData(self, mimeType):
        if mimeType != 'image/png':
            return

        image = QImage(self.imageLabel.size(), QImage.Format_RGB32)
        painter = QPainter()
        painter.begin(image)
        self.imageLabel.renderer().render(painter)
        painter.end()

        data = QByteArray()
        buffer = QBuffer(data)
        buffer.open(QIODevice.WriteOnly)
        image.save(buffer, 'PNG')
        buffer.close()
        self.mimeData.setData('image/png', data)

    def startDrag(self):
        self.mimeData = MimeData()
        self.mimeData.dataRequested.connect(self.createData, Qt.DirectConnection)

        drag = QDrag(self)
        drag.setMimeData(self.mimeData)
        drag.setPixmap(QPixmap(':/images/drag.png'))
        drag.exec_(Qt.CopyAction)
示例#27
0
    def __init__(self, text=None):
        super(SVGButton, self).__init__(text)

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

        self.svg = QSvgWidget("./assets/loading.svg", self)
        self.svg.setVisible(False)

        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.svg)
示例#28
0
    def __init__(self):
        """Initial user interface and slots

        :returns: none
        """
        super(LottoSimuDialog, self).__init__()

        # Set up the user interface from Designer.
        try:
            self.ui = uic.loadUi(
                os.path.join("pylottosimu", "lottosimu_gui.ui"))
        except FileNotFoundError:
            self.ui = uic.loadUi(
                os.path.abspath(
                    os.path.join(os.path.dirname(sys.argv[0]), "pylottosimu",
                                 "lottosimu_gui.ui")))
        self.ui.setWindowIcon(
            QtGui.QIcon(
                os.path.abspath(
                    os.path.join(os.path.dirname(sys.argv[0]), "misc",
                                 "pyLottoSimu.svg"))))

        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(
            os.path.abspath(
                os.path.join(os.path.dirname(sys.argv[0]), "pylottosimu",
                             "lottokugel.svg")))
        self.ui.scrollArea.setWidget(self.imageLabel)

        self.actionLottoSim()
        self.timer = QtCore.QTimer(self)
        self.sysdat = LottoSystemData()

        # Slots
        self.ui.btn_random_numbers.clicked.connect(self.randomNumbersGenerator)
        self.ui.clean_output_text.clicked.connect(self.cleanOutputText)
        self.ui.btn_start.clicked.connect(self.onBtnStart)
        self.ui.action_quit.triggered.connect(self.onClose)
        self.ui.action_info.triggered.connect(self.onInfo)
        self.ui.action_go_to_the_website.triggered.connect(self.openWebsite)
        self.ui.action_lotto_simulation.changed.connect(self.actionLottoSim)
        self.ui.btn_draw_overview.clicked.connect(self.onDrawOverview)
        self.timer.timeout.connect(self.onTimer)
        self.ui.statusBar().showMessage(self.tr('ready'))
        self.ui.action_lotto_system.triggered.connect(self.onSystem)
        self.ui.action_uniform_distribution.triggered.connect(
            self.draw_distribution)

        self.turn = 0
        self.random_number = 0
        self.delay_of_next_number = self.ui.horizontalSlider.value()
        self.lottodraw = DrawLotto()
        self.ui.label_numbers.setText(self.lottodraw.data['name'])
        self.ui.show()
示例#29
0
 def generateCheme(self):
     chemes = ChemeSvgGenerator(self.cheme)
     chemes.generate()
     self.shemeSvgShemeWidget = QSvgWidget("{0} {1} - Deffects.svg".format(
         self.cheme.calcNumber, self.cheme.owner))
     self.shemeSvgShemeWidget.setGeometry(500, 500, 850, 850)
     self.shemePreviewLayout.addWidget(self.shemeSvgShemeWidget)
     self.shemeSvgShemePreviewWidget = QSvgWidget(
         "{0} {1} - Cheme.svg".format(self.cheme.calcNumber,
                                      self.cheme.owner))
     self.shemeSvgShemePreviewWidget.setGeometry(500, 500, 850, 850)
     self.defectShemePreviewLayout.addWidget(self.shemeSvgShemeWidget)
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 1100, 1100)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 1080, 1080)

        self.chessboard = chess.Board()

        self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)
示例#31
0
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 850, 850)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 800, 800)

        self.board = chess.Board()  #'8/8/8/rnbqk3/ppppp3/8/PPPPP3/RNBQK3')

        self.boardSvg = chess.svg.board(self.board).encode("UTF-8")
        self.widgetSvg.load(self.boardSvg)
示例#32
0
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel("Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")
    def __init__(self, sysdat, parent=None, testcase=None):
        '''Setup the Lotto Settings Dialog

        :param parent:
        :param testcase:
        :return:
        '''
        super(LottoSettingsDialog, self).__init__(parent)

        def loadpath(*path):
            if not testcase:
                return (os.path.abspath(os.path.join(
                    os.path.dirname(sys.argv[0]), *path)))
            else:
                return os.path.join(*path)

        # Set up the user interface from Designer.
        self.ui = uic.loadUi(
            loadpath("pylottosimu", "dialog", "lottosystem.ui"))

        self.ui.setWindowIcon(
            QtGui.QIcon(loadpath("misc", "pyLottoSimu.svg")))
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(
            loadpath("pylottosimu", "lottokugel.svg"))
        self.ui.scrollArea.setWidget(self.imageLabel)

        self.systemdata = sysdat
        for systemname in self.systemdata.data:
            self.ui.combo_name.addItem(systemname['name'])
        self.ui.combo_name.currentIndexChanged.connect(self.set_values)
        self.ui.check_with_addit.clicked.connect(self.with_addit)
        self.ui.check_sep_addit_numbers.clicked.connect(self.sep_addit_numbers)

        self.set_values()
示例#34
0
    def __init__(self):
        """Initial user interface and slots

        :returns: none
        """
        super(LottoSimuDialog, self).__init__()

        # Set up the user interface from Designer.
        try:
            self.ui = uic.loadUi(os.path.join(
                "pylottosimu", "lottosimu_gui.ui"))
        except FileNotFoundError:
            self.ui = uic.loadUi(os.path.abspath(os.path.join(
                os.path.dirname(sys.argv[0]),
                "pylottosimu", "lottosimu_gui.ui")))
        self.ui.setWindowIcon(
            QtGui.QIcon(os.path.abspath(os.path.join(
                os.path.dirname(sys.argv[0]), "misc", "pyLottoSimu.svg"))))

        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(os.path.abspath(os.path.join(
            os.path.dirname(sys.argv[0]),
            "pylottosimu", "lottokugel.svg")))
        self.ui.scrollArea.setWidget(self.imageLabel)

        self.actionLottoSim()
        self.timer = QtCore.QTimer(self)
        self.sysdat = LottoSystemData()

        # Slots
        self.ui.btn_random_numbers.clicked.connect(
            self.randomNumbersGenerator)
        self.ui.clean_output_text.clicked.connect(self.cleanOutputText)
        self.ui.btn_start.clicked.connect(self.onBtnStart)
        self.ui.action_quit.triggered.connect(self.onClose)
        self.ui.action_info.triggered.connect(self.onInfo)
        self.ui.action_go_to_the_website.triggered.connect(self.openWebsite)
        self.ui.action_lotto_simulation.changed.connect(self.actionLottoSim)
        self.ui.btn_draw_overview.clicked.connect(self.onDrawOverview)
        self.timer.timeout.connect(self.onTimer)
        self.ui.statusBar().showMessage(self.tr('ready'))
        self.ui.action_lotto_system.triggered.connect(self.onSystem)
        self.ui.action_uniform_distribution.triggered.connect(
            self.draw_distribution)

        self.turn = 0
        self.random_number = 0
        self.delay_of_next_number = self.ui.horizontalSlider.value()
        self.lottodraw = DrawLotto()
        self.ui.label_numbers.setText(self.lottodraw.data['name'])
        self.ui.show()
示例#35
0
 def __init__(self, svgFile, parent=None, name=None):
     """
     Constructor
     
     @param svgFile filename of a SVG graphics file to show (string)
     @param parent parent widget of the view (QWidget)
     @param name name of the view widget (string)
     """
     super(SvgDiagram, self).__init__(parent)
     if name:
         self.setObjectName(name)
     else:
         self.setObjectName("SvgDiagram")
     self.setWindowTitle(self.tr("SVG-Viewer"))
     
     self.svgWidget = QSvgWidget()
     self.svgWidget.setObjectName("svgWidget")
     self.svgWidget.setBackgroundRole(QPalette.Base)
     self.svgWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
     
     self.svgView = QScrollArea()
     self.svgView.setObjectName("svgView")
     self.svgView.setBackgroundRole(QPalette.Dark)
     self.svgView.setWidget(self.svgWidget)
     
     self.setCentralWidget(self.svgView)
     
     self.__zoomWidget = E5ZoomWidget(
         UI.PixmapCache.getPixmap("zoomOut.png"),
         UI.PixmapCache.getPixmap("zoomIn.png"),
         UI.PixmapCache.getPixmap("zoomReset.png"), self)
     self.statusBar().addPermanentWidget(self.__zoomWidget)
     self.__zoomWidget.setMapping(
         SvgDiagram.ZoomLevels, SvgDiagram.ZoomLevelDefault)
     self.__zoomWidget.valueChanged.connect(self.__doZoom)
     
     # polish up the dialog
     self.resize(QSize(800, 600).expandedTo(self.minimumSizeHint()))
     
     self.zoom = 1.0
     self.svgFile = svgFile
     self.svgWidget.load(self.svgFile)
     self.svgWidget.resize(self.svgWidget.renderer().defaultSize())
     
     self.__initActions()
     self.__initContextMenu()
     self.__initToolBars()
     
     self.grabGesture(Qt.PinchGesture)
示例#36
0
    def ui_create(self):
        self.pathLabel.setText(self.settings.value(self.settings_prefix + '/path', self.data['path'], type=str))

        name = self.nameLabel.text()
        name = name.replace('{NAME}', self.data['name'])
        name = name.replace('{URL}', self.data['site'])

        version = self.data['version']
        if version == 'Not Found' and len(self.pathLabel.text()) > 0:
            version_ = self.data['get_version'](self.pathLabel.text())
            if len(version) > 0:
                version = version_
        self.version_pos = name.find('{VERSION}')
        name = name[:self.version_pos] + version

        self.nameLabel.setText(name)

        if self.data['icon'].endswith('.svg'):
            self.svgWidget = QSvgWidget()
            self.svgWidget.load(':' + self.data['icon'])
            self.svgWidget.setMaximumSize(QSize(24, 24))
            self.gridLayout.addWidget(self.svgWidget, 0, 0)
        else:
            self.iconLabel = QLabel()
            self.iconLabel.setPixmap(QPixmap(':' + self.data['icon']).scaled(24, 24))
            self.gridLayout.addWidget(self.iconLabel, 0, 0)

        platformText = ''
        for platform in self.data['platforms'].keys():
            platformText += '&nbsp;&nbsp;&nbsp;&nbsp;• ' + platform + ' (' + ', '.join(self.data['platforms'][platform]) + ')<br/>'

        self.platformLabel.setText(self.platformLabel.text().replace('{PLATFORMS}', platformText))

        self.gameList.insertColumn(0)
        self.gameList.insertColumn(1)
        self.gameList.insertColumn(2)
        self.gameList.insertColumn(3)
        self.gameList.insertColumn(4)
        self.gameList.setHorizontalHeaderLabels([ 'Platform', 'ID', 'Title', 'Region', 'Path' ])
        self.gameList.horizontalHeader().setStretchLastSection(True)

        self.gameList.setContextMenuPolicy(Qt.CustomContextMenu)
示例#37
0
文件: editor.py 项目: Avaren/puppy
 def add_svg(self, title, data):
     svg = QSvgWidget()
     svg.load(data)
     scrollpane = QScrollArea()
     scrollpane.setWidget(svg)
     self.tabs.addTab(scrollpane, title)
示例#38
0
 def __init__(self, parent=None):
     QSvgWidget.__init__(self, parent)
     sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
     sizePolicy.setHeightForWidth(True)
     self.setSizePolicy(sizePolicy)
示例#39
0
文件: editor.py 项目: dpgeorge/puppy
 def add_svg(self, title, data):
     editor = QSvgWidget()
     editor.load(data)
     self.tabs.addTab(editor, title)
示例#40
0
class Emulator(QWidget, ui_emulator.Ui_Emulator):
    game_found = QtCore.pyqtSignal(int, dict, str, int)
    games_loaded = QtCore.pyqtSignal()

    def __init__(self, data):
        super(Emulator, self).__init__()
        self.setupUi(self)
        self.data = data

        self.processes = { }
        self.roms = [ ]

        self.settings = QSettings('SanderTheDragon', 'Qtendo')
        self.settings_prefix = 'emulation/emulator/' + self.data['name'].lower().replace(' ', '_')

        self.config_files = self.get_config_files()

        self.settings_dialog = emulator_settings.EmulatorSettingsDialog(parent=self, data=self.data)
        self.settings_dialog.accepted.connect(lambda: self.reload_settings())
        self.settings_dialog.setWindowTitle(self.data['name'] + ' Settings')

        self.ui_create()
        self.ui_connect()

        Thread(target=self.find_games, daemon=True).start()



    def ui_create(self):
        self.pathLabel.setText(self.settings.value(self.settings_prefix + '/path', self.data['path'], type=str))

        name = self.nameLabel.text()
        name = name.replace('{NAME}', self.data['name'])
        name = name.replace('{URL}', self.data['site'])

        version = self.data['version']
        if version == 'Not Found' and len(self.pathLabel.text()) > 0:
            version_ = self.data['get_version'](self.pathLabel.text())
            if len(version) > 0:
                version = version_
        self.version_pos = name.find('{VERSION}')
        name = name[:self.version_pos] + version

        self.nameLabel.setText(name)

        if self.data['icon'].endswith('.svg'):
            self.svgWidget = QSvgWidget()
            self.svgWidget.load(':' + self.data['icon'])
            self.svgWidget.setMaximumSize(QSize(24, 24))
            self.gridLayout.addWidget(self.svgWidget, 0, 0)
        else:
            self.iconLabel = QLabel()
            self.iconLabel.setPixmap(QPixmap(':' + self.data['icon']).scaled(24, 24))
            self.gridLayout.addWidget(self.iconLabel, 0, 0)

        platformText = ''
        for platform in self.data['platforms'].keys():
            platformText += '&nbsp;&nbsp;&nbsp;&nbsp;• ' + platform + ' (' + ', '.join(self.data['platforms'][platform]) + ')<br/>'

        self.platformLabel.setText(self.platformLabel.text().replace('{PLATFORMS}', platformText))

        self.gameList.insertColumn(0)
        self.gameList.insertColumn(1)
        self.gameList.insertColumn(2)
        self.gameList.insertColumn(3)
        self.gameList.insertColumn(4)
        self.gameList.setHorizontalHeaderLabels([ 'Platform', 'ID', 'Title', 'Region', 'Path' ])
        self.gameList.horizontalHeader().setStretchLastSection(True)

        self.gameList.setContextMenuPolicy(Qt.CustomContextMenu)


    def ui_connect(self):
        self.game_found.connect(self.add_game)
        self.games_loaded.connect(self.done_loading)

        self.gameList.customContextMenuRequested.connect(lambda position: self.game_list_context_menu(position))
        self.gameList.cellDoubleClicked.connect(lambda row, column: self.launch_game(self.gameList.item(row, 4).text()))
        self.refreshButton.pressed.connect(lambda: ( self.reset_list(), Thread(target=self.find_games, daemon=True).start() ))
        self.settingsButton.pressed.connect(lambda: self.settings_dialog.exec_())
        self.filterEdit.textChanged.connect(lambda text: self.search())



    def find_games(self):
        file_types = [ ]
        for platform in self.data['platforms'].keys():
            file_types += self.data['platforms'][platform]

        logging.debug('[' + self.data['name'] + '] Searching for ( ' + ', '.join(file_types) + ' ) files')

        paths = self.settings.value('emulation/roms/paths', [ ], type=str)
        games_length = 0
        for path in paths:
            if not os.path.isdir(path):
                continue

            possible_games = utils.find_files(path, file_types)
            games_length = len(possible_games)
            logging.debug('[' + self.data['name'] + '] Found ' + str(games_length) + ' possible ROM' + ('s' if games_length != 1 else ''))
            for game in possible_games:
                index = self.gameList.rowCount()

                try:
                    rom_ = rom.Rom(game, self.data['platforms'])
                    if rom_.is_rom:
                        logging.debug('[' + self.data['name'] + '] \'' + game + '\' is a valid ROM')
                        self.roms.append(rom_)
                        info = rom_.module.get_info(game)
                        self.game_found.emit(index, info, game, games_length)
                    else:
                        logging.debug('[' + self.data['name'] + '] \'' + game + '\' is not a valid ROM')
                        games_length -= 1
                except:
                    traceback.print_exc()

        logging.debug('[' + self.data['name'] + '] Found ' + str(games_length) + ' ROM' + ('s' if games_length != 1 else ''))
        self.games_loaded.emit()


    def add_game(self, index, info, path, count):
        self.gameList.insertRow(index)

        if len(info.keys()) > 0:
            self.gameList.setItem(index, 0, QTableWidgetItem(info['platform']))
            self.gameList.setItem(index, 1, QTableWidgetItem(info['id']))
            self.gameList.setItem(index, 2, QTableWidgetItem(info['title']))
            self.gameList.setItem(index, 3, QTableWidgetItem(info['region'] + '(' + info['region_code'] + ')'))

        self.gameList.setItem(index, 4, QTableWidgetItem(path))
        self.gameList.resizeColumnsToContents()

        self.progressBar.setValue(int(100.0 / float(count) * float(index + 1)))


    def reset_list(self):
        self.refreshButton.setEnabled(False)
        self.progressBar.setValue(0)
        self.progressBar.setVisible(True)
        self.gameList.setSortingEnabled(False)
        self.gameList.setRowCount(0)
        self.roms.clear()


    def done_loading(self):
        self.gameList.setSortingEnabled(True)
        self.gameList.sortItems(1)
        self.progressBar.setVisible(False)
        self.refreshButton.setEnabled(True)
        self.search()


    def launch_game(self, path):
        if path in self.processes:
            return

        command = self.settings.value(self.settings_prefix + '/command', '{EXEC} {ARGS} {ROM}', type=str)
        command = command.replace('{EXEC}', self.settings.value(self.settings_prefix + '/path', self.data['path'], type=str))
        command = command.replace('{ARGS}', ' '.join(self.data['arguments']))
        command = command.replace('{ROM}', shlex.quote(path))
        logging.info('[' + self.data['name'] + '] Launching: `' + command + '`')

        process = QProcess(self)
        process.finished.connect(functools.partial(self.end_game, path))

        if self.settings.value('emulation/log/stdout', True, type=bool):
            process.readyReadStandardOutput.connect(functools.partial(lambda path: self.log_game(path, bytes(self.processes[path].readAllStandardOutput()).decode('utf-8')), path))

        if self.settings.value('emulation/log/stderr', True, type=bool):
            process.readyReadStandardError.connect(functools.partial(lambda path: self.log_game(path, bytes(self.processes[path].readAllStandardError()).decode('utf-8'), logging.error), path))
            process.errorOccurred.connect(functools.partial(lambda path, error: self.log_game(path, str(error), logging.error), path))

        args = shlex.split(command)
        self.processes[path] = process
        self.processes[path].start(args[0], args[1:])


    def log_game(self, path, message, method=logging.info):
        if '\n' in message:
            for line in message.split('\n'):
                self.log_game(path, line, method)
        else:
            message = utils.ansi_trim(message.strip())
            if len(message) == 0:
                return

            method('[' + self.data['name'] + ':' + path[path.rfind('/') + 1:] + '] ' + message)


    def end_game(self, path, code, status):
        if code == 0:
            logging.info('[' + self.data['name'] + '] Process for \'' + path + '\' exited')
        else:
            logging.error('[' + self.data['name'] + '] Process for \'' + path + '\' exited with non-zero code: ' + str(code))

        del self.processes[path]


    def reload_settings(self):
        self.pathLabel.setText(self.settings.value(self.settings_prefix + '/path', self.data['path'], type=str))

        name = self.nameLabel.text()
        version = self.data['get_version'](self.pathLabel.text())
        if len(version) > 0:
            name = name[:self.version_pos] + version
        self.nameLabel.setText(name)

        self.data['reload_settings']()


    def game_list_context_menu(self, position):
        menu = QMenu()
        launchAction = menu.addAction("Launch")
        menu.addSeparator()

        action = menu.exec_(self.gameList.mapToGlobal(position))

        if action == launchAction:
             self.launch_game(self.gameList.item(self.gameList.selectionModel().selectedRows()[0].row(), 4).text())


    def search(self):
        text = self.filterEdit.text()
        for i in range(self.gameList.rowCount()):
            if text.lower() in self.gameList.item(i, 2).text().lower():
                self.gameList.showRow(i)
            else:
                self.gameList.hideRow(i)
class LottoSettingsDialog(QtWidgets.QDialog):
    """The GUI of Settings.

    :param sysdat: Lotto setting
    :type sysdat: string
    :param parent: parent window
    :type parent: string
    """
    def __init__(self, sysdat, parent=None, testcase=None):
        '''Setup the Lotto Settings Dialog

        :param parent:
        :param testcase:
        :return:
        '''
        super(LottoSettingsDialog, self).__init__(parent)

        def loadpath(*path):
            if not testcase:
                return (os.path.abspath(os.path.join(
                    os.path.dirname(sys.argv[0]), *path)))
            else:
                return os.path.join(*path)

        # Set up the user interface from Designer.
        self.ui = uic.loadUi(
            loadpath("pylottosimu", "dialog", "lottosystem.ui"))

        self.ui.setWindowIcon(
            QtGui.QIcon(loadpath("misc", "pyLottoSimu.svg")))
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(
            loadpath("pylottosimu", "lottokugel.svg"))
        self.ui.scrollArea.setWidget(self.imageLabel)

        self.systemdata = sysdat
        for systemname in self.systemdata.data:
            self.ui.combo_name.addItem(systemname['name'])
        self.ui.combo_name.currentIndexChanged.connect(self.set_values)
        self.ui.check_with_addit.clicked.connect(self.with_addit)
        self.ui.check_sep_addit_numbers.clicked.connect(self.sep_addit_numbers)

        self.set_values()

    def sep_addit_numbers(self):
        """if the checkbox with separate additional numbers is active
        then enable to set the number

        :return:
        """
        check = self.ui.check_sep_addit_numbers.isChecked()
        self.ui.label_max_addit.setEnabled(check)
        self.ui.spinBox_max_addit.setEnabled(check)

    def with_addit(self):
        """if the checkbox with additional numbers is active
        then enable to set the number

        :return:
        """
        check = self.ui.check_with_addit.isChecked()
        self.ui.spinBox_addit_numbers.setEnabled(check)
        self.ui.label_addit_numbers.setEnabled(check)
        self.ui.label_sep_addit_numbers.setEnabled(check)
        self.ui.check_sep_addit_numbers.setEnabled(check)
        if check is not True:
            self.ui.check_sep_addit_numbers.setChecked(False)
        self.sep_addit_numbers()

    def set_values(self):
        """Set Values

        :return:
        """
        index = self.ui.combo_name.currentIndex()
        self.ui.spinBox_max_draw.setValue(
            self.systemdata.data[index]['max_draw'])
        self.ui.spinBox_draw_numbers.setValue(
            self.systemdata.data[index]['draw_numbers'])
        self.ui.check_with_addit.setChecked(
            self.systemdata.data[index]['with_addition'])
        self.ui.spinBox_addit_numbers.setValue(
            self.systemdata.data[index]['addition_numbers'])
        self.ui.check_sep_addit_numbers.setChecked(
            self.systemdata.data[index]['sep_addition_numbers'])
        self.ui.spinBox_max_addit.setValue(
            self.systemdata.data[index]['max_addition'])
        self.ui.edit_name_addition.setText(
            self.systemdata.data[index]['name_addition'])
        self.with_addit()

    def values(self):
        """Values

        :return:
        """
        return (str(self.ui.combo_name.currentText()),
                self.ui.spinBox_max_draw.valueFromText(
                    self.ui.spinBox_max_draw.text()),
                self.ui.spinBox_draw_numbers.valueFromText(
                    self.ui.spinBox_draw_numbers.text()),
                self.ui.check_with_addit.isChecked(),
                self.ui.spinBox_addit_numbers.valueFromText(
                    self.ui.spinBox_addit_numbers.text()),
                self.ui.check_sep_addit_numbers.isChecked(),
                self.ui.spinBox_max_addit.valueFromText(
                    self.ui.spinBox_max_addit.text()),
                self.ui.edit_name_addition.text())

    @staticmethod
    def get_values(sysdat, parent=None):
        """static method to create the dialog and return
        (dialog.values, accepted)

        :param sysdat: Lotto setting
        :type sysdat: string
        :returns: dialog.values, accepted
        :rtype: array of int, bool
        """
        dialog = LottoSettingsDialog(sysdat, parent)
        result = dialog.ui.exec_()
        return (dialog.values(), result == QtWidgets.QDialog.Accepted)
示例#42
0
class SvgDiagram(E5MainWindow):
    """
    Class implementing a dialog showing a SVG graphic.
    """
    ZoomLevels = [
        1, 3, 5, 7, 9,
        10, 20, 30, 50, 67, 80, 90,
        100,
        110, 120, 133, 150, 170, 200, 240, 300, 400,
        500, 600, 700, 800, 900, 1000,
    ]
    ZoomLevelDefault = 100
    
    def __init__(self, svgFile, parent=None, name=None):
        """
        Constructor
        
        @param svgFile filename of a SVG graphics file to show (string)
        @param parent parent widget of the view (QWidget)
        @param name name of the view widget (string)
        """
        super(SvgDiagram, self).__init__(parent)
        if name:
            self.setObjectName(name)
        else:
            self.setObjectName("SvgDiagram")
        self.setWindowTitle(self.tr("SVG-Viewer"))
        
        self.svgWidget = QSvgWidget()
        self.svgWidget.setObjectName("svgWidget")
        self.svgWidget.setBackgroundRole(QPalette.Base)
        self.svgWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        
        self.svgView = QScrollArea()
        self.svgView.setObjectName("svgView")
        self.svgView.setBackgroundRole(QPalette.Dark)
        self.svgView.setWidget(self.svgWidget)
        
        self.setCentralWidget(self.svgView)
        
        self.__zoomWidget = E5ZoomWidget(
            UI.PixmapCache.getPixmap("zoomOut.png"),
            UI.PixmapCache.getPixmap("zoomIn.png"),
            UI.PixmapCache.getPixmap("zoomReset.png"), self)
        self.statusBar().addPermanentWidget(self.__zoomWidget)
        self.__zoomWidget.setMapping(
            SvgDiagram.ZoomLevels, SvgDiagram.ZoomLevelDefault)
        self.__zoomWidget.valueChanged.connect(self.__doZoom)
        
        # polish up the dialog
        self.resize(QSize(800, 600).expandedTo(self.minimumSizeHint()))
        
        self.zoom = 1.0
        self.svgFile = svgFile
        self.svgWidget.load(self.svgFile)
        self.svgWidget.resize(self.svgWidget.renderer().defaultSize())
        
        self.__initActions()
        self.__initContextMenu()
        self.__initToolBars()
        
        self.grabGesture(Qt.PinchGesture)
        
    def __initActions(self):
        """
        Private method to initialize the view actions.
        """
        self.closeAct = \
            QAction(UI.PixmapCache.getIcon("close.png"),
                    self.tr("Close"), self)
        self.closeAct.triggered.connect(self.close)
        
        self.printAct = \
            QAction(UI.PixmapCache.getIcon("print.png"),
                    self.tr("Print"), self)
        self.printAct.triggered.connect(self.__printDiagram)
        
        self.printPreviewAct = \
            QAction(UI.PixmapCache.getIcon("printPreview.png"),
                    self.tr("Print Preview"), self)
        self.printPreviewAct.triggered.connect(self.__printPreviewDiagram)
        
    def __initContextMenu(self):
        """
        Private method to initialize the context menu.
        """
        self.__menu = QMenu(self)
        self.__menu.addAction(self.closeAct)
        self.__menu.addSeparator()
        self.__menu.addAction(self.printPreviewAct)
        self.__menu.addAction(self.printAct)
        
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__showContextMenu)
        
    def __showContextMenu(self, coord):
        """
        Private slot to show the context menu of the listview.
        
        @param coord the position of the mouse pointer (QPoint)
        """
        self.__menu.popup(self.mapToGlobal(coord))
        
    def __initToolBars(self):
        """
        Private method to populate the toolbars with our actions.
        """
        self.windowToolBar = QToolBar(self.tr("Window"), self)
        self.windowToolBar.setIconSize(UI.Config.ToolBarIconSize)
        self.windowToolBar.addAction(self.closeAct)
        
        self.graphicsToolBar = QToolBar(self.tr("Graphics"), self)
        self.graphicsToolBar.setIconSize(UI.Config.ToolBarIconSize)
        self.graphicsToolBar.addAction(self.printPreviewAct)
        self.graphicsToolBar.addAction(self.printAct)
        
        self.addToolBar(Qt.TopToolBarArea, self.windowToolBar)
        self.addToolBar(Qt.TopToolBarArea, self.graphicsToolBar)
        
    def getDiagramName(self):
        """
        Public method to retrieve a name for the diagram.
        
        @return name for the diagram
        """
        return self.svgFile
    
    def wheelEvent(self, evt):
        """
        Protected method to handle wheel events.
        
        @param evt reference to the wheel event (QWheelEvent)
        """
        if evt.modifiers() & Qt.ControlModifier:
            if qVersion() >= "5.0.0":
                delta = evt.angleDelta().y()
            else:
                delta = evt.delta()
            if delta < 0:
                self.__zoomOut()
            else:
                self.__zoomIn()
            evt.accept()
            return
        
        super(SvgDiagram, self).wheelEvent(evt)
    
    def event(self, evt):
        """
        Public method handling events.
        
        @param evt reference to the event (QEvent)
        @return flag indicating, if the event was handled (boolean)
        """
        if evt.type() == QEvent.Gesture:
            self.gestureEvent(evt)
            return True
        
        return super(SvgDiagram, self).event(evt)
    
    def gestureEvent(self, evt):
        """
        Protected method handling gesture events.
        
        @param evt reference to the gesture event (QGestureEvent
        """
        pinch = evt.gesture(Qt.PinchGesture)
        if pinch:
            if pinch.state() == Qt.GestureStarted:
                pinch.setScaleFactor(self.__zoom() / 100)
            else:
                self.__doZoom(int(pinch.scaleFactor() * 100))
            evt.accept()
    
    ###########################################################################
    ## Private menu handling methods below.
    ###########################################################################
    
    def __adjustScrollBar(self, scrollBar, factor):
        """
        Private method to adjust a scrollbar by a certain factor.
        
        @param scrollBar reference to the scrollbar object (QScrollBar)
        @param factor factor to adjust by (float)
        """
        scrollBar.setValue(
            int(factor * scrollBar.value() +
                ((factor - 1) * scrollBar.pageStep() / 2)))
        
    def __levelForZoom(self, zoom):
        """
        Private method determining the zoom level index given a zoom factor.
        
        @param zoom zoom factor (integer)
        @return index of zoom factor (integer)
        """
        try:
            index = SvgDiagram.ZoomLevels.index(zoom)
        except ValueError:
            for index in range(len(SvgDiagram.ZoomLevels)):
                if zoom <= SvgDiagram.ZoomLevels[index]:
                    break
        return index
    
    def __doZoom(self, value):
        """
        Private method to set the zoom value in percent.
        
        @param value zoom value in percent (integer)
        """
        oldValue = self.__zoom()
        if value != oldValue:
            self.svgWidget.resize(value / 100 * self.svgWidget.sizeHint())
            
            factor = value / oldValue
            self.__adjustScrollBar(self.svgView.horizontalScrollBar(), factor)
            self.__adjustScrollBar(self.svgView.verticalScrollBar(), factor)
            
            self.__zoomWidget.setValue(value)
        
    def __zoomIn(self):
        """
        Private method to zoom into the SVG.
        """
        index = self.__levelForZoom(self.__zoom())
        if index < len(SvgDiagram.ZoomLevels) - 1:
            self.__doZoom(SvgDiagram.ZoomLevels[index + 1])
        
    def __zoomOut(self):
        """
        Private method to zoom out of the SVG.
        """
        index = self.__levelForZoom(self.__zoom())
        if index > 0:
            self.__doZoom(SvgDiagram.ZoomLevels[index - 1])
        
    def __zoomReset(self):
        """
        Private method to reset the zoom value.
        """
        self.__doZoom(SvgDiagram.ZoomLevels[SvgDiagram.ZoomLevelDefault])
        
    def __zoom(self):
        """
        Private method to get the current zoom factor in percent.
        
        @return current zoom factor in percent (integer)
        """
        return int(self.svgWidget.width() /
                   self.svgWidget.sizeHint().width() * 100.0)
        
    def __printDiagram(self):
        """
        Private slot called to print the diagram.
        """
        printer = QPrinter(mode=QPrinter.ScreenResolution)
        printer.setFullPage(True)
        if Preferences.getPrinter("ColorMode"):
            printer.setColorMode(QPrinter.Color)
        else:
            printer.setColorMode(QPrinter.GrayScale)
        if Preferences.getPrinter("FirstPageFirst"):
            printer.setPageOrder(QPrinter.FirstPageFirst)
        else:
            printer.setPageOrder(QPrinter.LastPageFirst)
        printerName = Preferences.getPrinter("PrinterName")
        if printerName:
            printer.setPrinterName(printerName)
        
        printDialog = QPrintDialog(printer, self)
        if printDialog.exec_():
            self.__print(printer)
        
    def __printPreviewDiagram(self):
        """
        Private slot called to show a print preview of the diagram.
        """
        from PyQt5.QtPrintSupport import QPrintPreviewDialog
        
        printer = QPrinter(mode=QPrinter.ScreenResolution)
        printer.setFullPage(True)
        if Preferences.getPrinter("ColorMode"):
            printer.setColorMode(QPrinter.Color)
        else:
            printer.setColorMode(QPrinter.GrayScale)
        if Preferences.getPrinter("FirstPageFirst"):
            printer.setPageOrder(QPrinter.FirstPageFirst)
        else:
            printer.setPageOrder(QPrinter.LastPageFirst)
        printer.setPageMargins(
            Preferences.getPrinter("LeftMargin") * 10,
            Preferences.getPrinter("TopMargin") * 10,
            Preferences.getPrinter("RightMargin") * 10,
            Preferences.getPrinter("BottomMargin") * 10,
            QPrinter.Millimeter
        )
        printerName = Preferences.getPrinter("PrinterName")
        if printerName:
            printer.setPrinterName(printerName)
        
        preview = QPrintPreviewDialog(printer, self)
        preview.paintRequested[QPrinter].connect(self.__print)
        preview.exec_()
        
    def __print(self, printer):
        """
        Private slot to the actual printing.
        
        @param printer reference to the printer object (QPrinter)
        """
        painter = QPainter()
        painter.begin(printer)

        # calculate margin and width of printout
        font = QFont("times", 10)
        painter.setFont(font)
        fm = painter.fontMetrics()
        fontHeight = fm.lineSpacing()
        marginX = printer.pageRect().x() - printer.paperRect().x()
        marginX = Preferences.getPrinter("LeftMargin") * \
            int(printer.resolution() / 2.54) - marginX
        marginY = printer.pageRect().y() - printer.paperRect().y()
        marginY = Preferences.getPrinter("TopMargin") * \
            int(printer.resolution() / 2.54) - marginY

        width = printer.width() - marginX - \
            Preferences.getPrinter("RightMargin") * \
            int(printer.resolution() / 2.54)
        height = printer.height() - fontHeight - 4 - marginY - \
            Preferences.getPrinter("BottomMargin") * \
            int(printer.resolution() / 2.54)

        # write a foot note
        s = self.tr("Diagram: {0}").format(self.getDiagramName())
        tc = QColor(50, 50, 50)
        painter.setPen(tc)
        painter.drawRect(marginX, marginY, width, height)
        painter.drawLine(marginX, marginY + height + 2,
                         marginX + width, marginY + height + 2)
        painter.setFont(font)
        painter.drawText(marginX, marginY + height + 4, width,
                         fontHeight, Qt.AlignRight, s)

        # render the diagram
        painter.setViewport(marginX, marginY, width, height)
        self.svgWidget.renderer().render(painter)
        painter.end()
示例#43
0
class LottoSimuDialog(QtWidgets.QMainWindow):
    """The GUI and program of the pyLottoSimu.
    """
    def __init__(self):
        """Initial user interface and slots

        :returns: none
        """
        super(LottoSimuDialog, self).__init__()

        # Set up the user interface from Designer.
        self.ui = qt_loadui(os.path.abspath(os.path.join(
                           os.path.dirname(sys.argv[0]),
                           "pylottosimu", "lottosimu_gui.ui")))
        self.ui.setWindowIcon(
            QtGui.QIcon(os.path.abspath(os.path.join(
                os.path.dirname(sys.argv[0]), "misc", "pyLottoSimu.svg"))))

        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(os.path.abspath(os.path.join(
            os.path.dirname(sys.argv[0]),
            "pylottosimu", "lottokugel.svg")))
        self.ui.scrollArea.setWidget(self.imageLabel)

        self.action_lottosim()
        self.timer = QtCore.QTimer(self)
        self.sysdat = LottoSystemData()

        # Slots
        self.ui.btn_random_numbers.clicked.connect(
            self.onrandom_numbers_generator)
        self.ui.clean_output_text.clicked.connect(self.onclean_output_text)
        self.ui.btn_start.clicked.connect(self.onbtn_start)
        self.ui.action_quit.triggered.connect(self.onclose)
        self.ui.action_info.triggered.connect(self.oninfo)
        self.ui.action_go_to_the_website.triggered.connect(self.onwebsite)
        self.ui.action_lotto_simulation.changed.connect(self.action_lottosim)
        self.ui.btn_draw_overview.clicked.connect(self.onbtn_draw_overview)
        self.timer.timeout.connect(self.ontimer)
        self.ui.statusBar().showMessage(self.tr('ready'))
        self.ui.actionLotto_system.triggered.connect(self.onsystem)

        self.turn = 0
        self.random_number = 0
        self.LastTextnumber = -1
        self.delay_of_next_number = self.ui.horizontalSlider.value()
        self.lottodraw = DrawLotto()
        self.ui.label_numbers.setText(self.lottodraw.data['name'])
        self.ui.show()

    def ontimer(self):
        """Start time to show a number.

        :returns: none
        """
        self.timer.stop()
        verz = self.ui.horizontalSlider.value()
        if self.delay_of_next_number >= verz:
            self.delay_of_next_number = verz
        self.delay_of_next_number -= 1
        if (self.delay_of_next_number < 10 or
                (self.delay_of_next_number < 17 and
                    (self.delay_of_next_number % 2) == 0) or
                (self.delay_of_next_number < 25 and
                    (self.delay_of_next_number % 3) == 0) or
                (self.delay_of_next_number % 4) == 0):
            self.ui.label_big_number.setText(str(
                random.sample(range(1, int(
                    self.lottodraw.data['max_draw']) + 1), 1)[0]))
        self.timer.start(100)
        if self.delay_of_next_number < 0:
            self.show_next_number()
            self.delay_of_next_number = verz

    def show_next_number(self):
        """Simulation of the draw and show the next Number on the Screen.

        :returns: none
        """
        if self.turn == 0:
            self.ui.btn_draw_overview.setVisible(False)
            self.LastTextnumber = -1

        if self.turn >= len((self.lottodraw.random_number +
                             self.lottodraw.random_addit)):
            self.timer.stop()
            if self.ui.rdbtn_show_draw_after.isChecked():
                self.onbtn_draw_overview()
            self.ui.btn_draw_overview.setVisible(True)
        else:
            self.ui.label_last_draw_number.setText(str((
                self.lottodraw.random_number +
                self.lottodraw.random_addit)[self.turn]))
            self.ui.label_big_number.setText(str((
                self.lottodraw.random_number +
                self.lottodraw.random_addit)[self.turn]))

        self.ui.plaintextedit.appendPlainText(self.lottodraw.picknumber(
            self.turn))

        self.turn += 1

    def onbtn_draw_overview(self):
        """show dialog of the draw

        :returns: none
        """
        separetebonus = False
        if self.lottodraw.data['sep_addit_numbers']:
            separetebonus = self.lottodraw.data['max_addit']

        dlgdraw = DlgShowDrawing(self.lottodraw.ballnumber,
                                 self.lottodraw.data['max_draw'],
                                 self.lottodraw.ballbonus,
                                 highestbonus=separetebonus
                                 )
        dlgdraw.exec_()

    def onsystem(self):
        """show dialog of the draw

        :returns: none
        """
        system = LottoSettingsDialog.get_values(self.sysdat)

        if system[1]:
            self.lottodraw.data['name'] = system[0][0]
            self.lottodraw.data['max_draw'] = system[0][1]
            self.lottodraw.data['draw_numbers'] = system[0][2]
            self.lottodraw.data['with_addit'] = system[0][3]
            self.lottodraw.data['addit_numbers'] = system[0][4]
            self.lottodraw.data['sep_addit_numbers'] = system[0][5]
            self.lottodraw.data['max_addit'] = system[0][6]

        self.ui.label_numbers.setText(self.lottodraw.data['name'])
        self.ui.btn_draw_overview.setVisible(False)

    def onbtn_start(self):
        """Start simulation with the first drawing
        init timer with the valve from the Scrollbar
        the next drawing starts with the timer event.

        :returns: none
        """
        self.ui.label_last_draw_number.setText("")
        self.turn = 0
        self.lottodraw.draw()
        self.ui.plaintextedit.setPlainText(self.lottodraw.picknumber(-1))
        self.timer.start(100)
        self.delay_of_next_number = self.ui.horizontalSlider.value()

    def action_lottosim(self):
        """Changing the layout for simulation or generation
        and change the visible of the buttons.

        :returns: none
        """
        self.ui.plaintextedit.setPlainText("")
        if self.ui.action_lotto_simulation.isChecked():
            # lotto simulation
            self.ui.statusBar().showMessage(self.tr('lotto simulation'))
            self.ui.plaintextedit.setGeometry(QtCore.QRect(20, 180, 441, 136))
            self.ui.btn_random_numbers.setVisible(False)
            self.ui.clean_output_text.setVisible(False)
            self.ui.label_Lottozahlen.setVisible(False)
            self.ui.label_big_number.setVisible(True)
            self.ui.label_last_draw_number.setVisible(True)
            self.ui.label_speed.setVisible(True)
            self.ui.label_big_number.setText("")
            self.ui.label_last_draw_number.setText("")
            self.ui.btn_start.setVisible(True)
            self.ui.horizontalSlider.setVisible(True)
            self.ui.btn_draw_overview.setVisible(False)
            self.ui.rdbtn_show_draw_after.setVisible(True)

        else:
            # random numbers
            self.ui.statusBar().showMessage(self.tr('random numbers'))
            self.ui.plaintextedit.setGeometry(QtCore.QRect(20, 20, 441, 111))
            self.ui.btn_random_numbers.setVisible(True)
            self.ui.clean_output_text.setVisible(True)
            self.ui.label_Lottozahlen.setVisible(True)
            self.ui.label_big_number.setVisible(False)
            self.ui.label_last_draw_number.setVisible(False)
            self.ui.label_speed.setVisible(False)
            self.ui.btn_start.setVisible(False)
            self.ui.horizontalSlider.setVisible(False)
            self.ui.btn_draw_overview.setVisible(False)
            self.ui.rdbtn_show_draw_after.setVisible(False)
            self.timer.stop()

    def onrandom_numbers_generator(self):
        """Show the output from the random number generator.

        :returns: none
        """
        self.lottodraw.draw()
        if self.lottodraw.random_number:
            text = "".join(map(" {0:02d}".format, sorted(
                self.lottodraw.random_number)))
        else:
            text = self.tr("Error, no valid numbers available!")
        dt = datetime.now()
        texttr = self.tr("{} {} out of {}: {}")
        text = str(texttr).format(dt.strftime("%H:%M:%S:"),
                                  self.lottodraw.data['draw_numbers'],
                                  self.lottodraw.data['max_draw'], text)
        self.ui.plaintextedit.appendPlainText(text)

    def onclean_output_text(self):
        """Clean the output text

        :returns: none
        """
        self.ui.plaintextedit.setPlainText("")

    def oninfo(self):
        """Set the text for the info message box in html format

        :returns: none
        """
        infobox = QtWidgets.QMessageBox()
        infobox.setWindowTitle(self.tr('Info'))
        infobox.setText(self.tr(
            'The simulation of a lottery draw based on an idea of '
            '<a href="http://www.m-i-u.de/">my-image-upload.de</a>,<br><br>'
            'pyLottoSimu is free software and use GNU General Public License '
            '<a href="http://www.gnu.org/licenses/">www.gnu.org/licenses</a>'))
        infobox.setInformativeText(self.tr(
            'More Information about the program at '
            '<a href="http://pylottosimu.readthedocs.io">'
            'pylottosimu.readthedocs.io</a>'))
        infobox.exec_()

    @staticmethod
    def onwebsite():
        """Open website

        :returns: none
        """
        webbrowser.open_new_tab(
            "http://pylottosimu.readthedocs.io")

    def onclose(self):
        """Close the GUI

        :returns: none"""
        self.ui.close()