예제 #1
1
    def load(self, path):
        self._path = path

        with open(os.path.join(self._path, "theme.json")) as f:
            data = json.load(f)

        self._initializeDefaults()

        if "colors" in data:
            for name, color in data["colors"].items():
                c = QColor(color[0], color[1], color[2], color[3])
                self._colors[name] = c

        fontsdir = os.path.join(self._path, "fonts")
        if os.path.isdir(fontsdir):
            for file in os.listdir(fontsdir):
                if "ttf" in file:
                    QFontDatabase.addApplicationFont(
                        os.path.join(fontsdir, file))

        if "fonts" in data:
            for name, font in data["fonts"].items():
                f = QFont()

                if not sys.platform == "win32":
                    # Excluding windows here as a workaround for bad font rendering
                    f.setFamily(
                        font.get("family",
                                 QCoreApplication.instance().font().family()))

                f.setStyleName(font.get("style", "Regular"))
                f.setBold(font.get("bold", False))
                f.setLetterSpacing(QFont.AbsoluteSpacing,
                                   font.get("letterSpacing", 0))
                f.setItalic(font.get("italic", False))
                f.setPixelSize(font.get("size", 1) * self._em_height)
                f.setCapitalization(QFont.AllUppercase if font.get(
                    "capitalize", False) else QFont.MixedCase)

                self._fonts[name] = f

        if "sizes" in data:
            for name, size in data["sizes"].items():
                s = QSizeF()
                s.setWidth(round(size[0] * self._em_width))
                s.setHeight(round(size[1] * self._em_height))

                self._sizes[name] = s

        styles = os.path.join(self._path, "styles.qml")
        if os.path.isfile(styles):
            c = QQmlComponent(self._engine, styles)
            self._styles = c.create()

            if c.isError():
                for error in c.errors():
                    Logger.log("e", error.toString())

        iconsdir = os.path.join(self._path, "icons")
        if os.path.isdir(iconsdir):
            for icon in os.listdir(iconsdir):
                name = os.path.splitext(icon)[0]
                self._icons[name] = QUrl.fromLocalFile(
                    os.path.join(iconsdir, icon))

        imagesdir = os.path.join(self._path, "images")
        if os.path.isdir(imagesdir):
            for image in os.listdir(imagesdir):
                name = os.path.splitext(image)[0]
                self._images[name] = QUrl.fromLocalFile(
                    os.path.join(imagesdir, image))

        Logger.log("d", "Loaded theme %s", self._path)
        self.themeLoaded.emit()
예제 #2
0
    def registerObjects(self, engine):
        engine.rootContext().setContextProperty("Printer", self)
        engine.rootContext().setContextProperty("CuraApplication", self)
        self._print_information = PrintInformation.PrintInformation()
        engine.rootContext().setContextProperty("PrintInformation", self._print_information)
        self._cura_actions = CuraActions.CuraActions(self)
        engine.rootContext().setContextProperty("CuraActions", self._cura_actions)

        qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")

        qmlRegisterType(cura.Settings.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")

        qmlRegisterType(cura.Settings.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
        qmlRegisterType(cura.Settings.MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")

        qmlRegisterSingletonType(cura.Settings.ContainerManager, "Cura", 1, 0, "ContainerManager", cura.Settings.ContainerManager.createContainerManager)

        qmlRegisterSingletonType(QUrl.fromLocalFile(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")), "Cura", 1, 0, "Actions")

        engine.rootContext().setContextProperty("ExtruderManager", cura.Settings.ExtruderManager.getInstance())

        for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
            type_name = os.path.splitext(os.path.basename(path))[0]
            if type_name in ("Cura", "Actions"):
                continue

            qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
예제 #3
0
def test_addGetDisplayComponent():
    stage = Stage()
    stage.addDisplayComponent("BLORP", "location")
    assert stage.getDisplayComponent("BLORP") == QUrl.fromLocalFile("location")

    stage.addDisplayComponent("MEEP!", QUrl.fromLocalFile("MEEP"))
    assert stage.getDisplayComponent("MEEP!") == QUrl.fromLocalFile("MEEP")
예제 #4
0
    def registerObjects(self, engine):
        engine.rootContext().setContextProperty("Printer", self)
        engine.rootContext().setContextProperty("CuraApplication", self)
        self._print_information = PrintInformation.PrintInformation()
        engine.rootContext().setContextProperty("PrintInformation", self._print_information)
        self._cura_actions = CuraActions.CuraActions(self)
        engine.rootContext().setContextProperty("CuraActions", self._cura_actions)

        qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")

        qmlRegisterType(cura.Settings.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")

        qmlRegisterType(cura.Settings.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
        qmlRegisterSingletonType(cura.Settings.ProfilesModel, "Cura", 1, 0, "ProfilesModel", cura.Settings.ProfilesModel.createProfilesModel)
        qmlRegisterType(cura.Settings.QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
        qmlRegisterType(cura.Settings.UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
        qmlRegisterType(cura.Settings.MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
        qmlRegisterType(cura.Settings.QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
        qmlRegisterType(cura.Settings.MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")

        qmlRegisterSingletonType(cura.Settings.ContainerManager, "Cura", 1, 0, "ContainerManager", cura.Settings.ContainerManager.createContainerManager)

        # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
        actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
        qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")

        engine.rootContext().setContextProperty("ExtruderManager", cura.Settings.ExtruderManager.getInstance())

        for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
            type_name = os.path.splitext(os.path.basename(path))[0]
            if type_name in ("Cura", "Actions"):
                continue

            qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
예제 #5
0
def fuzzy_url(urlstr):
    """Get a QUrl based on an user input which is URL or search term.

    Args:
        urlstr: URL to load as a string.

    Return:
        A target QUrl to a searchpage or the original URL.
    """
    path = os.path.abspath(os.path.expanduser(urlstr))
    stripped = urlstr.strip()
    if os.path.exists(path):
        log.url.debug("URL is a local file")
        url = QUrl.fromLocalFile(path)
    elif (not _has_explicit_scheme(QUrl(urlstr)) and
            os.path.exists(os.path.abspath(path))):
        # We do this here rather than in the first block because we first want
        # to make sure it's not an URL like http://, because os.path.abspath
        # would mangle that.
        log.url.debug("URL is a relative local file")
        url = QUrl.fromLocalFile(os.path.abspath(path))
    elif is_url(stripped):
        # probably an address
        log.url.debug("URL is a fuzzy address")
        url = qurl_from_user_input(urlstr)
    else:  # probably a search term
        log.url.debug("URL is a fuzzy search term")
        try:
            url = _get_search_url(urlstr)
        except ValueError:  # invalid search engine
            url = qurl_from_user_input(stripped)
    log.url.debug("Converting fuzzy term {} to URL -> {}".format(
                  urlstr, url.toDisplayString()))
    qtutils.ensure_valid(url)
    return url
예제 #6
0
def url(arg):
    """Converts a filename-like argument to a QUrl."""
    if re.match(r'^(https?|s?ftp)://', arg):
        return QUrl(arg)
    elif arg.startswith('file://'):
        return QUrl.fromLocalFile(os.path.abspath(arg[7:]))
    elif arg.startswith('file:'):
        return QUrl.fromLocalFile(os.path.abspath(arg[5:]))
    else:
        return QUrl.fromLocalFile(os.path.abspath(arg))
예제 #7
0
def test_iconSource():
    stage = Stage()

    # Should be empty if we didn't do anything yet
    assert stage.iconSource == QUrl()

    stage.setIconSource("DERP")
    assert stage.iconSource == QUrl.fromLocalFile("DERP")

    stage.setIconSource(QUrl.fromLocalFile("FOO"))
    assert stage.iconSource == QUrl.fromLocalFile("FOO")
예제 #8
0
    def test_activeToolPanel(self):
        # There is no active tool, so it should be empty
        assert self.proxy.activeToolPanel == QUrl()

        with patch("UM.PluginRegistry.PluginRegistry.getMetaData", MagicMock(return_value={"tool": {"tool_panel": "derp"}})):
            with patch("UM.PluginRegistry.PluginRegistry.getPluginPath", MagicMock(return_value = "OMG")):
                Application.getInstance().getController().setActiveTool(self.tool)
                assert self.proxy.activeToolPanel == QUrl.fromLocalFile("OMG/derp")
        # Try again with empty metadata
        with patch("UM.PluginRegistry.PluginRegistry.getMetaData", MagicMock(return_value={"tool": {}})):
            Application.getInstance().getController().setActiveTool("")
            Application.getInstance().getController().setActiveTool(self.tool)
            assert self.proxy.activeToolPanel == QUrl.fromLocalFile("")
예제 #9
0
    def createDocument(self, filename, contents):
        """Create a new document using the specified filename and contents.

        Make it the current document in our mainwindow.

        """
        while os.path.exists(filename) or app.findDocument(QUrl.fromLocalFile(filename)):
            filename = util.next_file(filename)
        doc = app.openUrl(QUrl())
        doc.setPlainText(contents)
        doc.setUrl(QUrl.fromLocalFile(filename))
        doc.setModified(True)
        self.mainwindow().setCurrentDocument(doc)
        return doc       
예제 #10
0
파일: ChangeLog.py 프로젝트: Patola/Cura
    def createChangelogWindow(self):
        path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "ChangeLog.qml"))

        component = QQmlComponent(Application.getInstance()._engine, path)
        self._changelog_context = QQmlContext(Application.getInstance()._engine.rootContext())
        self._changelog_context.setContextProperty("manager", self)
        self._changelog_window = component.create(self._changelog_context)
예제 #11
0
 def __open(self):
     """
     Private slot to open the downloaded file.
     """
     info = QFileInfo(self.__output)
     url = QUrl.fromLocalFile(info.absoluteFilePath())
     QDesktopServices.openUrl(url)
예제 #12
0
 def speak(self, name, text, lang="pt-br"):
     fpath = "./speeches/" + name + ".mp3"
     if not os.path.isdir("./speeches"):
         os.mkdir("./speeches")
     if not os.path.isfile(fpath):
         print("Running TTS...")
         try:
             data = urlencode( [("tl", lang), ("q", text), ("ie", "UTF-8")] )
             bin_data = data.encode("utf8")
             req = Request("http://translate.google.com/translate_tts", bin_data, {"User-Agent":"My agent !"})
             fin = urlopen(req)
             mp3 = fin.read()
             fout = open(fpath, "wb")
             fout.write(mp3)
             fout.close()
         except Exception as exc:
             print("Error trying to get TTS file:", str(exc))
             if self.backup != None:
                 print("Proceeding to use backup speaker...")
                 self.backup.speak(text)
             return
     
     self.player.stop()
     self.player.setMedia(QMediaContent(QUrl.fromLocalFile(QFileInfo(fpath).absoluteFilePath())))
     self.player.play()
예제 #13
0
 def openFolder(self):
     """
     Public slot to open the folder containing the downloaded file.
     """
     info = QFileInfo(self.__fileName)
     url = QUrl.fromLocalFile(info.absolutePath())
     QDesktopServices.openUrl(url)
예제 #14
0
def fuzzy_url(urlstr, cwd=None):
    """Get a QUrl based on an user input which is URL or search term.

    Args:
        urlstr: URL to load as a string.
        cwd: The current working directory, or None.

    Return:
        A target QUrl to a searchpage or the original URL.
    """
    if cwd:
        path = os.path.join(cwd, os.path.expanduser(urlstr))
    else:
        try:
            path = os.path.abspath(os.path.expanduser(urlstr))
        except OSError:
            path = None
    stripped = urlstr.strip()
    if path is not None and os.path.exists(path):
        log.url.debug("URL is a local file")
        url = QUrl.fromLocalFile(path)
    elif is_url(stripped):
        # probably an address
        log.url.debug("URL is a fuzzy address")
        url = qurl_from_user_input(urlstr)
    else:  # probably a search term
        log.url.debug("URL is a fuzzy search term")
        try:
            url = _get_search_url(urlstr)
        except ValueError:  # invalid search engine
            url = qurl_from_user_input(stripped)
    log.url.debug("Converting fuzzy term {} to URL -> {}".format(
                  urlstr, url.toDisplayString()))
    qtutils.ensure_valid(url)
    return url
예제 #15
0
def file_url(path):
    """Return a file:// url (as string) to the given local path.

    Arguments:
        path: The absolute path to the local file
    """
    return QUrl.fromLocalFile(path).toString(QUrl.FullyEncoded)
예제 #16
0
def test_parent_in_root_dir(dir_layout, quteproc):
    # This actually works on windows
    root_path = os.path.realpath('/')
    urlstr = QUrl.fromLocalFile(root_path).toString(QUrl.FullyEncoded)
    quteproc.open_url(urlstr)
    page = parse(quteproc)
    assert page.parent is None
예제 #17
0
 def setData(self, xx, yy, region):
     data = ','.join(["['%s', %d]" % (x, y) for x, y in zip(xx, yy)])
     header = "['%s', '%s']" % (self.tr("Country"), self.tr("Number of coins"))
     data = ','.join((header, data))
     locale = Settings()['locale']
     self.html_data = self.HTML % (locale, MAPS_API_KEY, region, data)
     self.setHtml(self.html_data, QUrl.fromLocalFile(OpenNumismat.PRJ_PATH))
예제 #18
0
파일: SpeedDial.py 프로젝트: Darriall/eric
 def initialScript(self):
     """
     Public method to get the 'initial' JavaScript script.
     
     @return initial JavaScript script (string)
     """
     if self.__regenerateScript:
         self.__regenerateScript = False
         self.__initialScript = ""
         
         for page in self.__webPages:
             if page.broken:
                 imgSource = "qrc:icons/brokenPage.png"
             else:
                 imgSource = self.__imageFileName(page.url)
                 if not os.path.exists(imgSource):
                     self.loadThumbnail(page.url)
                     imgSource = "qrc:icons/loading.gif"
                     
                     if not page.url:
                         imgSource = ""
                 else:
                     imgSource = QUrl.fromLocalFile(imgSource).toString()
             
             self.__initialScript += \
                 "addBox('{0}', '{1}', '{2}');\n".format(
                     page.url, Utilities.html_uencode(page.title),
                     imgSource)
     
     return self.__initialScript
예제 #19
0
 def showMutiPlaylistDialog(self, _id, _type):
     self._id = _id
     self._type = _type
     self.setSource(QUrl.fromLocalFile(
         os.path.join(get_parent_dir(__file__, 2), 'views','dialogs' ,'MutiPlaylistChoseDialog.qml')))
     self.moveCenter()
     self.show()
예제 #20
0
    def open_file(self, cmdline=None):
        """Open the downloaded file.

        Args:
            cmdline: The command to use as string. A `{}` is expanded to the
                     filename. None means to use the system's default
                     application. If no `{}` is found, the filename is appended
                     to the cmdline.
        """
        assert self.successful
        filename = self._get_open_filename()
        if filename is None:  # pragma: no cover
            log.downloads.error("No filename to open the download!")
            return

        if cmdline is None:
            log.downloads.debug("Opening {} with the system application"
                                .format(filename))
            url = QUrl.fromLocalFile(filename)
            QDesktopServices.openUrl(url)
            return

        cmd, *args = shlex.split(cmdline)
        args = [arg.replace('{}', filename) for arg in args]
        if '{}' not in cmdline:
            args.append(filename)
        log.downloads.debug("Opening {} with {}"
                            .format(filename, [cmd] + args))
        proc = guiprocess.GUIProcess(what='download')
        proc.start_detached(cmd, args)
예제 #21
0
 def test_file(self, tmpdir):
     filename = tmpdir / 'foo'
     filename.ensure()
     url = QUrl.fromLocalFile(str(filename))
     req = QNetworkRequest(url)
     reply = filescheme.handler(req, None, None)
     assert reply is None
예제 #22
0
파일: webkit.py 프로젝트: moredain/zp
def PdfConverter(username):

        htmllink = "bootstrap_mod/usertemp/"+username+".html"
        app1 = QApplication(sys.argv)

        web = QWebView()

        link =QUrl.fromLocalFile(QFileInfo(htmllink).absoluteFilePath())

        web.load(QUrl(link))

        printer = QPrinter()
        printer.setPageSize(QPrinter.A4)
        printer.setOutputFormat(QPrinter.PdfFormat)
        Pdf_Generated_Name="bootstrap_mod/usertemp/"+username+".pdf"
        printer.setOutputFileName(Pdf_Generated_Name)

        web.print(printer)
        QApplication.exit()
        def convertIt():
                web.print(printer)
                print("Pdf generated")
                QApplication.exit()

        web.loadFinished.connect(convertIt)
        sys.exit(app1.exec_())
        return 0
예제 #23
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.log = logging.getLogger(__name__)
        self._read_settings()

        self.client = Client(self)

        if self.remember:
            self._autologin()

        self.model = MainWindowViewModel(self)
        self.loginModel = LoginViewModel(self.client, self.user, self.password, self.remember, self)
        self.loginModel.panel_visible = not self.remember
        self.gamesModel = GamesViewModel(self)

        self.engine = QQmlApplicationEngine(self)
        self.engine.rootContext().setContextProperty('windowModel', self.model)
        self.engine.rootContext().setContextProperty('loginModel', self.loginModel)
        self.engine.rootContext().setContextProperty('contentModel', self.gamesModel)
        self.engine.quit.connect(parent.quit)
        self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml'))

        self.window = self.engine.rootObjects()[0]

        # wire up logging console
        self.console = self.window.findChild(QQuickItem, 'console')
        parent.log_changed.connect(self._log)
예제 #24
0
    def __init__(self, buffer_id, buffer_width, buffer_height):
        super(BrowserBuffer, self).__init__()

        self.buffer_id = buffer_id
        self.buffer_width = buffer_width
        self.buffer_height = buffer_height

        self.setPage(WebPage())
        self.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        cookie_jar.restore_cookies()
        self.page().networkAccessManager().setCookieJar(cookie_jar)
        self.page().userAgentForUrl = self.customize_user_agent
        self.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(os.path.join(get_parent_dir(__file__), "theme.css")))
        self.settings().setAttribute(QWebSettings.PluginsEnabled, True)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
        self.settings().setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
        self.settings().setFontFamily(QWebSettings.StandardFont, "Sans")

        self.adjust_size(self.buffer_width, self.buffer_height)

        self.view_dict = {}

        self.titleChanged.connect(self.change_title)

        self.press_ctrl_flag = False
        
        self.loading_flag = False
        self.loading_percent = 0
        
        self.loadFinished.connect(self.handle_load_finished)
        self.loadStarted.connect(self.handle_load_started)
        self.loadProgress.connect(self.handle_load_progress)
예제 #25
0
 def __init__(self,parent=None):
     super(MainApplication, self).__init__(parent)
     #self.resize(1200, 900) # TODO update to get screen size for full
     
     self.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'qml/Display_rev_1.qml')))
     self.setupUpdateThread()  
     self.qml = self.rootObject()
예제 #26
0
    def initQMLContext(self):
        self.mainWindow.setContexts(contexts)
        self.mainWindow.setSource(QUrl.fromLocalFile(os.path.join(
            get_parent_dir(__file__, 2), 'views', 'Main.qml')))

        self.qmlDialog = QmlDialog(self.mainWindow.engine())
        self.mainWindow.setContext('QmlDialog', self.qmlDialog)
예제 #27
0
    def import_done(self):
        j = self._import_job
        conf_dlg = self._import_dialog
        conf_dlg.saveSettings()
        lyfile = os.path.splitext(self._import_file)[0] + ".ly"
        while (os.path.exists(lyfile)
            or app.findDocument(QUrl.fromLocalFile(lyfile))):
            lyfile = util.next_file(lyfile)
        shutil.move(j.output_file(), lyfile)

        doc = app.openUrl(QUrl.fromLocalFile(lyfile))
        doc.setModified(True)
        self.mainwindow().setCurrentDocument(doc)

        self.post_import(conf_dlg.get_post_settings(), doc)
        self.mainwindow().saveDocument(doc)
예제 #28
0
파일: MachineAction.py 프로젝트: 3d20/Cura
 def _createViewFromQML(self):
     path = QUrl.fromLocalFile(
         os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), self._qml_url))
     self._component = QQmlComponent(Application.getInstance()._engine, path)
     self._context = QQmlContext(Application.getInstance()._engine.rootContext())
     self._context.setContextProperty("manager", self)
     self._view = self._component.create(self._context)
예제 #29
0
파일: app.py 프로젝트: daleathan/moneyguru
 def showHelp(self):
     help_path = op.abspath(op.join(HELP_PATH, 'index.html'))
     if op.exists(help_path):
         url = QUrl.fromLocalFile(help_path)
     else:
         url = QUrl("https://www.hardcoded.net/moneyguru/help/en")
     QDesktopServices.openUrl(url)
예제 #30
0
 def qmlPath(self) -> "QUrl":
     plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
     if plugin_path is None:
         Logger.log("e", "Cannot create QML view: cannot find plugin path for plugin [%s]", self.getPluginId())
         return QUrl("")
     path = os.path.join(plugin_path, self._qml_url)
     return QUrl.fromLocalFile(path)
예제 #31
0
 def printMusic(self):
     doc = self.actionCollection.music_document_select.currentDocument()
     if doc and doc.document():
         ### temporarily disable printing on Mac OS X
         import sys
         if sys.platform.startswith('darwin'):
             from PyQt5.QtCore import QUrl
             from PyQt5.QtGui import QMessageBox
             result =  QMessageBox.warning(self.mainwindow(),
                 _("Print Music"), _(
                 "Unfortunately, this version of Frescobaldi is unable to print "
                 "PDF documents on Mac OS X due to various technical reasons.\n\n"
                 "Do you want to open the file in the default viewer for printing instead? "
                 "(remember to close it again to avoid access problems)\n\n"
                 "Choose Yes if you want that, No if you want to try the built-in "
                 "printing functionality anyway, or Cancel to cancel printing."),
                 QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
             if result == QMessageBox.Yes:
                 import helpers
                 helpers.openUrl(QUrl.fromLocalFile(doc.filename()), "pdf")
                 return
             elif result == QMessageBox.Cancel:
                 return
         ### end temporarily disable printing on Mac OS X
         import popplerprint
         popplerprint.printDocument(doc, self)
예제 #32
0
 def _showConfigurationFolder(self):
     path = Resources.getConfigStoragePath()
     QDesktopServices.openUrl(QUrl.fromLocalFile( path ))
예제 #33
0
 def getDefaultPath(self, key):
     default_path = Preferences.getInstance().getValue("local_file/%s" % key)
     return QUrl.fromLocalFile(default_path)
예제 #34
0
    def __init__(self):
        Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
        if not hasattr(sys, "frozen"):
            Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))

        self._open_file_queue = []  # Files to open when plug-ins are loaded.

        # Need to do this before ContainerRegistry tries to load the machines
        SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
        SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
        # this setting can be changed for each group in one-at-a-time mode
        SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
        SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)

        # From which stack the setting would inherit if not defined per object (handled in the engine)
        # AND for settings which are not settable_per_mesh:
        # which extruder is the only extruder this setting is obtained from
        SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1")

        # For settings which are not settable_per_mesh and not settable_per_extruder:
        # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
        SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")

        SettingDefinition.addSettingType("extruder", None, str, Validator)

        SettingFunction.registerOperator("extruderValues", cura.Settings.ExtruderManager.getExtruderValues)
        SettingFunction.registerOperator("extruderValue", cura.Settings.ExtruderManager.getExtruderValue)
        SettingFunction.registerOperator("resolveOrValue", cura.Settings.ExtruderManager.getResolveOrValue)

        ## Add the 4 types of profiles to storage.
        Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
        Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
        Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
        Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
        Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
        Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")

        ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer)
        ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer)
        ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer)
        ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer)
        ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack)
        ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack)

        ##  Initialise the version upgrade manager with Cura's storage paths.
        import UM.VersionUpgradeManager #Needs to be here to prevent circular dependencies.
        UM.VersionUpgradeManager.VersionUpgradeManager.getInstance().setCurrentVersions(
            {
                ("quality", UM.Settings.InstanceContainer.Version):    (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
                ("machine_stack", UM.Settings.ContainerStack.Version): (self.ResourceTypes.MachineStack, "application/x-uranium-containerstack"),
                ("preferences", UM.Preferences.Version):               (Resources.Preferences, "application/x-uranium-preferences"),
                ("user", UM.Settings.InstanceContainer.Version):       (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer")
            }
        )

        self._machine_action_manager = MachineActionManager.MachineActionManager()
        self._machine_manager = None    # This is initialized on demand.
        self._setting_inheritance_manager = None

        self._additional_components = {} # Components to add to certain areas in the interface

        super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType)

        self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))

        self.setRequiredPlugins([
            "CuraEngineBackend",
            "MeshView",
            "LayerView",
            "STLReader",
            "SelectionTool",
            "CameraTool",
            "GCodeWriter",
            "LocalFileOutputDevice"
        ])
        self._physics = None
        self._volume = None
        self._output_devices = {}
        self._print_information = None
        self._previous_active_tool = None
        self._platform_activity = False
        self._scene_bounding_box = AxisAlignedBox.Null

        self._job_name = None
        self._center_after_select = False
        self._camera_animation = None
        self._cura_actions = None
        self._started = False

        self._message_box_callback = None
        self._message_box_callback_arguments = []

        self._i18n_catalog = i18nCatalog("cura")

        self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
        self.getController().toolOperationStopped.connect(self._onToolOperationStopped)

        Resources.addType(self.ResourceTypes.QmlFiles, "qml")
        Resources.addType(self.ResourceTypes.Firmware, "firmware")

        self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))

        # Add empty variant, material and quality containers.
        # Since they are empty, they should never be serialized and instead just programmatically created.
        # We need them to simplify the switching between materials.
        empty_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
        empty_variant_container = copy.deepcopy(empty_container)
        empty_variant_container._id = "empty_variant"
        empty_variant_container.addMetaDataEntry("type", "variant")
        ContainerRegistry.getInstance().addContainer(empty_variant_container)
        empty_material_container = copy.deepcopy(empty_container)
        empty_material_container._id = "empty_material"
        empty_material_container.addMetaDataEntry("type", "material")
        ContainerRegistry.getInstance().addContainer(empty_material_container)
        empty_quality_container = copy.deepcopy(empty_container)
        empty_quality_container._id = "empty_quality"
        empty_quality_container.setName("Not supported")
        empty_quality_container.addMetaDataEntry("quality_type", "normal")
        empty_quality_container.addMetaDataEntry("type", "quality")
        ContainerRegistry.getInstance().addContainer(empty_quality_container)
        empty_quality_changes_container = copy.deepcopy(empty_container)
        empty_quality_changes_container._id = "empty_quality_changes"
        empty_quality_changes_container.addMetaDataEntry("type", "quality_changes")
        ContainerRegistry.getInstance().addContainer(empty_quality_changes_container)

        # Set the filename to create if cura is writing in the config dir.
        self._config_lock_filename = os.path.join(Resources.getConfigStoragePath(), CONFIG_LOCK_FILENAME)
        self.waitConfigLockFile()
        ContainerRegistry.getInstance().load()

        Preferences.getInstance().addPreference("cura/active_mode", "simple")
        Preferences.getInstance().addPreference("cura/recent_files", "")
        Preferences.getInstance().addPreference("cura/categories_expanded", "")
        Preferences.getInstance().addPreference("cura/jobname_prefix", True)
        Preferences.getInstance().addPreference("view/center_on_select", True)
        Preferences.getInstance().addPreference("mesh/scale_to_fit", True)
        Preferences.getInstance().addPreference("mesh/scale_tiny_meshes", True)

        for key in [
            "dialog_load_path",  # dialog_save_path is in LocalFileOutputDevicePlugin
            "dialog_profile_path",
            "dialog_material_path"]:

            Preferences.getInstance().addPreference("local_file/%s" % key, os.path.expanduser("~/"))

        Preferences.getInstance().setDefault("local_file/last_used_type", "text/x-gcode")

        Preferences.getInstance().setDefault("general/visible_settings", """
            machine_settings
            resolution
                layer_height
            shell
                wall_thickness
                top_bottom_thickness
            infill
                infill_sparse_density
            material
                material_print_temperature
                material_bed_temperature
                material_diameter
                material_flow
                retraction_enable
            speed
                speed_print
                speed_travel
                acceleration_print
                acceleration_travel
                jerk_print
                jerk_travel
            travel
            cooling
                cool_fan_enabled
            support
                support_enable
                support_extruder_nr
                support_type
                support_interface_density
            platform_adhesion
                adhesion_type
                adhesion_extruder_nr
                brim_width
                raft_airgap
                layer_0_z_overlap
                raft_surface_layers
            dual
                prime_tower_enable
                prime_tower_size
                prime_tower_position_x
                prime_tower_position_y
            meshfix
            blackmagic
                print_sequence
                infill_mesh
            experimental
        """.replace("\n", ";").replace(" ", ""))

        JobQueue.getInstance().jobFinished.connect(self._onJobFinished)

        self.applicationShuttingDown.connect(self.saveSettings)
        self.engineCreatedSignal.connect(self._onEngineCreated)
        self._recent_files = []
        files = Preferences.getInstance().getValue("cura/recent_files").split(";")
        for f in files:
            if not os.path.isfile(f):
                continue

            self._recent_files.append(QUrl.fromLocalFile(f))
예제 #35
0
파일: config.py 프로젝트: lugrus2000/retext
 def openLink(self, link):
     QDesktopServices.openUrl(QUrl.fromLocalFile(link))
예제 #36
0
 def getDefaultPath(self) -> QUrl:
     return QUrl.fromLocalFile(os.path.expanduser("~/"))
예제 #37
0
    def __init__(self):

        Tk.__init__(self)

        self.geometry('%dx%d+100+100' % (1200, 600))
        self.title('Crowdtour')
        self.audioCount = 0
        self.WAVE_OUTPUT_FILENAME = ''
        self.button_list = []
        self.current_places = []

        app = QApplication(sys.argv)

        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)

        self.canvas.pack()
        self.canvas.place(relx=0, rely=0)
        self.bind("<Key>", self.check_quit)
        self.bind('<B1-Motion>', self.drag)
        self.bind('<Button-1>', self.click)

        self.label = Label(self.canvas)

        self.radiogroup = Frame(self.canvas)
        self.radiovar = IntVar()
        self.maptypes = ['roadmap', 'terrain', 'satellite', 'hybrid']
        self.add_radio_button('Road Map', 0)
        self.add_radio_button('Terrain', 1)
        self.add_radio_button('Satellite', 2)
        self.add_radio_button('Hybrid', 3)

        #input
        self.entry = Entry(self, bd=3)
        self.button = Button(self, text="Location", command=self.geolocation)
        self.button.place(relx=.18, rely=.90, anchor="c")
        self.entry.place(relx=.05, rely=.80)

        #buttons
        self.recordButton = Button(self, text="Record", command=self.record)
        self.recordButton.place(relx=.30, rely=.75, anchor="c")

        self.uploadButton = Button(self, text="Upload", command=self.upload)
        self.uploadButton.place(relx=.30, rely=.80, anchor="c")

        self.playButton = Button(self, text="Play", command=self.play)
        self.playButton.place(relx=.30, rely=.85, anchor="c")

        self.deleteButton = Button(self, text="Delete", command=self.delete)
        self.deleteButton.place(relx=.30, rely=.90, anchor="c")
        ### adding part here ###
        self.sound = QSoundEffect()
        # This is where you set default sound source
        if not os.path.exists('sounds'):
            os.makedirs('sounds')

        defaultBytes = b'27\xe5\xb2\x81\xe5'
        waveTest = wave.open(os.path.join('sounds', 'DefaultSound.wav'), 'w')
        waveTest.setparams((2, 2, 44100, 440320, 'NONE', 'not compressed'))
        waveTest.writeframes(defaultBytes)

        self.sound.setSource(
            QUrl.fromLocalFile(os.path.join('sounds', 'DefaultSound.wav')))

        ### adding part here ###

        self.zoom_in_button = self.add_zoom_button('+', +1)
        self.zoom_out_button = self.add_zoom_button('-', -1)

        self.zoomlevel = ZOOM

        maptype_index = 0
        self.radiovar.set(maptype_index)
        MARKER = "markers=size:tiny|label:B|color:blue|" + str(
            LATITUDE) + "," + str(LONGITUDE)
        self.goompy = GooMPy(WIDTH, HEIGHT, LATITUDE, LONGITUDE, ZOOM, MAPTYPE,
                             MARKER)

        self.restart()
예제 #38
0
 def openFolder(self):
     myfolder = path.dirname(sys.argv[0])
     QDesktopServices.openUrl(QUrl.fromLocalFile(myfolder))
예제 #39
0
파일: Theme.py 프로젝트: situchen/Uranium
    def load(self, path: str, is_first_call: bool = True) -> None:
        if path == self._path:
            return

        with open(os.path.join(path, "theme.json"), encoding = "utf-8") as f:
            Logger.log("d", "Loading theme file: %s", os.path.join(path, "theme.json"))
            data = json.load(f)

        # Iteratively load inherited themes
        try:
            theme_id = data["metadata"]["inherits"]
            self.load(Resources.getPath(Resources.Themes, theme_id), is_first_call = False)
        except FileNotFoundError:
            Logger.log("e", "Could not find inherited theme %s", theme_id)
        except KeyError:
            pass  # No metadata or no inherits keyword in the theme.json file

        if "colors" in data:
            for name, color in data["colors"].items():
                c = QColor(color[0], color[1], color[2], color[3])
                self._colors[name] = c

        fonts_dir = os.path.join(path, "fonts")
        if os.path.isdir(fonts_dir):
            for root, dirnames, filenames in os.walk(fonts_dir):
                for filename in filenames:
                    if filename.lower().endswith(".ttf"):
                        QFontDatabase.addApplicationFont(os.path.join(root, filename))

        if "fonts" in data:
            system_font_size = QCoreApplication.instance().font().pointSize()
            for name, font in data["fonts"].items():
                q_font = QFont()
                q_font.setFamily(font.get("family", QCoreApplication.instance().font().family()))

                if font.get("bold"):
                    q_font.setBold(font.get("bold", False))
                else:
                    q_font.setWeight(font.get("weight", 50))

                q_font.setLetterSpacing(QFont.AbsoluteSpacing, font.get("letterSpacing", 0))
                q_font.setItalic(font.get("italic", False))
                q_font.setPointSize(int(font.get("size", 1) * system_font_size))
                q_font.setCapitalization(QFont.AllUppercase if font.get("capitalize", False) else QFont.MixedCase)

                self._fonts[name] = q_font

        if "sizes" in data:
            for name, size in data["sizes"].items():
                s = QSizeF()
                s.setWidth(round(size[0] * self._em_width))
                s.setHeight(round(size[1] * self._em_height))

                self._sizes[name] = s

        iconsdir = os.path.join(path, "icons")
        if os.path.isdir(iconsdir):
            for icon in os.listdir(iconsdir):
                name = os.path.splitext(icon)[0]
                self._icons[name] = QUrl.fromLocalFile(os.path.join(iconsdir, icon))

        imagesdir = os.path.join(path, "images")
        if os.path.isdir(imagesdir):
            for image in os.listdir(imagesdir):
                name = os.path.splitext(image)[0]
                self._images[name] = QUrl.fromLocalFile(os.path.join(imagesdir, image))

        styles = os.path.join(path, "styles.qml")
        if os.path.isfile(styles):
            c = QQmlComponent(self._engine, styles)
            context = QQmlContext(self._engine, self._engine)
            context.setContextProperty("Theme", self)
            self._styles = c.create(context)

            if c.isError():
                for error in c.errors():
                    Logger.log("e", error.toString())

        Logger.log("d", "Loaded theme %s", path)
        self._path = path

        # only emit the theme loaded signal once after all the themes in the inheritance chain have been loaded
        if is_first_call:
            self.themeLoaded.emit()
예제 #40
0
    def on_wordTableWidget_currentItemChanged(self, item, previous):
        #print "000",item, previous
        if not item: item = previous
        try:
            self.selectedWord = str(
                self.wordTableWidget.item(item.row(), 0).text())
            try:
                self.selectedTokeni = self.base.d.token2id[
                    self.
                    selectedWord]  # TODO: clean this mess up! .encode("utf-8")
            except:
                self.selectedTokeni = self.base.d.token2id[self.selectedWord]
        except Exception as e:
            print("oh, something wrong", Exception, e)
            self.selectedTokeni = 0
        #print 8888

        self.sectionMap.clearSelection()
        red = QtGui.QColor("red")
        green = QtGui.QColor("green")
        whitebrush = QtGui.QBrush(QtCore.Qt.white, QtCore.Qt.NoBrush)
        self.smin, self.smax, self.fmax = 0, 0, 0
        #		print self.currwordsectspecdic
        for i, section in enumerate(self.sectrast.sections):
            #s=self.currwordsectspecdic[(i, )]
            # print i,section,sorted(self.sectrast.specificity[self.selectedTokeni])
            # try:
            s = self.sectrast.specificity[self.selectedTokeni][(
                section, )]  # TODO: check why error on windows!
            # except:s=0
            if s > 0:
                #self.sectionMap.item(i).setBackgroundColor(red.darker(30*s))
                self.sectionMap.item(i).setBackground(
                    QtGui.QBrush(QtGui.QColor(QtCore.Qt.red).darker(30 * s)))
            elif s < 0:
                self.sectionMap.item(i).setBackground(
                    QtGui.QBrush(
                        QtGui.QColor(QtCore.Qt.green).darker(30 * -s)))
            else:
                self.sectionMap.item(i).setBackground(whitebrush)
            freq = self.sectrast.bows[section].get(self.selectedTokeni, 0)
            if freq:
                self.sectionMap.item(i).setForeground(
                    QtGui.QBrush(QtCore.Qt.magenta))
            else:
                self.sectionMap.item(i).setForeground(
                    QtGui.QBrush(QtCore.Qt.black))
            if s > self.smax: self.smax = s
            elif s < self.smin: self.smin = s

            if freq > self.fmax: self.fmax = freq

        self.updateInfo()
        #if self.currwordsectspecdic:
        #print ";.isChecked()",self.graphButton.isChecked()
        #print self.autoSelect,"jjj"
        if self.actionCollocations.isChecked(): self.colloc(self.selectedWord)
        #print self.autoSelect,"uuu"
        if self.autoSelect:
            #sleep(.5)
            #print self.recenter.word
            #if self.recenter.word==self.selectedWord:
            if self.autoSelect and self.graphButton.isChecked():
                #print "sleep",self.recenter.word

                #self.autoSelect=0
                #sleep(.5)
                baseUrl = QUrl.fromLocalFile(
                    QDir.current().absoluteFilePath("lib/resources/about.html")
                )  # any html file to base the setHtml!!!
                self.webView.setHtml(self.collocations.graph(self.nbBestKids),
                                     baseUrl)
                #self.makeCollocGraph()
                #sleep(.5)
                self.webView.page().mainFrame().addToJavaScriptWindowObject(
                    "pyObj", self.recenter)
                #self.autoSelect=1
                #print 111,self.recenter.word
            return

        if self.graphButton.isChecked(): self.makeCollocGraph()
        else: self.makeSpecGraph()
        #print "www"
        self.actionSelect_sections_with_occurrences.setEnabled(True)
        self.actionSelectposspecificsections.setEnabled(True)
        self.actionSelectnegspecificsections.setEnabled(True)
def blocklist_invalid_utf8(tmp_path):
    dest_path = tmp_path / "invalid_utf8.txt"
    dest_path.write_bytes(b"invalidutf8\xa0")
    return QUrl.fromLocalFile(str(dest_path)).toString()
예제 #42
0
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
import sys
import os

app = QApplication(sys.argv)

browser = QWebEngineView()
file_path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "video.html"))
local_url = QUrl.fromLocalFile(file_path)
browser.load(local_url)

browser.show()

app.exec_()
예제 #43
0
 def on_btnEffect_Resource_clicked(self):
     url = QUrl.fromLocalFile(":/Wave/sound/blast.wav")
     player = QSoundEffect(self)
     player.setLoopCount(2)
     player.setSource(url)
     player.play()  #无法播放资源文件
예제 #44
0
 def on_btnEffect_File_clicked(self):
     url = QUrl.fromLocalFile("Ak47.wav")
     player = QSoundEffect(self)
     player.setLoopCount(2)  #播放循环次数
     player.setSource(url)  #设置源文件
     player.play()
예제 #45
0
파일: main.py 프로젝트: RezepovPeter/VP
 def open_file(self):
     filename, _ = QFileDialog.getOpenFileName(self, "Open Video")
     if filename != '':
         self.mediaPlayer.setMedia(
             QMediaContent(QUrl.fromLocalFile(filename)))
     self.playBtn.setEnabled(True)
예제 #46
0
 def handle_help_button(self):
     """When Help button of dialog box is clicked, show BoB manual (pdf)"""
     bob_manual_pdf = 'docs%ssource%smanual%sApplications%sReact%sbob2.3.pdf' % (
         (os.sep, ) * 5)
     QDesktopServices.openUrl(QUrl.fromLocalFile(bob_manual_pdf))
예제 #47
0
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)
        self.setFixedSize(900, 600)
        self.setWindowTitle(
            "Automatic mosaic editing of videos using deep learning")
        self.setWindowIcon(QIcon('kwicon.jpg'))
        #self._mutex = QtCore.QMutex()

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer_1 = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        self.videoWidget = QVideoWidget()
        self.videoWidget_1 = QVideoWidget()

        p = self.videoWidget.palette()
        p_1 = self.videoWidget_1.palette()
        p.setColor(self.backgroundRole(), Qt.black)
        p_1.setColor(self.backgroundRole(), Qt.black)
        self.videoWidget.setPalette(p)
        self.videoWidget_1.setPalette(p_1)

        self.video_path = video_path
        self.tmp_result_name = 'tmp_result.mp4'
        self.tmp_result_path = "C:/Users/mmlab/PycharmProjects/UI_pyqt/" + self.tmp_result_name

        self.playButton = QPushButton()
        self.playButton.setEnabled(True)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)
        self.playButton.setStyleSheet('background:white')

        self.pauseButton = QPushButton()
        self.pauseButton.setEnabled(True)
        self.pauseButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaPause))
        self.pauseButton.clicked.connect(self.pause)
        self.pauseButton.setStyleSheet('background:white')

        self.stopButton = QPushButton()
        self.stopButton.setEnabled(True)
        self.stopButton.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.stopButton.clicked.connect(self.stop)
        self.stopButton.setStyleSheet('background:white')

        self.openButton = QPushButton()
        self.openButton.setEnabled(True)
        self.openButton.setText("OPEN")
        self.openButton.setFixedHeight(25)
        self.openButton.setFixedWidth(50)
        self.openButton.clicked.connect(lambda: self.openFile(self.grid))
        self.openButton.setStyleSheet('background:white')

        self.saveButton = QPushButton()
        self.saveButton.setEnabled(True)
        self.saveButton.setText("SAVE")
        self.saveButton.setFixedHeight(25)
        self.saveButton.setFixedWidth(50)
        self.saveButton.clicked.connect(self.saveFile)
        self.saveButton.setStyleSheet('background:white')

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        # Image ScrollArea
        self.grid = QtWidgets.QGridLayout()  # Create Grid Layout
        self.bg = QtWidgets.QButtonGroup(self)  # Create Button Group

        flen = len(
            os.listdir(
                'C:/Users/mmlab/PycharmProjects/UI_pyqt/cluster_people'))
        self.f = []
        self.cont01 = 0
        mod = sys.modules[__name__]
        for i in range(0, flen):
            self.f.append(
                'C:/Users/mmlab/PycharmProjects/UI_pyqt/cluster_people/{}'.
                format(i) + 'human/{}'.format(i) + 'human1.png')
        a = 0
        check = []
        vBox = QtWidgets.QHBoxLayout()
        self._databases_checked = []
        positions = [(0, j) for j in range(flen)]
        for position, title in zip(positions, self.f):
            if title == '':
                continue
            QLabel = QtWidgets.QLabel()
            QLabel.setFixedWidth(150)
            QLabel.setFixedHeight(150)
            image = self.f[self.cont01]
            num = []
            num.append(self.cont01)

            self.qp = QPixmap()
            self.qp.load(image)
            self.qp = self.qp.scaled(150, 150)
            QLabel.setPixmap(self.qp)

            vBox.addWidget(QLabel)
            cb = QCheckBox(str(a))
            cb.stateChanged.connect(self.on_stateChanged)

            vBox.addWidget(cb)
            self.grid.addLayout(vBox, *position)
            self.cont01 += 1
            a += 1

        setattr
        #RUN 버튼
        self.okButton = QPushButton()
        self.okButton.setEnabled(True)
        self.okButton.clicked.connect(self.RunFile)
        self.okButton.setFixedWidth(50)
        self.okButton.setFixedHeight(25)
        self.okButton.setText("RUN")
        self.okButton.setStyleSheet('background:yellow')
        self.okButton.setFont(QFont("굴림", 10, QFont.Bold))

        # 확인버튼
        # grid2 = QtWidgets.QGridLayout()

        wid = QWidget(self)
        self.setCentralWidget(wid)
        # CREATION OF SCROLL AREA
        frame = QFrame()
        frame.setLayout(self.grid)
        scroll = QScrollArea()
        scroll.setWidget(frame)
        scroll.setWidgetResizable(False)
        scroll.setFixedHeight(210)
        self.scrollbar = scroll.verticalScrollBar()
        # Create a QVBoxLayout
        layout_scroll = QVBoxLayout(self)
        # Add the Widget QScrollArea to the QVBoxLayout
        layout_scroll.addWidget(scroll)

        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open video')
        openAction.triggered.connect(self.openFile)

        # Create save action
        saveAction = QAction(QIcon('save.png'), '&Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save video')
        saveAction.triggered.connect(self.saveFile)

        # Create exit action
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.exitCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(exitAction)
        editMenu = menuBar.addMenu('&Edit')
        viewMenu = menuBar.addMenu('&View')
        toolMenu = menuBar.addMenu('&Tools')
        helpMenu = menuBar.addMenu('&Help')

        # Create a widget for window contents
        wid = QWidget(self)
        self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.pauseButton)
        controlLayout.addWidget(self.stopButton)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.openButton)
        controlLayout.addWidget(self.okButton)
        controlLayout.addWidget(self.saveButton)

        self.videoLayout = QHBoxLayout()
        self.videoLayout.setContentsMargins(0, 0, 0, 0)
        self.videoLayout.addWidget(self.videoWidget)
        self.videoLayout.addWidget(self.videoWidget_1)
        #bLayout = QHBoxLayout()
        #bLayout.setContentsMargins(0, 0, 0, 0)
        #bLayout.addWidget(self.okButton)

        layout = QVBoxLayout()
        layout.addLayout(self.videoLayout)
        layout.addLayout(controlLayout)
        layout.addLayout(layout_scroll)
        #layout.addLayout(bLayout)
        #layout.addWidget(self.errorLabel)

        # Set widget to contain window contents
        wid.setLayout(layout)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        # self.mediaPlayer.error.connect(self.handleError)

        self.mediaPlayer_1.setVideoOutput(self.videoWidget_1)
        self.mediaPlayer_1.positionChanged.connect(self.positionChanged)
        self.mediaPlayer_1.durationChanged.connect(self.durationChanged)
        # self.mediaPlayer_1.error.connect(self.handleError)
        fileName2 = "C:/Users/mmlab/PycharmProjects/UI_pyqt/tmp_result1.mp4"

        self.mediaPlayer.setMedia(QMediaContent(
            QUrl.fromLocalFile(video_path)))
        self.mediaPlayer_1.setMedia(
            QMediaContent(QUrl.fromLocalFile(fileName2)))
 def _onMessageActionTriggered(self, message, action):
     if action == "open_folder" and hasattr(message, "_folder"):
         QDesktopServices.openUrl(QUrl.fromLocalFile(message._folder))
예제 #49
0
 def applyCustomStyleSheet(self):
     styleSheet = QUrl.fromLocalFile(constants.XWARESTYLE_FILE)
     self.settings().setUserStyleSheetUrl(styleSheet)
예제 #50
0
	def showInDir(self):
		if self.currentTab.fileName:
			path = QFileInfo(self.currentTab.fileName).path()
			QDesktopServices.openUrl(QUrl.fromLocalFile(path))
		else:
			QMessageBox.warning(self, '', self.tr("Please, save the file somewhere."))
예제 #51
0
 def _set_media(self, movie: Movie):
     file_name = movie.get_target_path()
     self._rctx.setContextProperty("movieSource",
                                   QUrl.fromLocalFile(file_name))
예제 #52
0
    def initUI(self):
        horUnit = int(self.width / 12)
        verUnit = int(self.height / 12)

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setStyleSheet("background-color: white;")
        '''
        # INITIAL DATABASE 
        mydb = mysql.connector.connect(
            host='localhost',
            user="******",
            # passwd="",
            database="spl"
        )
        myCursor = mydb.cursor(buffered=True)
        sql = "SELECT image_name_1, image_name_2, image_name_3, \
               object_image, audio_name, video_name FROM object where object_id = %s"
        val = (LearningModule.ObjectID ,)
        myCursor.execute(sql, val)
        myresult = myCursor.fetchone()
        LearningModule.img.clear() 

        LearningModule.img.append(myresult[0]) 
        LearningModule.img.append(myresult[1])
        LearningModule.img.append(myresult[2])
        LearningModule.objNameImg = myresult[3]
        LearningModule.audio = myresult[4]
        LearningModule.video = myresult[5]
        print(myresult[4])
        self.play_audio(LearningModule.audio)

        myCursor.close()
        mydb.close()
        '''

        #=========================================Video Part===============================================#

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        self.videoWidget = QVideoWidget()

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Maximum)

        self.mediaPlayer.setMedia(
            QMediaContent(
                QUrl.fromLocalFile(
                    "F:\StudyMaterials\Python Exercises\Videos\ARBOVIRUS__HARIYE_JAO.mp4"
                )))  # NECESSARY
        self.playButton.setEnabled(True)

        # Create layouts to place inside widget

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.errorLabel)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        # ===============================Image  widget========================================#

        self.imglabel = QLabel(self)
        self.pixmap = QPixmap('mango.jpg')
        #print(LearningModule.img[0])
        #self.pixmap = QPixmap(LearningModule.img[0])
        self.imglabel.setPixmap(self.pixmap)
        self.imglabel.setGeometry(0.5 * horUnit, 3 * verUnit, 4.5 * horUnit,
                                  6 * verUnit)
        self.imglabel.setStyleSheet("background-color: lightgray;")
        self.imglabel.setAlignment(QtCore.Qt.AlignCenter)

        # audio button widget
        self.audioButton = QPushButton('\t PLAY AUDIO \t', self)
        self.audioButton.setToolTip('play audio')
        self.audioButton.setStyleSheet(
            "background-color: lightgray; font-size: 12px; font-weight: bold;")
        self.audioButton.setGeometry(7 * horUnit, 9.5 * verUnit, 4.5 * horUnit,
                                     0.5 * verUnit)
        self.audioButton.clicked.connect(
            lambda: self.play_audio(LearningModule.audio))  # NECESSARY

        # Previous button widget
        self.buttonP = QPushButton('\t PREVIOUS IMAGE \t', self)
        self.buttonP.setToolTip('Go to previous picture')
        self.buttonP.setStyleSheet(
            "background-color: lightgray; font-size: 12px; font-weight: bold;")
        self.buttonP.setGeometry(0.5 * horUnit, 9.5 * verUnit, 1.2 * horUnit,
                                 0.5 * verUnit)
        self.buttonP.clicked.connect(self.on_click_prev)

        # Skip button widget
        self.buttonS = QPushButton('\t SKIP THIS OBJECT \t', self)
        self.buttonS.setToolTip('Skip this object')
        self.buttonS.setStyleSheet(
            "background-color: lightgray; font-size: 12px; font-weight: bold;")
        self.buttonS.setGeometry(2 * horUnit, 9.5 * verUnit, 1.5 * horUnit,
                                 0.5 * verUnit)
        self.buttonS.clicked.connect(self.on_click_skip)

        # Next button widget
        self.buttonN = QPushButton('\t NEXT IMAGE \t', self)
        self.buttonN.setToolTip('Go to next picture')
        self.buttonN.setStyleSheet(
            "background-color: lightgray; font-size: 12px; font-weight: bold;")
        self.buttonN.setGeometry(3.8 * horUnit, 9.5 * verUnit, 1.2 * horUnit,
                                 0.5 * verUnit)
        self.buttonN.clicked.connect(self.on_click_next)

        # OBJECT NAME LABEL
        self.lblObjName = QLabel(self)
        pixmap = QPixmap('IMG-1.jpg')
        self.lblObjName.setPixmap(pixmap)
        self.lblObjName.setGeometry(3 * horUnit, 0 * verUnit, 6 * horUnit,
                                    2 * verUnit)
        self.lblObjName.setAlignment(QtCore.Qt.AlignCenter)

        # Create a widget for window contents
        self.wid = QWidget(self)
        self.wid.setGeometry(7 * horUnit, 3 * verUnit, 4.5 * horUnit,
                             6 * verUnit)
        self.wid.setStyleSheet("background-color: lightgray;")
        self.wid.setLayout(layout)
        self.wid.show()
        self.show()
    def __init__(self, parent=None):
        super(PieChart, self).__init__(parent)

        self._name = ''
        self._color = QColor()

    def paint(self, painter):
        painter.setPen(QPen(self._color, 2))
        painter.setRenderHints(QPainter.Antialiasing, True)

        rect = QRectF(0, 0, self.width(), self.height()).adjusted(1, 1, -1, -1)
        painter.drawPie(rect, 90 * 16, 290 * 16)


if __name__ == '__main__':
    import os
    import sys

    app = QGuiApplication(sys.argv)

    qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(
        QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'app.qml')))
    view.show()

    sys.exit(app.exec_())
예제 #54
0
 def openExtern(self, index):
     if index.isValid():
         filename = self.model().filePath(index)
         QDesktopServices.openUrl(QUrl.fromLocalFile(filename))
예제 #55
0
 def showHelp(self):
     url = QUrl.fromLocalFile(op.abspath(op.join(HELP_PATH, 'index.html')))
     QDesktopServices.openUrl(url)
예제 #56
0
def get_data_folder_url(data_folder):
    #return QUrl.fromLocalFile(str(Path(data_folder).joinpath("index.html")))
    return QUrl.fromLocalFile(data_folder + "/index.html")
예제 #57
0
파일: qml.py 프로젝트: joancs/Gantry
from PyQt5.QtGui import QGuiApplication

if __name__ == '__main__':

    #get our data
    url = "http://country.io/names.json"
    response = urllib.request.urlopen(url)
    data = json.loads(response.read().decode('utf-8'))

    #Format and sort the data
    data_list = list(data.values())
    data_list.sort()

    #Set up the application window
    app = QGuiApplication(sys.argv)
    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)

    #Expose the list to the Qml code
    my_model = QStringListModel()
    my_model.setStringList(data_list)
    view.rootContext().setContextProperty("myModel", my_model)

    #Load the QML file
    qml_file = os.path.join(os.path.dirname(__file__), "test.ui.qml")
    view.setSource(QUrl.fromLocalFile(os.path.abspath(qml_file)))

    #Show the window
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.show()
예제 #58
0
def _desktop_open(path):
    QDesktopServices.openUrl(QUrl.fromLocalFile(path))
 def play(self, url):
     self.media_player.setMedia(QMediaContent(QUrl.fromLocalFile(url)))
     self.media_player.play()
예제 #60
0
    QTabWidget )
from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog
from PyQt5.QtNetwork import QNetworkRequest
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebPage, QWebFrame

from ui_settings_dialog import Ui_SettingsDialog
from bookmark_manager import Bookmarks_Dialog, Add_Bookmark_Dialog, History_Dialog, icon_dir
from import_export import *
from download_manager import Download, DownloadsModel, Downloads_Dialog, SaveAsHtml
from common import *
import ui_download_confirm, youtube
import resources_rc, webkit

downloads_list_file = configdir+"downloads.txt"
homepage = QUrl.fromLocalFile(program_dir + 'home.html').toString()


class Main(QMainWindow):
    def __init__(self):
        global downloads_list_file
        QMainWindow.__init__(self)
        self.setWindowIcon(QIcon(":/quartz.png"))
        self.setWindowTitle("Quartz Browser - "+__version__)
        # Window Properties
        self.history = []
        self.downloads = []
        self.confirm_before_quit = True
        # Create required directories
        for folder in [configdir, icon_dir, thumbnails_dir]:
            if not os.path.exists(folder):