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
示例#2
0
    def _setupPanel(self, iconSize):
        layout = QHBoxLayout()
        layout.setAlignment(Qt.AlignHCenter)

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

        self.setLayout(layout)
示例#3
0
    def _createIconLayout(self, iconSize):
        iconLayout = QHBoxLayout()
        iconLayout.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

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

        return iconLayout
示例#4
0
class Icon(QWidget):
    def __init__(self, parent, icon, size=None, padding=None, color=None):
        QWidget.__init__(self, parent)
        padding = padding or 0
        self._theme_manager = ThemeManager.get(self)

        self._color = format_color(
            color or self._theme_manager.get_color('button_foreground'),
            ColorFormat.rgb_string_256)

        self._svgdoc = QDomDocument()
        self._icon_widget = QSvgWidget(self)

        self.loadIcon(icon)

        if size:
            self._icon_widget.setFixedSize(
                QSize(size.width() - 2 * padding,
                      size.height() - 2 * padding))

        self._layout = QHBoxLayout(self)
        self._layout.setContentsMargins(padding, padding, padding, padding)
        self._layout.addWidget(self._icon_widget, Qt.AlignCenter)

    def loadIcon(self, icon):
        file = QFile(f'icons:{icon}')
        file.open(QFile.ReadOnly)
        self._svgdoc.setContent(file.readAll())
        self._svgdoc.documentElement().setAttribute('fill', self._color)
        file.close()
        self._icon_widget.load(self._svgdoc.toByteArray())

    def setEnabled(self, enabled):
        QWidget.setEnabled(self, enabled)
        self._svgdoc.documentElement().setAttribute('fill', self._color)
        self._svgdoc.documentElement().setAttribute(
            'fill-opacity', '1' if self.isEnabled() else '0.4')
        self._icon_widget.load(self._svgdoc.toByteArray())

    def setColor(self, color=None):
        color = format_color(
            color or self._theme_manager.get_color('button_foreground'),
            ColorFormat.rgb_string_256) or self._color
        self._svgdoc.documentElement().setAttribute('fill', color)
        self._svgdoc.documentElement().setAttribute(
            'fill-opacity', '1' if self.isEnabled() else '0.4')
        self._icon_widget.load(self._svgdoc.toByteArray())
示例#5
0
    def loadDecoration(self, decoKey, decoSize=None):

        if decoKey not in self.DECO_MAP:
            logger.error("Decoration with name '%s' does not exist" % decoKey)
            return QSvgWidget()

        svgPath = path.join(self.mainConf.graphPath, self.DECO_MAP[decoKey])
        if not path.isfile(svgPath):
            logger.error("Decoration file '%s' not in assets folder" %
                         self.DECO_MAP[decoKey])
            return QSvgWidget()

        svgDeco = QSvgWidget(svgPath)
        if decoSize is not None:
            svgDeco.setFixedSize(QSize(decoSize[0], decoSize[1]))

        return svgDeco
示例#6
0
class BackgroundTab():
    def __init__(self):
        self.img_path = media.img.ImgPath()
        self.IniUIElements()
        self.DrawTab()

    def IniUIElements(self):
        self.DefinePicture()

    def DefinePicture(self):
        self.pic = QSvgWidget(self.img_path.background)
        self.pic.setFixedSize(400, 400)

    def DrawTab(self):
        wp_layout = QHBoxLayout()
        wp_layout.addWidget(self.pic)
        self.tab_widget = QWidget()
        self.tab_widget.setLayout(wp_layout)
示例#7
0
    def __init_ui(self) -> NoReturn:
        self.setFixedSize(120, 60)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setObjectName("item")

        self.setStyleSheet("""
            QFrame#item {
                border: 2px solid black;
                border-radius: 5px;
                background-color: """ + self._enum.background_color + """;
                }
            """)

        icon = QSvgWidget(self)
        icon.load(self._enum.path)
        icon.setFixedSize(40, 40)

        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(icon)
        self.setLayout(layout)
示例#8
0
class DownloadSpeedWidget(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.downloaded_bytes = 0
        self.total_bytes = 0

        self.timer = QTimer()
        self.timer.start(1000)
        self.timer.timeout.connect(self.monitor_download_show)
        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)

        self.text = QLabel()
        self.set_text()

        size = self.text.fontMetrics().height()

        self.icon = QSvgWidget()
        self.icon.load(os.path.join(ASSETS_PATH, "speed_download.svg"))
        self.icon.setFixedSize(size * 0.7, size * 0.7)

        self.layout.addWidget(self.icon)
        self.layout.addWidget(self.text)

    def set_text(self):
        self.text.setText(
            f"{format_bytes(self.downloaded_bytes)}/s ({format_bytes(self.total_bytes)})"
        )

    def reset(self):
        self.total_bytes = 0

    def monitor_download(self, size):
        self.downloaded_bytes += size
        self.total_bytes += size

    def monitor_download_show(self):
        self.set_text()
        self.downloaded_bytes = 0
    def get_svg_widget(self,
                       element: Gui_Element,
                       height: int,
                       width: int,
                       fill: str = "#FF9933",
                       text: str = "00") -> QSvgWidget:

        svg = self.read_svg_from_file(element)
        svg = self.interpolate_svg(svg, fill, text)

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

        return svg_widget
示例#10
0
class GuiConfigEditor(QDialog):
    def __init__(self, theParent, theProject):
        QDialog.__init__(self, theParent)

        logger.debug("Initialising ConfigEditor ...")

        self.mainConf = nw.CONFIG
        self.theParent = theParent
        self.theProject = theProject
        self.outerBox = QHBoxLayout()
        self.innerBox = QVBoxLayout()

        self.setWindowTitle("Preferences")

        self.gradPath = path.abspath(
            path.join(self.mainConf.appPath, "graphics", "gear.svg"))
        self.svgGradient = QSvgWidget(path.join(self.gradPath))
        self.svgGradient.setFixedSize(QSize(64, 64))

        self.theProject.countStatus()
        self.tabMain = GuiConfigEditGeneral(self.theParent)
        self.tabEditor = GuiConfigEditEditor(self.theParent)

        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.tabMain, "General")
        self.tabWidget.addTab(self.tabEditor, "Editor")

        self.setLayout(self.outerBox)
        self.outerBox.addWidget(self.svgGradient, 0, Qt.AlignTop)
        self.outerBox.addLayout(self.innerBox)

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.accepted.connect(self._doSave)
        self.buttonBox.rejected.connect(self._doClose)

        self.innerBox.addWidget(self.tabWidget)
        self.innerBox.addWidget(self.buttonBox)

        self.show()

        logger.debug("ProjectEditor ConfigEditor complete")

        return

    def _doSave(self):

        logger.verbose("ConfigEditor save button clicked")

        validEntries = True
        needsRestart = False

        retA, retB = self.tabMain.saveValues()
        validEntries &= retA
        needsRestart |= retB

        retA, retB = self.tabEditor.saveValues()
        validEntries &= retA
        needsRestart |= retB

        if needsRestart:
            msgBox = QMessageBox()
            msgBox.information(
                self, "Preferences",
                "Some changes will not be applied until<br>%s has been restarted."
                % nw.__package__)

        if validEntries:
            self.accept()

        return

    def _doClose(self):
        logger.verbose("ConfigEditor close button clicked")
        self.close()
        return
示例#11
0
class GuiItemEditor(QDialog):

    def __init__(self, theParent, theProject, tHandle):
        QDialog.__init__(self, theParent)

        logger.debug("Initialising ItemEditor ...")

        self.mainConf   = nw.CONFIG
        self.theProject = theProject
        self.theParent  = theParent
        self.theItem    = self.theProject.getItem(tHandle)

        self.outerBox   = QHBoxLayout()
        self.innerBox   = QVBoxLayout()

        self.setWindowTitle("Item Settings")

        self.gradPath = path.abspath(path.join(self.mainConf.appPath,"graphics","gear.svg"))
        self.svgGradient = QSvgWidget(self.gradPath)
        self.svgGradient.setFixedSize(QSize(64,64))

        self.setLayout(self.outerBox)
        self.outerBox.addWidget(self.svgGradient, 0, Qt.AlignTop)
        self.outerBox.addLayout(self.innerBox)

        self.mainGroup = QGroupBox("Item Settings")
        self.mainForm  = QFormLayout()

        self.editName   = QLineEdit()
        self.editStatus = QComboBox()
        self.editLayout = QComboBox()

        if self.theItem.itemClass == nwItemClass.NOVEL:
            for sLabel, _, _ in self.theProject.statusItems:
                self.editStatus.addItem(
                    self.theParent.statusIcons[sLabel], sLabel, sLabel
                )
        else:
            for sLabel, _, _ in self.theProject.importItems:
                self.editStatus.addItem(
                    self.theParent.importIcons[sLabel], sLabel, sLabel
                )

        self.validLayouts = []
        if self.theItem.itemType == nwItemType.FILE:
            if self.theItem.itemClass == nwItemClass.NOVEL:
                self.validLayouts.append(nwItemLayout.TITLE)
                self.validLayouts.append(nwItemLayout.BOOK)
                self.validLayouts.append(nwItemLayout.PAGE)
                self.validLayouts.append(nwItemLayout.PARTITION)
                self.validLayouts.append(nwItemLayout.UNNUMBERED)
                self.validLayouts.append(nwItemLayout.CHAPTER)
                self.validLayouts.append(nwItemLayout.SCENE)
                self.validLayouts.append(nwItemLayout.NOTE)
            else:
                self.validLayouts.append(nwItemLayout.NOTE)
        else:
            self.validLayouts.append(nwItemLayout.NO_LAYOUT)

        for itemLayout in nwItemLayout:
            if itemLayout in self.validLayouts:
                self.editLayout.addItem(nwLabels.LAYOUT_NAME[itemLayout],itemLayout)

        self.mainForm.addRow("Name",   self.editName)
        self.mainForm.addRow("Status", self.editStatus)
        self.mainForm.addRow("Layout", self.editLayout)

        self.editName.setMinimumWidth(200)

        self.editName.setText(self.theItem.itemName)
        statusIdx = self.editStatus.findData(self.theItem.itemStatus)
        if statusIdx != -1:
            self.editStatus.setCurrentIndex(statusIdx)
        layoutIdx = self.editLayout.findData(self.theItem.itemLayout)
        if layoutIdx != -1:
            self.editLayout.setCurrentIndex(layoutIdx)

        self.buttonBox = QHBoxLayout()
        self.closeButton = QPushButton("Close")
        self.closeButton.clicked.connect(self._doClose)
        self.saveButton = QPushButton("Save")
        self.saveButton.setDefault(True)
        self.saveButton.clicked.connect(self._doSave)
        self.buttonBox.addStretch(1)
        self.buttonBox.addWidget(self.closeButton)
        self.buttonBox.addWidget(self.saveButton)

        self.mainGroup.setLayout(self.mainForm)
        self.innerBox.addWidget(self.mainGroup)
        self.innerBox.addLayout(self.buttonBox)

        self.show()

        self.editName.selectAll()

        logger.debug("ItemEditor initialisation complete")

        return

    def _doSave(self):
        logger.verbose("ItemEditor save button clicked")
        itemName   = self.editName.text()
        itemStatus = self.editStatus.currentData()
        itemLayout = self.editLayout.currentData()
        self.theItem.setName(itemName)
        self.theItem.setStatus(itemStatus)
        self.theItem.setLayout(itemLayout)
        self.theProject.setProjectChanged(True)
        self.accept()
        self.close()
        return

    def _doClose(self):
        logger.verbose("ItemEditor close button clicked")
        self.reject()
        self.close()
        return
示例#12
0
class GuiProjectEditor(QDialog):
    def __init__(self, theParent, theProject):
        QDialog.__init__(self, theParent)

        logger.debug("Initialising ProjectEditor ...")

        self.mainConf = nw.CONFIG
        self.theParent = theParent
        self.theProject = theProject

        self.outerBox = QHBoxLayout()
        self.innerBox = QVBoxLayout()
        self.setWindowTitle("Project Settings")
        self.setLayout(self.outerBox)

        self.gradPath = path.abspath(
            path.join(self.mainConf.appPath, "graphics", "gear.svg"))
        self.svgGradient = QSvgWidget(self.gradPath)
        self.svgGradient.setFixedSize(QSize(64, 64))

        self.theProject.countStatus()
        self.tabMain = GuiProjectEditMain(self.theParent, self.theProject)
        self.tabStatus = GuiProjectEditStatus(self.theParent,
                                              self.theProject.statusItems)
        self.tabImport = GuiProjectEditStatus(self.theParent,
                                              self.theProject.importItems)
        self.tabReplace = GuiProjectEditReplace(self.theParent,
                                                self.theProject)

        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.tabMain, "Settings")
        self.tabWidget.addTab(self.tabStatus, "Status")
        self.tabWidget.addTab(self.tabImport, "Importance")
        self.tabWidget.addTab(self.tabReplace, "Auto-Replace")

        self.outerBox.addWidget(self.svgGradient, 0, Qt.AlignTop)
        self.outerBox.addLayout(self.innerBox)

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.accepted.connect(self._doSave)
        self.buttonBox.rejected.connect(self._doClose)

        self.innerBox.addWidget(self.tabWidget)
        self.innerBox.addWidget(self.buttonBox)

        self.show()

        logger.debug("ProjectEditor initialisation complete")

        return

    def _doSave(self):
        logger.verbose("ProjectEditor save button clicked")

        projName = self.tabMain.editName.text()
        bookTitle = self.tabMain.editTitle.text()
        bookAuthors = self.tabMain.editAuthors.toPlainText()
        doBackup = self.tabMain.doBackup.isChecked()
        self.theProject.setProjectName(projName)
        self.theProject.setBookTitle(bookTitle)
        self.theProject.setBookAuthors(bookAuthors)
        self.theProject.setProjBackup(doBackup)

        if self.tabStatus.colChanged:
            statusCol = self.tabStatus.getNewList()
            self.theProject.setStatusColours(statusCol)
        if self.tabImport.colChanged:
            importCol = self.tabImport.getNewList()
            self.theProject.setImportColours(importCol)
        if self.tabStatus.colChanged or self.tabImport.colChanged:
            self.theParent.rebuildTree()
        if self.tabReplace.arChanged:
            newList = self.tabReplace.getNewList()
            self.theProject.setAutoReplace(newList)

        self.close()

        return

    def _doClose(self):
        logger.verbose("ProjectEditor close button clicked")
        self.close()
        return
class FileHistoryWidget(QWidget, Ui_FileHistoryWidget):
    get_versions_success = pyqtSignal()
    get_versions_error = pyqtSignal()

    def __init__(
        self,
        jobs_ctx,
        workspace_fs,
        path,
        reload_timestamped_signal,
        update_version_list,
        close_version_list,
    ):
        super().__init__()
        self.setupUi(self)
        self.jobs_ctx = jobs_ctx
        update_version_list.connect(self.reset_dialog)
        self.get_versions_success.connect(self.on_get_version_success)
        self.get_versions_error.connect(self.on_get_version_error)
        self.button_load_more_entries.clicked.connect(self.load_more)
        self.workspace_fs = workspace_fs
        self.version_lister = workspace_fs.get_version_lister()
        self.spinner = QSvgWidget(":/icons/images/icons/spinner.svg")
        self.spinner.setFixedSize(100, 100)
        self.spinner_layout.addWidget(self.spinner, Qt.AlignCenter)
        self.spinner_layout.setAlignment(Qt.AlignCenter)
        self.set_loading_in_progress(False)
        self.reset_dialog(workspace_fs, self.version_lister, path)

    def set_loading_in_progress(self, in_progress: bool):
        self.loading_in_progress = in_progress
        self.area_list.setVisible(not in_progress)
        self.spinner_frame.setVisible(in_progress)

    def reset_dialog(self, workspace_fs, version_lister, path):
        if self.loading_in_progress:
            return
        self.set_loading_in_progress(True)
        self.workspace_fs = workspace_fs
        self.path = path
        self.reset_list()

    def load_more(self):
        if self.loading_in_progress:
            return
        self.set_loading_in_progress(True)
        self.reset_list()

    def reset_list(self):
        while self.layout_history.count() != 0:
            item = self.layout_history.takeAt(0)
            if item:
                w = item.widget()
                self.layout_history.removeWidget(w)
                w.hide()
                w.setParent(0)
        self.versions_job = self.jobs_ctx.submit_job(
            ThreadSafeQtSignal(self, "get_versions_success"),
            ThreadSafeQtSignal(self, "get_versions_error"),
            _do_workspace_version,
            version_lister=self.version_lister,
            path=self.path,
        )

    def add_history_item(self, version, path, creator, size, timestamp,
                         src_path, dst_path):
        button = FileHistoryButton(
            version=version,
            creator=creator,
            name=path,
            size=size,
            src=src_path,
            dst=dst_path,
            timestamp=timestamp,
        )
        self.layout_history.addWidget(button)
        button.show()

    def on_get_version_success(self):
        versions_list, download_limit_reached = self.versions_job.ret
        if download_limit_reached:
            self.button_load_more_entries.setVisible(False)
        self.versions_job = None
        for v in versions_list:
            self.add_history_item(
                version=v.version,
                path=self.path,
                creator=v.creator,
                size=v.size,
                timestamp=v.early,
                src_path=v.source,
                dst_path=v.destination,
            )
        self.set_loading_in_progress(False)

    def on_get_version_error(self):
        if self.versions_job and self.versions_job.status != "cancelled":
            show_error(self,
                       _("TEXT_FILE_HISTORY_LIST_FAILURE"),
                       exception=self.versions_job.exc)
        self.versions_job = None
        self.reject()

    def on_close(self):
        if self.versions_job:
            self.versions_job.cancel_and_join()

    @classmethod
    def exec_modal(
        cls,
        jobs_ctx,
        workspace_fs,
        path,
        reload_timestamped_signal,
        update_version_list,
        close_version_list,
        parent,
    ):
        w = cls(
            jobs_ctx=jobs_ctx,
            workspace_fs=workspace_fs,
            path=path,
            reload_timestamped_signal=reload_timestamped_signal,
            update_version_list=update_version_list,
            close_version_list=close_version_list,
        )
        d = GreyedDialog(
            w,
            title=_("TEXT_FILE_HISTORY_TITLE_name").format(name=path.name),
            parent=parent)
        return d.exec_()
示例#14
0
    def init_ui(self):
        # 1) Logo & heading
        logo_label = QSvgWidget(get_path_temporary('logo.svg'))
        logo_label.setFixedSize(100, 28)

        # 1) Enter API key section
        api_key_field_label = F1QLabel(text="1) Enter your API key",
                                       object_name="apiKeyFieldLabel")
        api_key_help_text_label = F1QLabel(
            text=
            "You can find your API key on the <a href='https://www.f1laps.com/telemetry'>F1Laps Telemetry page</a>",
            object_name="apiKeyHelpTextLabel")
        self.api_key_field = QLineEdit()
        self.api_key_field.setObjectName("apiKeyField")
        self.api_key_field.setText(self.api_key)

        # 2) Check IP section
        ip_value_label = F1QLabel(
            text="2) Set your F1 game Telemetry settings",
            object_name="ipValueLabel")
        ip_value_help_text_label = F1QLabel(
            text=
            "Open the F1 Game Settings -> Telemetry and set the IP to this value:",
            object_name="ipValueHelpTextLabel")
        self.ip_value = F1QLabel(object_name="ipValueField")
        self.ip_value.setContentsMargins(0, 0, 0, 5)
        self.port_value_help_text_label = F1QLabel(
            text=
            "Set the port to this value (anything from 1024 to 49151, default is %s): "
            % DEFAULT_PORT,
            object_name="udpBroadcastHelpTextLabel")
        self.port_value_field = QLineEdit()
        self.port_value_field.setObjectName("portValueField")
        self.port_value_field.setText(self.port_value)

        udp_broadcast_help_text_label = F1QLabel(
            text="Alternatively you can set and use UDP broadcast mode:",
            object_name="udpBroadcastHelpTextLabel")
        self.udp_broadcast_checkbox = QCheckBox("Use UDP broadcast mode")
        self.udp_broadcast_checkbox.setChecked(self.broadcast_mode_enabled)

        # Start/Stop button section
        self.start_button = StartButton()
        self.start_button.clicked.connect(lambda: self.start_button_click())
        self.status_label = StatusLabel()

        # Support & notes section
        help_text_label = F1QLabel(
            text=
            "Need help? <a href='https://community.f1laps.com/c/telemetry-app-faqs'>Check out the FAQs!</a>",
            object_name="helpTextLabel")
        self.app_version_label = F1QLabel(text="You're using app version %s." %
                                          self.app_version,
                                          object_name="appVersionLabel")
        self.subscription_label = F1QLabel(text="",
                                           object_name="subscriptionLabel")

        # Draw layout
        self.layout = QVBoxLayout()

        # Logo section
        self.layout.addWidget(logo_label, alignment=Qt.AlignCenter)
        self.layout.addWidget(QHSeperationLine())

        # API key section
        #self.layout.addWidget(QVSpacer(0))
        self.layout.addWidget(api_key_field_label)
        self.layout.addWidget(api_key_help_text_label)
        self.layout.addWidget(self.api_key_field)

        # Telemetry settings
        self.layout.addWidget(QVSpacer(0.5))
        self.layout.addWidget(QHSeperationLine())
        self.layout.addWidget(QVSpacer(0.5))
        self.layout.addWidget(ip_value_label)
        self.layout.addWidget(ip_value_help_text_label)
        self.layout.addWidget(self.ip_value)
        self.layout.addWidget(self.port_value_help_text_label)
        self.layout.addWidget(self.port_value_field)
        self.layout.addWidget(udp_broadcast_help_text_label)
        self.layout.addWidget(self.udp_broadcast_checkbox)

        # Start button
        self.layout.addWidget(QVSpacer(1))
        self.layout.addWidget(QHSeperationLine())
        self.layout.addWidget(QVSpacer(5))
        self.layout.addWidget(self.start_button, alignment=Qt.AlignCenter)
        self.layout.addWidget(self.status_label, alignment=Qt.AlignCenter)

        # Status & help
        self.layout.addWidget(QVSpacer(1))
        self.layout.addWidget(QHSeperationLine())
        self.layout.addWidget(help_text_label)
        self.layout.addWidget(self.app_version_label)
        self.layout.addWidget(self.subscription_label)
        self.layout.setContentsMargins(30, 20, 30, 10)

        self.setLayout(self.layout)
        self.setFixedWidth(420)
        self.setWindowTitle("F1Laps Telemetry")
示例#15
0
class DropArea(QPushButton):
    Stylesheet = """
    QLineEdit, QLabel, QTabWidget {
        font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;
    }

    QLineEdit, QSpinBox {
        border: 1px solid #cbcbcb;
        border-radius: 2px;
        background: white;
        min-width: 31px;
        min-height: 21px;
    }
    QLineEdit:focus, QSpinBox:focus {
        border-color: rgb(139, 173, 228);
    }
    QPushButton {
        border: 2px solid #cbcbcb;
        border-radius: 10px;
        border-style: dashed;
        font-size: 16px;
        background: white;
    }
    QPushButton:hover {
        border-color: rgb(139, 173, 228);
    }
    QPushButton:pressed {
        color: #cbcbcb;
    }
    """

    changed = pyqtSignal(QMimeData)

    def __init__(self, loadNewAnimation_signal: pyqtSignal, parent=None):
        super(DropArea, self).__init__(parent,
                                       cursor=Qt.PointingHandCursor,
                                       toolTip='Import animation',
                                       clicked=self.searchFile)

        self.loadNewAnimation_signal = loadNewAnimation_signal

        self.setMinimumSize(self.screen().size() / 4)
        self.setAcceptDrops(True)
        self.setAutoFillBackground(True)
        self.clear()
        self.setStyleSheet(self.Stylesheet)

        layout = QGridLayout(self)
        self.setLayout(layout)

        self.svgWidget = QSvgWidget(':/UI/DropFileZone.svg')
        self.svgWidget.setFixedSize(200, 200)
        layout.addWidget(self.svgWidget)

    def dragEnterEvent(self, event):
        self.setBackgroundRole(QPalette.Highlight)

        if self.isAnimation(event.mimeData()):
            event.acceptProposedAction()
        self.changed.emit(event.mimeData())

    def dragMoveEvent(self, event):
        event.acceptProposedAction()

    def dropEvent(self, event):
        mimeData = event.mimeData()
        if self.isAnimation(mimeData):
            self.loadNewAnimation_signal.emit(mimeData.text()[8:])
        self.setBackgroundRole(QPalette.Dark)
        event.acceptProposedAction()

    def dragLeaveEvent(self, event):
        self.clear()
        event.accept()

    def clear(self):
        self.setBackgroundRole(QPalette.Dark)
        self.changed.emit(None)

    def isAnimation(self, file: QMimeData):
        if file.hasText():
            return file.text()[-5:] == '.anim'
        return False

    def resizeEvent(self, event):
        h = self.size().height()
        w = self.size().width()
        self.svgWidget.setFixedSize(min(h, w) * 0.8, min(h, w) * 0.8)

    def searchFile(self):
        directoryName, fileExtension = QFileDialog.getOpenFileName(
            self, 'Load animation', "./", "Animation Files (*.anim)")
        self.loadNewAnimation_signal.emit(directoryName)