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
Exemplo n.º 2
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)
 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
Exemplo n.º 4
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)
class DisplayImageWidget(QWidget):
    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)

    def update_image(self, svg_img):
        svg_bytes = bytearray(svg_img, encoding='utf-8')
        self.image_frame.renderer().load(svg_bytes)
Exemplo n.º 6
0
def init_board_window():
    def reload_svg():

        svg_bytes = bytearray(board_picture, encoding='utf-8')
        svgWidget.renderer().load(svg_bytes)
        svgWidget.update()

    svg_bytes = bytearray(board_picture, encoding='utf-8')
    app = QApplication(sys.argv)
    svgWidget = QSvgWidget()
    svgWidget.renderer().load(svg_bytes)
    svgWidget.setGeometry(200, 5, 440, 440)
    svgWidget.show()
    timer = QtCore.QTimer()
    timer.timeout.connect(lambda: reload_svg())
    timer.start(500)
    sys.exit(app.exec_())
Exemplo n.º 7
0
class WindowSvg(QWidget):
    def __init__(self, parent=None):
        super().__init__()

        image = QFile('foundry.svg')
        image.open(QIODevice.ReadOnly)
        self.data = image.readAll()
        image.close()

        area = QScrollArea()
        self.label = QSvgWidget()
        self.label.renderer().load(self.data)
        area.setWidget(self.label)

        layout = QVBoxLayout()
        layout.addWidget(area)
        self.setLayout(layout)
        self.setWindowTitle("SVG")
Exemplo n.º 8
0
 def on_click(self):
     svg = QSvgWidget()
     svg.renderer().load(self.trace())
     svg.setWindowTitle("SVG Picture")
     svg.show()
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)
Exemplo n.º 10
0
class ScalableDial(QDial):
    # enum CustomPaintMode
    CUSTOM_PAINT_MODE_NULL = 0  # default (NOTE: only this mode has label gradient)
    CUSTOM_PAINT_MODE_CARLA_WET = 1  # color blue-green gradient (reserved #3)
    CUSTOM_PAINT_MODE_CARLA_VOL = 2  # color blue (reserved #3)
    CUSTOM_PAINT_MODE_CARLA_L = 3  # color yellow (reserved #4)
    CUSTOM_PAINT_MODE_CARLA_R = 4  # color yellow (reserved #4)
    CUSTOM_PAINT_MODE_CARLA_PAN = 5  # color yellow (reserved #3)
    CUSTOM_PAINT_MODE_COLOR = 6  # color, selectable (reserved #3)
    CUSTOM_PAINT_MODE_ZITA = 7  # custom zita knob (reserved #6)
    CUSTOM_PAINT_MODE_NO_GRADIENT = 8  # skip label gradient

    # enum Orientation
    HORIZONTAL = 0
    VERTICAL = 1

    HOVER_MIN = 0
    HOVER_MAX = 9

    MODE_DEFAULT = 0
    MODE_LINEAR = 1

    # signals
    dragStateChanged = pyqtSignal(bool)
    realValueChanged = pyqtSignal(float)

    def __init__(self, parent, index=0):
        QDial.__init__(self, parent)

        self.fDialMode = self.MODE_LINEAR

        self.fMinimum = 0.0
        self.fMaximum = 1.0
        self.fRealValue = 0.0
        self.fPrecision = 10000
        self.fIsInteger = False

        self.fIsHovered = False
        self.fIsPressed = False
        self.fHoverStep = self.HOVER_MIN

        self.fLastDragPos = None
        self.fLastDragValue = 0.0

        self.fIndex = index
        self.fImage = QSvgWidget(":/scalable/dial_03.svg")
        self.fImageNum = "01"

        if self.fImage.sizeHint().width() > self.fImage.sizeHint().height():
            self.fImageOrientation = self.HORIZONTAL
        else:
            self.fImageOrientation = self.VERTICAL

        self.fLabel = ""
        self.fLabelPos = QPointF(0.0, 0.0)
        self.fLabelFont = QFont(self.font())
        self.fLabelFont.setPixelSize(8)
        self.fLabelWidth = 0
        self.fLabelHeight = 0

        if self.palette().window().color().lightness() > 100:
            # Light background
            c = self.palette().dark().color()
            self.fLabelGradientColor1 = c
            self.fLabelGradientColor2 = QColor(c.red(), c.green(), c.blue(), 0)
            self.fLabelGradientColorT = [
                self.palette().buttonText().color(),
                self.palette().mid().color()
            ]
        else:
            # Dark background
            self.fLabelGradientColor1 = QColor(0, 0, 0, 255)
            self.fLabelGradientColor2 = QColor(0, 0, 0, 0)
            self.fLabelGradientColorT = [Qt.white, Qt.darkGray]

        self.fLabelGradient = QLinearGradient(0, 0, 0, 1)
        self.fLabelGradient.setColorAt(0.0, self.fLabelGradientColor1)
        self.fLabelGradient.setColorAt(0.6, self.fLabelGradientColor1)
        self.fLabelGradient.setColorAt(1.0, self.fLabelGradientColor2)

        self.fLabelGradientRect = QRectF(0.0, 0.0, 0.0, 0.0)

        self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_NULL
        self.fCustomPaintColor = QColor(0xff, 0xff, 0xff)

        self.updateSizes()

        # Fake internal value, custom precision
        QDial.setMinimum(self, 0)
        QDial.setMaximum(self, self.fPrecision)
        QDial.setValue(self, 0)

        self.valueChanged.connect(self.slot_valueChanged)

    def getIndex(self):
        return self.fIndex

    def getBaseSize(self):
        return self.fImageBaseSize

    def forceWhiteLabelGradientText(self):
        self.fLabelGradientColor1 = QColor(0, 0, 0, 255)
        self.fLabelGradientColor2 = QColor(0, 0, 0, 0)
        self.fLabelGradientColorT = [Qt.white, Qt.darkGray]

    def setLabelColor(self, enabled, disabled):
        self.fLabelGradientColor1 = QColor(0, 0, 0, 255)
        self.fLabelGradientColor2 = QColor(0, 0, 0, 0)
        self.fLabelGradientColorT = [enabled, disabled]

    def updateSizes(self):
        if isinstance(self.fImage, QPixmap):
            self.fImageWidth = self.fImage.width()
            self.fImageHeight = self.fImage.height()
        else:
            self.fImageWidth = self.fImage.sizeHint().width()
            self.fImageHeight = self.fImage.sizeHint().height()

        if self.fImageWidth < 1:
            self.fImageWidth = 1

        if self.fImageHeight < 1:
            self.fImageHeight = 1

        if self.fImageOrientation == self.HORIZONTAL:
            self.fImageBaseSize = self.fImageHeight
            self.fImageLayersCount = self.fImageWidth / self.fImageHeight
        else:
            self.fImageBaseSize = self.fImageWidth
            self.fImageLayersCount = self.fImageHeight / self.fImageWidth

        self.setMinimumSize(self.fImageBaseSize,
                            self.fImageBaseSize + self.fLabelHeight + 5)
        self.setMaximumSize(self.fImageBaseSize,
                            self.fImageBaseSize + self.fLabelHeight + 5)

        if not self.fLabel:
            self.fLabelHeight = 0
            self.fLabelWidth = 0
            return

        self.fLabelWidth = QFontMetrics(self.fLabelFont).width(self.fLabel)
        self.fLabelHeight = QFontMetrics(self.fLabelFont).height()

        self.fLabelPos.setX(
            float(self.fImageBaseSize) / 2.0 - float(self.fLabelWidth) / 2.0)

        if self.fImageNum in ("01", "02", "07", "08", "09", "10"):
            self.fLabelPos.setY(self.fImageBaseSize + self.fLabelHeight)
        elif self.fImageNum in ("11", ):
            self.fLabelPos.setY(self.fImageBaseSize +
                                self.fLabelHeight * 2 / 3)
        else:
            self.fLabelPos.setY(self.fImageBaseSize + self.fLabelHeight / 2)

        self.fLabelGradient.setStart(0, float(self.fImageBaseSize) / 2.0)
        self.fLabelGradient.setFinalStop(
            0, self.fImageBaseSize + self.fLabelHeight + 5)

        self.fLabelGradientRect = QRectF(
            float(self.fImageBaseSize) / 8.0,
            float(self.fImageBaseSize) / 2.0,
            float(self.fImageBaseSize * 3) / 4.0,
            self.fImageBaseSize + self.fLabelHeight + 5)

    def setCustomPaintMode(self, paintMode):
        if self.fCustomPaintMode == paintMode:
            return

        self.fCustomPaintMode = paintMode
        self.update()

    def setCustomPaintColor(self, color):
        if self.fCustomPaintColor == color:
            return

        self.fCustomPaintColor = color
        self.update()

    def setLabel(self, label):
        if self.fLabel == label:
            return

        self.fLabel = label
        self.updateSizes()
        self.update()

    def setIndex(self, index):
        self.fIndex = index

    def setImage(self, imageId):
        self.fImageNum = "%02i" % imageId
        if imageId in (2, 6, 7, 8, 9, 10, 11, 12, 13):
            img = ":/bitmaps/dial_%s%s.png" % (self.fImageNum,
                                               "" if self.isEnabled() else "d")
        else:
            img = ":/scalable/dial_%s%s.svg" % (self.fImageNum, ""
                                                if self.isEnabled() else "d")

        if img.endswith(".png"):
            if not isinstance(self.fImage, QPixmap):
                self.fImage = QPixmap()
        else:
            if not isinstance(self.fImage, QSvgWidget):
                self.fImage = QSvgWidget()

        self.fImage.load(img)

        if self.fImage.width() > self.fImage.height():
            self.fImageOrientation = self.HORIZONTAL
        else:
            self.fImageOrientation = self.VERTICAL

        # special svgs
        if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL:
            # reserved for carla-wet, carla-vol, carla-pan and color
            if self.fImageNum == "03":
                self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_COLOR

            # reserved for carla-L and carla-R
            elif self.fImageNum == "04":
                self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_CARLA_L

            # reserved for zita
            elif self.fImageNum == "06":
                self.fCustomPaintMode = self.CUSTOM_PAINT_MODE_ZITA

        self.updateSizes()
        self.update()

    def setPrecision(self, value, isInteger):
        self.fPrecision = value
        self.fIsInteger = isInteger
        QDial.setMaximum(self, value)

    def setMinimum(self, value):
        self.fMinimum = value

    def setMaximum(self, value):
        self.fMaximum = value

    def rvalue(self):
        return self.fRealValue

    def setValue(self, value, emitSignal=False):
        if self.fRealValue == value or isnan(value):
            return

        if value <= self.fMinimum:
            qtValue = 0
            self.fRealValue = self.fMinimum

        elif value >= self.fMaximum:
            qtValue = self.fPrecision
            self.fRealValue = self.fMaximum

        else:
            qtValue = round(
                float(value - self.fMinimum) /
                float(self.fMaximum - self.fMinimum) * self.fPrecision)
            self.fRealValue = value

        # Block change signal, we'll handle it ourselves
        self.blockSignals(True)
        QDial.setValue(self, qtValue)
        self.blockSignals(False)

        if emitSignal:
            self.realValueChanged.emit(self.fRealValue)

    @pyqtSlot(int)
    def slot_valueChanged(self, value):
        self.fRealValue = float(value) / self.fPrecision * (
            self.fMaximum - self.fMinimum) + self.fMinimum
        self.realValueChanged.emit(self.fRealValue)

    @pyqtSlot()
    def slot_updateImage(self):
        self.setImage(int(self.fImageNum))

    def minimumSizeHint(self):
        return QSize(self.fImageBaseSize, self.fImageBaseSize)

    def sizeHint(self):
        return QSize(self.fImageBaseSize, self.fImageBaseSize)

    def changeEvent(self, event):
        QDial.changeEvent(self, event)

        # Force svg update if enabled state changes
        if event.type() == QEvent.EnabledChange:
            self.slot_updateImage()

    def enterEvent(self, event):
        self.fIsHovered = True
        if self.fHoverStep == self.HOVER_MIN:
            self.fHoverStep = self.HOVER_MIN + 1
        QDial.enterEvent(self, event)

    def leaveEvent(self, event):
        self.fIsHovered = False
        if self.fHoverStep == self.HOVER_MAX:
            self.fHoverStep = self.HOVER_MAX - 1
        QDial.leaveEvent(self, event)

    def mousePressEvent(self, event):
        if self.fDialMode == self.MODE_DEFAULT:
            return QDial.mousePressEvent(self, event)

        if event.button() == Qt.LeftButton:
            self.fIsPressed = True
            self.fLastDragPos = event.pos()
            self.fLastDragValue = self.fRealValue
            self.dragStateChanged.emit(True)

    def mouseMoveEvent(self, event):
        if self.fDialMode == self.MODE_DEFAULT:
            return QDial.mouseMoveEvent(self, event)

        if not self.fIsPressed:
            return

        range = (self.fMaximum - self.fMinimum) / 4.0
        pos = event.pos()
        dx = range * float(pos.x() - self.fLastDragPos.x()) / self.width()
        dy = range * float(pos.y() - self.fLastDragPos.y()) / self.height()
        value = self.fLastDragValue + dx - dy

        if value < self.fMinimum:
            value = self.fMinimum
        elif value > self.fMaximum:
            value = self.fMaximum
        elif self.fIsInteger:
            value = float(round(value))

        self.setValue(value, True)

    def mouseReleaseEvent(self, event):
        if self.fDialMode == self.MODE_DEFAULT:
            return QDial.mouseReleaseEvent(self, event)

        if self.fIsPressed:
            self.fIsPressed = False
            self.dragStateChanged.emit(False)

    def paintEvent(self, event):
        painter = QPainter(self)
        event.accept()

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)

        if self.fLabel:
            if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL:
                painter.setPen(self.fLabelGradientColor2)
                painter.setBrush(self.fLabelGradient)
                painter.drawRect(self.fLabelGradientRect)

            painter.setFont(self.fLabelFont)
            painter.setPen(
                self.fLabelGradientColorT[0 if self.isEnabled() else 1])
            painter.drawText(self.fLabelPos, self.fLabel)

        if self.isEnabled():
            normValue = float(self.fRealValue -
                              self.fMinimum) / float(self.fMaximum -
                                                     self.fMinimum)
            curLayer = int((self.fImageLayersCount - 1) * normValue)

            if self.fImageOrientation == self.HORIZONTAL:
                xpos = self.fImageBaseSize * curLayer
                ypos = 0.0
            else:
                xpos = 0.0
                ypos = self.fImageBaseSize * curLayer

            source = QRectF(xpos, ypos, self.fImageBaseSize,
                            self.fImageBaseSize)

            if isinstance(self.fImage, QPixmap):
                target = QRectF(0.0, 0.0, self.fImageBaseSize,
                                self.fImageBaseSize)
                painter.drawPixmap(target, self.fImage, source)
            else:
                self.fImage.renderer().render(painter, source)

            # Custom knobs (Dry/Wet and Volume)
            if self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_WET,
                                         self.CUSTOM_PAINT_MODE_CARLA_VOL):
                # knob color
                colorGreen = QColor(0x5D, 0xE7,
                                    0x3D).lighter(100 + self.fHoverStep * 6)
                colorBlue = QColor(0x3E, 0xB8,
                                   0xBE).lighter(100 + self.fHoverStep * 6)

                # draw small circle
                ballRect = QRectF(8.0, 8.0, 15.0, 15.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                #painter.drawRect(ballRect)
                tmpValue = (0.375 + 0.75 * normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                # draw arc
                startAngle = 218 * 16
                spanAngle = -255 * 16 * normValue

                if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_WET:
                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 0))
                    painter.drawEllipse(
                        QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                    gradient = QConicalGradient(15.5, 15.5, -45)
                    gradient.setColorAt(0.0, colorBlue)
                    gradient.setColorAt(0.125, colorBlue)
                    gradient.setColorAt(0.625, colorGreen)
                    gradient.setColorAt(0.75, colorGreen)
                    gradient.setColorAt(0.76, colorGreen)
                    gradient.setColorAt(1.0, colorGreen)
                    painter.setBrush(gradient)
                    painter.setPen(QPen(gradient, 3))

                else:
                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 0))
                    painter.drawEllipse(
                        QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 3))

                painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle)

            # Custom knobs (L and R)
            elif self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_L,
                                           self.CUSTOM_PAINT_MODE_CARLA_R):
                # knob color
                color = QColor(0xAD, 0xD5,
                               0x48).lighter(100 + self.fHoverStep * 6)

                # draw small circle
                ballRect = QRectF(7.0, 8.0, 11.0, 12.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                #painter.drawRect(ballRect)
                tmpValue = (0.375 + 0.75 * normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                painter.setBrush(color)
                painter.setPen(QPen(color, 0))
                painter.drawEllipse(
                    QRectF(ballPoint.x(), ballPoint.y(), 2.0, 2.0))

                # draw arc
                if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_L:
                    startAngle = 218 * 16
                    spanAngle = -255 * 16 * normValue
                else:
                    startAngle = 322.0 * 16
                    spanAngle = 255.0 * 16 * (1.0 - normValue)

                painter.setPen(QPen(color, 2.5))
                painter.drawArc(3.5, 3.5, 22.0, 22.0, startAngle, spanAngle)

            # Custom knobs (Color)
            elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_COLOR:
                # knob color
                color = self.fCustomPaintColor.lighter(100 +
                                                       self.fHoverStep * 6)

                # draw small circle
                ballRect = QRectF(8.0, 8.0, 15.0, 15.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                tmpValue = (0.375 + 0.75 * normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                # draw arc
                startAngle = 218 * 16
                spanAngle = -255 * 16 * normValue

                painter.setBrush(color)
                painter.setPen(QPen(color, 0))
                painter.drawEllipse(
                    QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                painter.setBrush(color)
                painter.setPen(QPen(color, 3))
                painter.drawArc(4.0, 4.8, 26.0, 26.0, startAngle, spanAngle)

            # Custom knobs (Zita)
            elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_ZITA:
                a = normValue * pi * 1.5 - 2.35
                r = 10.0
                x = 10.5
                y = 10.5
                x += r * sin(a)
                y -= r * cos(a)
                painter.setBrush(Qt.black)
                painter.setPen(QPen(Qt.black, 2))
                painter.drawLine(QPointF(11.0, 11.0), QPointF(x, y))

            # Custom knobs
            else:
                painter.restore()
                return

            if self.HOVER_MIN < self.fHoverStep < self.HOVER_MAX:
                self.fHoverStep += 1 if self.fIsHovered else -1
                QTimer.singleShot(20, self.update)

        else:  # isEnabled()
            target = QRectF(0.0, 0.0, self.fImageBaseSize, self.fImageBaseSize)
            if isinstance(self.fImage, QPixmap):
                painter.drawPixmap(target, self.fImage, target)
            else:
                self.fImage.renderer().render(painter, target)

        painter.restore()

    def resizeEvent(self, event):
        QDial.resizeEvent(self, event)
        self.updateSizes()
Exemplo n.º 11
0
class LEDButton(QPushButton):
    # unset
    UNSET  = -1
    # normal
    OFF    = 0
    BLUE   = 1
    GREEN  = 2
    RED    = 3
    YELLOW = 4
    # extra
    CALF   = 5

    def __init__(self, parent):
        QPushButton.__init__(self, parent)

        self.fLastColor = self.UNSET
        self.fColor     = self.UNSET

        self.fImage = QSvgWidget()
        self.fImage.load(":/scalable/led_off.svg")
        self.fRect = QRectF(self.fImage.rect())

        self.setCheckable(True)
        self.setText("")

        self.setColor(self.BLUE)

    def setColor(self, color):
        self.fColor = color

        if color == self.CALF:
            self.fLastColor = self.UNSET

        if self._loadImageNowIfNeeded():
            if isinstance(self.fImage, QPixmap):
                size = self.fImage.width()
            else:
                size = self.fImage.sizeHint().width()

            self.fRect = QRectF(self.fImage.rect())
            self.setFixedSize(self.fImage.size())

    def paintEvent(self, event):
        painter = QPainter(self)
        event.accept()

        self._loadImageNowIfNeeded()

        if isinstance(self.fImage, QPixmap):
            size = self.fImage.width()
            rect = QRectF(0, 0, size, size)
            painter.drawPixmap(rect, self.fImage, rect)
        else:
            size = self.fImage.sizeHint().width()
            rect = QRectF(0, 0, size, size)
            self.fImage.renderer().render(painter, rect)

    def _loadImageNowIfNeeded(self):
        if self.isChecked():
            if self.fLastColor == self.fColor:
                return
            if self.fColor == self.OFF:
                img = ":/scalable/led_off.svg"
            elif self.fColor == self.BLUE:
                img = ":/scalable/led_blue.svg"
            elif self.fColor == self.GREEN:
                img = ":/scalable/led_green.svg"
            elif self.fColor == self.RED:
                img = ":/scalable/led_red.svg"
            elif self.fColor == self.YELLOW:
                img = ":/scalable/led_yellow.svg"
            elif self.fColor == self.CALF:
                img = ":/bitmaps/led_calf_on.png"
            else:
                return False
            self.fLastColor = self.fColor

        elif self.fLastColor != self.OFF:
            img = ":/bitmaps/led_calf_off.png" if self.fColor == self.CALF else ":/scalable/led_off.svg"
            self.fLastColor = self.OFF

        else:
            return False

        if img.endswith(".png"):
            if not isinstance(self.fImage, QPixmap):
                self.fImage = QPixmap()
        else:
            if not isinstance(self.fImage, QSvgWidget):
                self.fImage = QSvgWidget()

        self.fImage.load(img)
        self.update()

        return True
Exemplo n.º 12
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()
Exemplo n.º 13
0
from PyQt5.QtCore import QByteArray, QEventLoop, QTimer

import chess
import chess.svg

board = chess.Board()
board.reset_board()

app = QApplication(sys.argv)
svgWidget = QSvgWidget()
svgWidget.setGeometry(400, 300, 400, 400)
svgWidget.show()
board_picture = chess.svg.board(board)

svg_bytes = bytearray(board_picture, encoding='utf-8')
svgWidget.renderer().load(svg_bytes)
svgWidget.update()
svgWidget.show()

loop = QEventLoop()
QTimer.singleShot(1000, loop.quit)
loop.exec_()

source_cell_index = chess.square(
    chess.FILE_NAMES.index('a'),
    chess.RANK_NAMES.index('1'))  #example: A1 is cell index = 0 (out of 63)
dest_cell_index = chess.square(chess.FILE_NAMES.index('a'),
                               chess.RANK_NAMES.index('3'))

print('source_cell_index:', source_cell_index)
print('dest_cell_index:', dest_cell_index)
Exemplo n.º 14
0
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)
class RSBGDocker(DockWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Rogudator's speech bubble generator")
        mainLayout = QVBoxLayout()

        self.addOnPage = QPushButton("Add on Page")
        mainLayout.addWidget(self.addOnPage)

        previewLabel = QLabel("Preview")
        mainLayout.addWidget(previewLabel)

        self.preview = QSvgWidget(self)
        self.preview.setMinimumHeight(200)
        #self.preview.setAspectRatioMode(Qt.AspectRatioMode.KeepAspectRatio)
        mainLayout.addWidget(self.preview)

        bubbleTypes = QGroupBox()
        bubbleTypes.setTitle("Bubble type")
        bubbleTypesLayout = QHBoxLayout()
        self.squareBubble = QRadioButton(self)
        self.squareBubble.setText("Square")
        bubbleTypesLayout.addWidget(self.squareBubble)
        self.roundBubble = QRadioButton(self)
        self.roundBubble.setText("Round")
        self.roundBubble.setChecked(True)
        bubbleTypesLayout.addWidget(self.roundBubble)
        bubbleTypes.setLayout(bubbleTypesLayout)
        self.bubbleColorButton = QPushButton(self)
        self.bubbleColor = QColor("white")
        bubbleColorImage = QPixmap(32, 32)
        bubbleColorImage.fill(self.bubbleColor)
        bubbleColorIcon = QIcon(bubbleColorImage)
        self.bubbleColorButton.setIcon(bubbleColorIcon)
        self.bubbleColorButton.setFixedWidth(self.bubbleColorButton.height())
        bubbleTypesLayout.addWidget(self.bubbleColorButton)
        mainLayout.addWidget(bubbleTypes)

        outlineSize = QGroupBox("Outline")
        outlineSliderAndSpinBox = QHBoxLayout()
        self.outlineSlider = QSlider(self)
        self.outlineSlider.setMinimum(0)
        self.outlineSlider.setMaximum(10)
        self.outlineSlider.setValue(3)
        self.outlineSlider.setOrientation(Qt.Orientation.Horizontal)
        outlineSliderAndSpinBox.addWidget(self.outlineSlider)
        self.outlineSpinBox = QSpinBox(self)
        self.outlineSpinBox.setMinimum(0)
        self.outlineSpinBox.setValue(3)
        outlineSliderAndSpinBox.addWidget(self.outlineSpinBox)
        self.outlineColorButton = QPushButton(self)
        self.outlineColor = QColor("black")
        outlineColorImage = QPixmap(32, 32)
        outlineColorImage.fill(self.outlineColor)
        outlineColorIcon = QIcon(outlineColorImage)
        self.outlineColorButton.setIcon(outlineColorIcon)
        self.outlineColorButton.setFixedWidth(self.outlineColorButton.height())
        outlineSliderAndSpinBox.addWidget(self.outlineColorButton)
        outlineSize.setLayout(outlineSliderAndSpinBox)
        mainLayout.addWidget(outlineSize)

        speechGroup = QGroupBox("Speech")
        speechGroupLayout = QVBoxLayout()

        fontRow = QHBoxLayout()

        self.speechFont = QFontComboBox(self)
        fontRow.addWidget(self.speechFont)

        self.speechFontSize = QSpinBox(self)
        self.speechFontSize.setValue(14)
        self.speechFontSize.setMinimum(1)
        fontRow.addWidget(self.speechFontSize)

        self.currentFontColorButton = QPushButton(self)
        self.speechFontColor = QColor("black")
        fontColorImage = QPixmap(32, 32)
        fontColorImage.fill(self.speechFontColor)
        fontColorIcon = QIcon(fontColorImage)
        self.currentFontColorButton.setIcon(fontColorIcon)
        self.currentFontColorButton.setFixedWidth(
            self.currentFontColorButton.height())
        fontRow.addWidget(self.currentFontColorButton)

        speechGroupLayout.addLayout(fontRow)

        self.bubbleText = QTextEdit("Rogudator's speech bubble generator!")
        speechGroupLayout.addWidget(self.bubbleText)

        self.autocenter = QCheckBox(self)
        self.autocenter.setText("Center automatically")
        self.autocenter.setChecked(True)
        speechGroupLayout.addWidget(self.autocenter)

        self.averageLineLength = QGroupBox()
        averageLineLengthSliderAndSpinBox = QHBoxLayout()
        self.averageLineLengthSlider = QSlider(self)
        self.averageLineLengthSlider.setMinimum(0)
        self.averageLineLengthSlider.setMaximum(100)
        self.averageLineLengthSlider.setOrientation(Qt.Orientation.Horizontal)
        averageLineLengthSliderAndSpinBox.addWidget(
            self.averageLineLengthSlider)
        self.averageLineLengthSpinBox = QSpinBox(self)
        self.averageLineLengthSpinBox.setMinimum(0)
        averageLineLengthSliderAndSpinBox.addWidget(
            self.averageLineLengthSpinBox)
        self.averageLineLength.setLayout(averageLineLengthSliderAndSpinBox)
        self.averageLineLength.setDisabled(True)
        speechGroupLayout.addWidget(self.averageLineLength)

        speechGroup.setLayout(speechGroupLayout)
        mainLayout.addWidget(speechGroup)

        tailSize = QGroupBox()
        tailSize.setTitle("Tail size")
        tailSliderAndSpinBox = QHBoxLayout()
        self.tailSlider = QSlider(self)
        self.tailSlider.setMinimum(0)
        self.tailSlider.setMaximum(self.speechFontSize.value() * 10)
        self.tailSlider.setOrientation(Qt.Orientation.Horizontal)
        tailSliderAndSpinBox.addWidget(self.tailSlider)
        self.tailSpinBox = QSpinBox(self)
        self.tailSpinBox.setMinimum(0)
        self.tailSpinBox.setMaximum(self.speechFontSize.value() * 10)
        tailSliderAndSpinBox.addWidget(self.tailSpinBox)
        tailSize.setLayout(tailSliderAndSpinBox)
        mainLayout.addWidget(tailSize)

        self.tailPositions = QGroupBox()
        self.tailPositions.setTitle("Tail position")
        tailPositionsLayout = QHBoxLayout()
        self.tailPosition = []
        for i in range(8):
            self.tailPosition.append(QRadioButton(self))
            self.tailPosition[i].setText(str(i + 1))
            self.tailPosition[i].clicked.connect(self.updatePreview)
            tailPositionsLayout.addWidget(self.tailPosition[i])

        self.tailPositions.setLayout(tailPositionsLayout)
        self.tailPositions.setDisabled(True)
        mainLayout.addWidget(self.tailPositions)

        self.updatePreview()

        self.addOnPage.clicked.connect(self.addOnPageShape)
        self.squareBubble.clicked.connect(self.updatePreview)
        self.roundBubble.clicked.connect(self.updatePreview)
        self.bubbleColorButton.clicked.connect(self.changeBubbleColor)
        self.outlineSlider.valueChanged.connect(self.outlineSpinBoxUpdate)
        self.outlineSpinBox.valueChanged.connect(self.outlineSliderUpdate)
        self.outlineSpinBox.valueChanged.connect(self.updatePreview)
        self.outlineColorButton.clicked.connect(self.changeOutlineColor)
        self.bubbleText.textChanged.connect(self.updatePreview)
        self.speechFontSize.valueChanged.connect(self.updatePreview)
        self.speechFontSize.valueChanged.connect(self.tailSliderUpdateMaximum)
        self.currentFontColorButton.clicked.connect(self.changeFontColor)
        self.speechFont.currentFontChanged.connect(self.updatePreview)
        self.autocenter.stateChanged.connect(self.enableAverageLineLength)
        self.autocenter.clicked.connect(self.updatePreview)
        self.averageLineLengthSlider.valueChanged.connect(
            self.averageLineLengthSpinBoxUpdate)
        self.averageLineLengthSpinBox.valueChanged.connect(self.updatePreview)
        self.averageLineLengthSpinBox.valueChanged.connect(
            self.averageLineLengthSliderUpdate)
        self.tailSlider.valueChanged.connect(self.tailSpinBoxUpdate)
        self.tailSpinBox.valueChanged.connect(self.tailSliderUpdate)
        self.tailSpinBox.valueChanged.connect(self.updatePreview)

        self.scrollMainLayout = QScrollArea(self)
        self.scrollMainLayout.setWidgetResizable(True)
        self.scrollMainLayout.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        widget = QWidget()
        widget.setLayout(mainLayout)
        self.scrollMainLayout.setWidget(widget)
        self.setWidget(self.scrollMainLayout)
        self.show()

    def tailSliderUpdateMaximum(self):
        self.tailSlider.setMaximum(self.speechFontSize.value() * 10)
        self.tailSpinBox.setMaximum(self.speechFontSize.value() * 10)

    def changeBubbleColor(self):
        self.bubbleColor = QColorDialog.getColor(self.bubbleColor)
        colorImage = QPixmap(32, 32)
        colorImage.fill(self.bubbleColor)
        colorIcon = QIcon(colorImage)
        self.bubbleColorButton.setIcon(colorIcon)
        self.updatePreview()

    def changeFontColor(self):
        self.speechFontColor = QColorDialog.getColor(self.speechFontColor)
        colorImage = QPixmap(32, 32)
        colorImage.fill(self.speechFontColor)
        colorIcon = QIcon(colorImage)
        self.currentFontColorButton.setIcon(colorIcon)
        self.updatePreview()

    def changeOutlineColor(self):
        self.outlineColor = QColorDialog.getColor(self.outlineColor)
        colorImage = QPixmap(32, 32)
        colorImage.fill(self.outlineColor)
        colorIcon = QIcon(colorImage)
        self.outlineColorButton.setIcon(colorIcon)
        self.updatePreview()

    def outlineSpinBoxUpdate(self):
        self.outlineSpinBox.setValue(self.outlineSlider.value())

    def outlineSliderUpdate(self):
        if self.outlineSpinBox.value() < 51:
            self.outlineSlider.setValue(self.outlineSpinBox.value())

    def tailSpinBoxUpdate(self):
        self.tailSpinBox.setValue(self.tailSlider.value())
        if self.tailSlider.value() == 0:
            self.tailPositions.setDisabled(True)
        else:
            self.tailPositions.setDisabled(False)

    def tailSliderUpdate(self):
        if self.tailSpinBox.value() < 101:
            self.tailSlider.setValue(self.tailSpinBox.value())

    def enableAverageLineLength(self):
        if self.autocenter.isChecked():
            self.averageLineLength.setDisabled(True)
        else:
            self.averageLineLength.setDisabled(False)

    def averageLineLengthSpinBoxUpdate(self):
        self.averageLineLengthSpinBox.setValue(
            self.averageLineLengthSlider.value())

    def averageLineLengthSliderUpdate(self):
        if self.averageLineLengthSpinBox.value() < 101:
            self.averageLineLengthSlider.setValue(
                self.averageLineLengthSpinBox.value())

    def getSpeechLines(self, text, lineLength):
        size = 0
        speach = ""
        lines = []
        if (lineLength > 0):
            words = text.split(" ")
            for word in words:
                speach += word
                size += len(word)
                if size < lineLength:
                    speach += " "
                else:
                    size = 0
                    lines.append(speach)
                    speach = ""
            if (speach != "") and (speach != " "):
                lines.append(speach.strip())
        else:
            lines = text.split("\n")

        return lines

    def getPreview(self):

        lineLength = int((pow(
            (len(self.bubbleText.toPlainText())), 1 / 2)) * 1.8)
        if not (self.autocenter.isChecked()):
            lineLength = self.averageLineLengthSpinBox.value()
        lines = self.getSpeechLines(self.bubbleText.toPlainText(), lineLength)

        biggestLine = ""
        for line in lines:
            if (len(line) > len(biggestLine)):
                biggestLine = line

        #Calculate text box size
        font = self.speechFont.currentFont()
        font.setPixelSize(int(self.speechFontSize.value() * 1.3))
        fontSize = self.speechFontSize.value()
        textHeight = int(fontSize * (len(lines)) -
                         (fontSize - QFontMetrics(font).capHeight()))
        textWidth = QFontMetrics(font).width(biggestLine)
        tailLength = self.tailSpinBox.value()

        framePadding = fontSize
        tailPadding = tailLength
        bubblePadding = int(fontSize * 1.5)

        textTag = "<text x=\"{}\" y=\"{}\" style=\"font-size:{};font-family:{};fill:{};text-anchor:middle\" >{}</text>"
        text = ""
        textStartX = framePadding + tailPadding + bubblePadding + (int(
            textWidth / 2))
        textStartY = framePadding + tailPadding + bubblePadding + QFontMetrics(
            font).capHeight()

        for line in lines:
            text += textTag.format(textStartX, textStartY, fontSize,
                                   font.family(), self.speechFontColor.name(),
                                   line)
            textStartY += fontSize

        bubbleCoordinatesX0 = framePadding + tailPadding
        bubbleCoordinatesY0 = framePadding + tailPadding
        bubbleCoordinatesXHalf = framePadding + tailPadding + bubblePadding + (
            int(textWidth / 2))
        bubbleCoordinatesYHalf = framePadding + tailPadding + bubblePadding + (
            int(textHeight / 2))
        bubbleCoordinatesX = framePadding + tailPadding + bubblePadding + textWidth + bubblePadding
        bubbleCoordinatesY = framePadding + tailPadding + bubblePadding + textHeight + bubblePadding
        bubbleCoordinates = []
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesXHalf, bubbleCoordinatesY0))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesX, bubbleCoordinatesY0))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesX, bubbleCoordinatesYHalf))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesX, bubbleCoordinatesY))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesXHalf, bubbleCoordinatesY))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesX0, bubbleCoordinatesY))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesX0, bubbleCoordinatesYHalf))
        bubbleCoordinates.append(
            BubbleCoordinates(bubbleCoordinatesX0, bubbleCoordinatesY0))

        i = 0
        bubbleCoordinatesString = "M"
        bubbleCoordinatesStringEnd = str(bubbleCoordinates[0].x) + "," + str(
            bubbleCoordinates[0].y) + "Z"
        while (i < 8):
            if (self.roundBubble.isChecked()):

                if (self.tailSpinBox.value() > 0):
                    #for coordinates in center (even)
                    textWidth01 = int(pow(textWidth, 1 / 2.8))
                    textHeight01 = int(pow(textHeight, 1 / 2))
                    #for coordinates in the corner (odd)
                    x04 = int(
                        (bubbleCoordinates[1].x - bubbleCoordinates[0].x) *
                        0.4)
                    x06 = int(
                        (bubbleCoordinates[1].x - bubbleCoordinates[0].x) *
                        0.6)
                    y04 = int(
                        (bubbleCoordinates[2].y - bubbleCoordinates[1].y) *
                        0.4)
                    y06 = int(
                        (bubbleCoordinates[2].y - bubbleCoordinates[1].y) *
                        0.6)
                    if i == 0 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += str(
                            bubbleCoordinates[0].x - textWidth01) + "," + str(
                                bubbleCoordinates[0].y) + " L" + str(
                                    bubbleCoordinates[0].x) + "," + str(
                                        bubbleCoordinates[0].y -
                                        tailLength) + " " + str(
                                            bubbleCoordinates[0].x +
                                            textWidth01) + "," + str(
                                                bubbleCoordinates[0].y) + " "
                        bubbleCoordinatesStringEnd = str(
                            bubbleCoordinates[0].x - textWidth01) + "," + str(
                                bubbleCoordinates[0].y) + "Z"
                    elif i == 2 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += str(
                            bubbleCoordinates[2].x) + "," + str(
                                bubbleCoordinates[2].y -
                                textHeight01) + " L" + str(
                                    bubbleCoordinates[2].x +
                                    tailLength) + "," + str(
                                        bubbleCoordinates[2].y) + " " + str(
                                            bubbleCoordinates[2].x
                                        ) + "," + str(bubbleCoordinates[2].y +
                                                      textHeight01) + " "
                    elif i == 4 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += str(
                            bubbleCoordinates[4].x + textWidth01) + "," + str(
                                bubbleCoordinates[4].y) + " L" + str(
                                    bubbleCoordinates[4].x) + "," + str(
                                        bubbleCoordinates[4].y +
                                        tailLength) + " " + str(
                                            bubbleCoordinates[4].x -
                                            textWidth01) + "," + str(
                                                bubbleCoordinates[4].y) + " "
                    elif i == 6 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += str(
                            bubbleCoordinates[6].x) + "," + str(
                                bubbleCoordinates[6].y +
                                textHeight01) + " L" + str(
                                    bubbleCoordinates[6].x -
                                    tailLength) + "," + str(
                                        bubbleCoordinates[6].y) + " " + str(
                                            bubbleCoordinates[6].x
                                        ) + "," + str(bubbleCoordinates[6].y -
                                                      textHeight01) + " "
                    elif i == 1 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += "Q" + str(
                            bubbleCoordinates[1].x - x06
                        ) + "," + str(bubbleCoordinates[1].y) + " " + str(
                            int((bubbleCoordinates[1].x +
                                 bubbleCoordinates[1].x - x06) / 2)
                        ) + "," + str(
                            int((bubbleCoordinates[1].y + y04 +
                                 bubbleCoordinates[1].y) / 2)) + " L" + str(
                                     bubbleCoordinates[1].x + tailLength
                                 ) + "," + str(
                                     bubbleCoordinates[1].y - tailLength
                                 ) + " " + str(
                                     int((bubbleCoordinates[1].x +
                                          bubbleCoordinates[1].x - x04) / 2)
                                 ) + "," + str(
                                     int((bubbleCoordinates[1].y + y06 +
                                          bubbleCoordinates[1].y) /
                                         2)) + " Q" + str(
                                             bubbleCoordinates[1].x
                                         ) + "," + str(bubbleCoordinates[1].y +
                                                       y06) + " "
                    elif i == 3 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += "Q" + str(
                            bubbleCoordinates[3].x) + "," + str(
                                bubbleCoordinates[3].y - y06) + " " + str(
                                    int(
                                        (bubbleCoordinates[3].x +
                                         bubbleCoordinates[3].x - x04) / 2
                                    )) + "," + str(
                                        int((bubbleCoordinates[3].y - y06 +
                                             bubbleCoordinates[3].y) / 2)
                                    ) + " L" + str(
                                        bubbleCoordinates[3].x + tailLength
                                    ) + "," + str(
                                        bubbleCoordinates[3].y + tailLength
                                    ) + " " + str(
                                        int((bubbleCoordinates[3].x +
                                             bubbleCoordinates[3].x - x06) / 2)
                                    ) + "," + str(
                                        int((bubbleCoordinates[3].y - y04 +
                                             bubbleCoordinates[3].y) /
                                            2)) + " Q" + str(
                                                bubbleCoordinates[3].x - x06
                                            ) + "," + str(
                                                bubbleCoordinates[3].y) + " "
                    elif i == 5 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += "Q" + str(
                            bubbleCoordinates[5].x + x06
                        ) + "," + str(bubbleCoordinates[5].y) + " " + str(
                            int((bubbleCoordinates[5].x +
                                 bubbleCoordinates[5].x + x06) / 2)
                        ) + "," + str(
                            int((bubbleCoordinates[5].y - y04 +
                                 bubbleCoordinates[5].y) / 2)) + " L" + str(
                                     bubbleCoordinates[5].x - tailLength
                                 ) + "," + str(
                                     bubbleCoordinates[5].y + tailLength
                                 ) + " " + str(
                                     int((bubbleCoordinates[5].x +
                                          bubbleCoordinates[5].x + x04) / 2)
                                 ) + "," + str(
                                     int((bubbleCoordinates[5].y - y06 +
                                          bubbleCoordinates[5].y) /
                                         2)) + " Q" + str(
                                             bubbleCoordinates[5].x
                                         ) + "," + str(bubbleCoordinates[5].y -
                                                       y06) + " "
                    elif i == 7 and self.tailPosition[i].isChecked():
                        bubbleCoordinatesString += "Q" + str(
                            bubbleCoordinates[7].x) + "," + str(
                                bubbleCoordinates[7].y + y06) + " " + str(
                                    int(
                                        (bubbleCoordinates[7].x +
                                         bubbleCoordinates[7].x + x04) / 2
                                    )) + "," + str(
                                        int((bubbleCoordinates[7].y + y06 +
                                             bubbleCoordinates[7].y) / 2)
                                    ) + " L" + str(
                                        bubbleCoordinates[7].x - tailLength
                                    ) + "," + str(
                                        bubbleCoordinates[7].y - tailLength
                                    ) + " " + str(
                                        int((bubbleCoordinates[7].x +
                                             bubbleCoordinates[7].x + x06) / 2)
                                    ) + "," + str(
                                        int((bubbleCoordinates[7].y + y04 +
                                             bubbleCoordinates[7].y) /
                                            2)) + " Q" + str(
                                                bubbleCoordinates[7].x + x06
                                            ) + "," + str(
                                                bubbleCoordinates[7].y) + " "
                    else:
                        if (i % 2 == 0):
                            bubbleCoordinatesString += str(
                                bubbleCoordinates[i].x) + "," + str(
                                    bubbleCoordinates[i].y) + " "
                        else:
                            bubbleCoordinatesString += "Q" + str(
                                bubbleCoordinates[i].x) + "," + str(
                                    bubbleCoordinates[i].y) + " "
                else:
                    if (i % 2 == 0):
                        bubbleCoordinatesString += str(
                            bubbleCoordinates[i].x) + "," + str(
                                bubbleCoordinates[i].y) + " "
                    else:
                        bubbleCoordinatesString += "Q" + str(
                            bubbleCoordinates[i].x) + "," + str(
                                bubbleCoordinates[i].y) + " "
            elif (self.squareBubble.isChecked()):
                bubbleCoordinatesString += str(
                    bubbleCoordinates[i].x) + "," + str(
                        bubbleCoordinates[i].y) + " "
            i += 1
        bubbleCoordinatesString += bubbleCoordinatesStringEnd
        pathStyle = "style=\"fill:{};stroke:{};stroke-width:{};stroke-linejoin:round\"".format(
            self.bubbleColor.name(), self.outlineColor.name(),
            self.outlineSpinBox.value())
        bubble = "<path " + pathStyle + " d=\"" + bubbleCoordinatesString + "\"/>"

        frameWidth = framePadding + tailPadding + bubblePadding + textWidth + bubblePadding + tailPadding + framePadding
        frameHeight = framePadding + tailPadding + bubblePadding + textHeight + bubblePadding + tailPadding + framePadding

        result = "<svg width=\"{}\" height=\"{}\" >{}{}</svg>".format(
            frameWidth, frameHeight, bubble, text)

        return result

    def updatePreview(self):
        result = self.getPreview()
        resultBytes = bytearray(result, encoding='utf-8')
        self.preview.renderer().load(resultBytes)

    def addOnPageShape(self):
        result = self.getPreview()
        d = Krita.instance().activeDocument()
        root = d.rootNode()
        l3 = d.createVectorLayer(self.bubbleText.toPlainText()[:16])
        root.addChildNode(l3, None)
        l3.addShapesFromSvg(result)
        pass

    def canvasChanged(self, canvas):
        pass
Exemplo n.º 16
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()
Exemplo n.º 17
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.
        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()

    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.showNextNumber()
            self.delay_of_next_number = verz

    def showNextNumber(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)
        if self.turn >= len(
            (self.lottodraw.random_number + self.lottodraw.random_addit)):
            self.timer.stop()
            if self.ui.rdbtn_show_draw_after.isChecked():
                self.onDrawOverview()
            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 onDrawOverview(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, accept = LottoSettingsDialog.get_values(self.sysdat)
        logging.debug('Lotto setting %s accept: %s', list(system), accept)
        if accept:
            self.lottodraw.data['name'] = system[0]
            self.lottodraw.data['max_draw'] = system[1]
            self.lottodraw.data['draw_numbers'] = system[2]
            self.lottodraw.data['with_addit'] = system[3]
            self.lottodraw.data['addit_numbers'] = system[4]
            self.lottodraw.data['sep_addit_numbers'] = system[5]
            self.lottodraw.data['max_addit'] = system[6]
            self.lottodraw.data['name_addition'] = system[7]

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

    def onBtnStart(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 actionLottoSim(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 randomNumbersGenerator(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 cleanOutputText(self):
        """Clean the output text

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

    def onInfo(self, test=None):
        """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>'))
        if test:
            infobox.setStandardButtons(QtWidgets.QMessageBox.Ok)
            button = infobox.button(QtWidgets.QMessageBox.Ok)
            QtCore.QTimer.singleShot(0, button.clicked)
        infobox.exec_()

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

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

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

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

    def draw_distribution(self, test=None):
        self.testdraw = statistic.uniform_distribution()
        maxtest = max(self.testdraw.items(), key=operator.itemgetter(1))
        mintest = min(self.testdraw.items(), key=operator.itemgetter(1))
        printdlg = DlgPrint()
        printdlg.editor.setHtml(
            self.
            tr('<h1>Overview</h1>Maximim {} at number {}, Minimum {} at number {}'
               '<br>Numbers in draw {}'.format(maxtest[1], maxtest[0],
                                               mintest[1], mintest[0],
                                               len(self.testdraw.items()))))
        if test:
            QtCore.QTimer.singleShot(500, printdlg.reject)
        printdlg.exec_()
Exemplo n.º 18
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()
</g>
</svg>

"""

app = QApplication(sys.argv)

layout = QGridLayout()  # планировка
widget = QWidget()
widget.setLayout(layout)

svgWidget = QSvgWidget()  # SVG виджет
svg_bytes = bytearray(
    svg_str.format(x='0', y='0'),
    encoding='utf-8')  # подставить угол и перевести в байтовую строку
svgWidget.renderer().load(svg_bytes)  # загрузить SVG в виджет
layout.addWidget(svgWidget)

sliderX = QSlider(Qt.Horizontal)  # слайдер
sliderX.setRange(0, 793)
sliderY = QSlider(Qt.Horizontal)  # слайдер
sliderY.setRange(0, 566)


def updateSVG():
    """ Обновляет SVG при движении слайдера"""
    x = sliderX.value()
    y = sliderY.value()
    svg_bytes = bytearray(
        svg_str.format(x=str(x), y=str(y)),
        encoding='utf-8')  # обновить угол и перевести в байтовую строку
Exemplo n.º 20
0
class ScalableButton(QPushButton):
    def __init__(self, parent):
        QPushButton.__init__(self, parent)

        self.fImageNormal = None
        self.fImageDown = None
        self.fImageHover = None
        self.fImageRect = QRectF()
        self.fIsHovered = False
        self.fTopText = ""
        self.fTopTextColor = QColor()
        self.fTopTextFont = QFont()
        self.setText("")

    def setPixmaps(self, normal, down, hover):
        self.fImageNormal = QPixmap()
        self.fImageDown = QPixmap()
        self.fImageHover = QPixmap()
        self._loadImages(normal, down, hover)

    def setSvgs(self, normal, down, hover):
        self.fImageNormal = QSvgWidget()
        self.fImageDown = QSvgWidget()
        self.fImageHover = QSvgWidget()
        self._loadImages(normal, down, hover)

    def _loadImages(self, normal, down, hover):
        self.fImageNormal.load(normal)
        self.fImageDown.load(down)
        self.fImageHover.load(hover)

        if isinstance(self.fImageNormal, QPixmap):
            width = self.fImageNormal.width()
            height = self.fImageNormal.height()
        else:
            width = self.fImageNormal.sizeHint().width()
            height = self.fImageNormal.sizeHint().height()

        self.fImageRect = QRectF(0, 0, width, height)

        self.setMinimumSize(width, height)
        self.setMaximumSize(width, height)

    def setTopText(self, text, color, font):
        self.fTopText = text
        self.fTopTextColor = color
        self.fTopTextFont = font

    def enterEvent(self, event):
        self.fIsHovered = True
        QPushButton.enterEvent(self, event)

    def leaveEvent(self, event):
        self.fIsHovered = False
        QPushButton.leaveEvent(self, event)

    def paintEvent(self, event):
        painter = QPainter(self)
        event.accept()

        if self.fImageNormal is None:
            return

        if isinstance(self.fImageNormal, QPixmap):
            self.paintEventPixmap(painter)
        else:
            self.paintEventSvg(painter)

        if not self.fTopText:
            return

        painter.save()
        painter.setPen(self.fTopTextColor)
        painter.setBrush(self.fTopTextColor)
        painter.setFont(self.fTopTextFont)
        painter.drawText(QPointF(10, 16), self.fTopText)
        painter.restore()

    def paintEventPixmap(self, painter):
        if not self.isEnabled():
            painter.save()
            painter.setOpacity(0.2)
            painter.drawPixmap(self.fImageRect, self.fImageNormal,
                               self.fImageRect)
            painter.restore()

        elif self.isChecked() or self.isDown():
            painter.drawPixmap(self.fImageRect, self.fImageDown,
                               self.fImageRect)

        elif self.fIsHovered:
            painter.drawPixmap(self.fImageRect, self.fImageHover,
                               self.fImageRect)

        else:
            painter.drawPixmap(self.fImageRect, self.fImageNormal,
                               self.fImageRect)

    def paintEventSvg(self, painter):
        if not self.isEnabled():
            painter.save()
            painter.setOpacity(0.2)
            self.fImageNormal.renderer().render(painter, self.fImageRect)
            painter.restore()

        elif self.isChecked() or self.isDown():
            self.fImageDown.renderer().render(painter, self.fImageRect)

        elif self.fIsHovered:
            self.fImageHover.renderer().render(painter, self.fImageRect)

        else:
            self.fImageNormal.renderer().render(painter, self.fImageRect)