当前位置: 首页>>代码示例>>Python>>正文


Python QtCore.QUrl类代码示例

本文整理汇总了Python中AnyQt.QtCore.QUrl的典型用法代码示例。如果您正苦于以下问题:Python QUrl类的具体用法?Python QUrl怎么用?Python QUrl使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QUrl类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _fetch_inventory

    def _fetch_inventory(self, url):
        cache_dir = config.cache_dir()
        cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__)

        try:
            os.makedirs(cache_dir)
        except OSError:
            pass

        url = QUrl(self.inventory)
        if not url.isLocalFile():
            # fetch and cache the inventory file.
            manager = QNetworkAccessManager(self)
            cache = QNetworkDiskCache()
            cache.setCacheDirectory(cache_dir)
            manager.setCache(cache)
            req = QNetworkRequest(url)

            # Follow redirects (for example http -> https)
            # If redirects were not followed, the documentation would not be found
            try:
                req.setAttribute(QNetworkRequest.FollowRedirectsAttribute, 1)  # from Qt 5.6
                req.setAttribute(QNetworkRequest.RedirectPolicyAttribute,  # from Qt 5.9
                                 QNetworkRequest.NoLessSafeRedirectPolicy)
            except AttributeError:  # if ran with earlier Qt
                pass

            self._reply = manager.get(req)
            manager.finished.connect(self._on_finished)
        else:
            with open(url.toLocalFile(), "rb") as f:
                self._load_inventory(f)
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:32,代码来源:provider.py

示例2: BaseInventoryProvider

class BaseInventoryProvider(HelpProvider):
    def __init__(self, inventory, parent=None):
        super().__init__(parent)
        self.inventory = QUrl(inventory)

        if not self.inventory.scheme() and not self.inventory.isEmpty():
            self.inventory.setScheme("file")

        self._error = None
        self._fetch_inventory(self.inventory)

    def _fetch_inventory(self, url):
        cache_dir = config.cache_dir()
        cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__)

        try:
            os.makedirs(cache_dir)
        except OSError:
            pass

        url = QUrl(self.inventory)
        if not url.isLocalFile():
            # fetch and cache the inventory file.
            manager = QNetworkAccessManager(self)
            cache = QNetworkDiskCache()
            cache.setCacheDirectory(cache_dir)
            manager.setCache(cache)
            req = QNetworkRequest(url)

            # Follow redirects (for example http -> https)
            # If redirects were not followed, the documentation would not be found
            try:
                req.setAttribute(QNetworkRequest.FollowRedirectsAttribute, 1)  # from Qt 5.6
                req.setAttribute(QNetworkRequest.RedirectPolicyAttribute,  # from Qt 5.9
                                 QNetworkRequest.NoLessSafeRedirectPolicy)
            except AttributeError:  # if ran with earlier Qt
                pass

            self._reply = manager.get(req)
            manager.finished.connect(self._on_finished)
        else:
            with open(url.toLocalFile(), "rb") as f:
                self._load_inventory(f)

    def _on_finished(self, reply):
        if reply.error() != QNetworkReply.NoError:
            log.error("An error occurred while fetching "
                      "help inventory '{0}'".format(self.inventory))
            self._error = reply.error(), reply.errorString()

        else:
            contents = bytes(reply.readAll())
            self._load_inventory(io.BytesIO(contents))

    def _load_inventory(self, stream):
        raise NotImplementedError()
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:56,代码来源:provider.py

示例3: test_dragEnterEvent_rejects_binary

 def test_dragEnterEvent_rejects_binary(self):
     with named_file("", suffix=".42") as fn:
         with open(fn, "wb") as f:
             f.write(b"\xc3\x28")
         event = self._drag_enter_event(QUrl.fromLocalFile(fn))
         self.widget.dragEnterEvent(event)
         self.assertFalse(event.isAccepted())
开发者ID:ales-erjavec,项目名称:orange3,代码行数:7,代码来源:test_owpythonscript.py

示例4: create_html_provider

def create_html_provider(entry_point):
    locations = entry_point.resolve()
    replacements = _replacements_for_dist(entry_point.dist)

    formatter = string.Formatter()

    for target in locations:
        # Extract all format fields
        format_iter = formatter.parse(target)
        fields = {name for _, name, _, _ in format_iter if name}

        if not set(fields) <= set(replacements.keys()):
            log.warning("Invalid replacement fields %s",
                        set(fields) - set(replacements.keys()))
            continue
        target = formatter.format(target, **replacements)

        targeturl = qurl_from_path(target)
        if not targeturl.isValid():
            continue

        if targeturl.isLocalFile():
            if not os.path.exists(target):
                log.info("Local doc root '%s' does not exist.", target)
                continue

        if target:
            return provider.SimpleHelpProvider(
                baseurl=QUrl.fromLocalFile(target))

    return None
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:31,代码来源:manager.py

示例5: BaseInventoryProvider

class BaseInventoryProvider(HelpProvider):
    def __init__(self, inventory, parent=None):
        super().__init__(parent)
        self.inventory = QUrl(inventory)

        if not self.inventory.scheme() and not self.inventory.isEmpty():
            self.inventory.setScheme("file")

        self._error = None
        self._fetch_inventory(self.inventory)

    def _fetch_inventory(self, url):
        cache_dir = config.cache_dir()
        cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__)

        try:
            os.makedirs(cache_dir)
        except OSError:
            pass

        url = QUrl(self.inventory)
        if not url.isLocalFile():
            # fetch and cache the inventory file.
            manager = QNetworkAccessManager(self)
            cache = QNetworkDiskCache()
            cache.setCacheDirectory(cache_dir)
            manager.setCache(cache)
            req = QNetworkRequest(url)

            self._reply = manager.get(req)
            manager.finished.connect(self._on_finished)
        else:
            with open(str(url.toLocalFile()), "rb") as f:
                self._load_inventory(f)

    def _on_finished(self, reply):
        if reply.error() != QNetworkReply.NoError:
            log.error("An error occurred while fetching "
                      "help inventory '{0}'".format(self.inventory))
            self._error = reply.error(), reply.errorString()

        else:
            contents = bytes(reply.readAll())
            self._load_inventory(io.BytesIO(contents))

    def _load_inventory(self, stream):
        raise NotImplementedError()
开发者ID:RachitKansal,项目名称:orange3,代码行数:47,代码来源:provider.py

示例6: test_dropEvent_replaces_file

 def test_dropEvent_replaces_file(self):
     with named_file("test", suffix=".42") as fn:
         previous = self.widget.text.toPlainText()
         event = self._drop_event(QUrl.fromLocalFile(fn))
         self.widget.dropEvent(event)
         self.assertEqual("test", self.widget.text.toPlainText())
         self.widget.text.undo()
         self.assertEqual(previous, self.widget.text.toPlainText())
开发者ID:ales-erjavec,项目名称:orange3,代码行数:8,代码来源:test_owpythonscript.py

示例7: __init__

    def __init__(self, inventory, parent=None):
        super().__init__(parent)
        self.inventory = QUrl(inventory)

        if not self.inventory.scheme() and not self.inventory.isEmpty():
            self.inventory.setScheme("file")

        self._error = None
        self._fetch_inventory(self.inventory)
开发者ID:RachitKansal,项目名称:orange3,代码行数:9,代码来源:provider.py

示例8: test_script_insert_mime_file

 def test_script_insert_mime_file(self):
     with named_file("test", suffix=".42") as fn:
         previous = self.widget.text.toPlainText()
         mime = QMimeData()
         url = QUrl.fromLocalFile(fn)
         mime.setUrls([url])
         self.widget.text.insertFromMimeData(mime)
         self.assertEqual("test", self.widget.text.toPlainText())
         self.widget.text.undo()
         self.assertEqual(previous, self.widget.text.toPlainText())
开发者ID:ales-erjavec,项目名称:orange3,代码行数:10,代码来源:test_owpythonscript.py

示例9: test_dropEvent_selects_file

    def test_dropEvent_selects_file(self):
        self.widget.load_data = Mock()
        self.widget.source = OWFile.URL

        event = self._drop_event(QUrl.fromLocalFile(TITANIC_PATH))
        self.widget.dropEvent(event)

        self.assertEqual(self.widget.source, OWFile.LOCAL_FILE)
        self.assertTrue(path.samefile(self.widget.last_path(), TITANIC_PATH))
        self.widget.load_data.assert_called_with()
开发者ID:nikicc,项目名称:orange3,代码行数:10,代码来源:test_owfile.py

示例10: urlFromValue

    def urlFromValue(self, value):
        variable = value.variable
        origin = variable.attributes.get("origin", "")
        if origin and QDir(origin).exists():
            origin = QUrl.fromLocalFile(origin)
        elif origin:
            origin = QUrl(origin)
            if not origin.scheme():
                origin.setScheme("file")
        else:
            origin = QUrl("")
        base = origin.path()
        if base.strip() and not base.endswith("/"):
            origin.setPath(base + "/")

        name = QUrl(str(value))
        url = origin.resolved(name)
        if not url.scheme():
            url.setScheme("file")
        return url
开发者ID:martinmozina,项目名称:orange3,代码行数:20,代码来源:owimageviewer.py

示例11: _fetch_inventory

    def _fetch_inventory(self, url):
        cache_dir = config.cache_dir()
        cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__)

        try:
            os.makedirs(cache_dir)
        except OSError:
            pass

        url = QUrl(self.inventory)
        if not url.isLocalFile():
            # fetch and cache the inventory file.
            manager = QNetworkAccessManager(self)
            cache = QNetworkDiskCache()
            cache.setCacheDirectory(cache_dir)
            manager.setCache(cache)
            req = QNetworkRequest(url)

            self._reply = manager.get(req)
            manager.finished.connect(self._on_finished)
        else:
            self._load_inventory(open(str(url.toLocalFile()), "rb"))
开发者ID:rekonder,项目名称:orange3,代码行数:22,代码来源:provider.py

示例12: create_intersphinx_provider

def create_intersphinx_provider(entry_point):
    locations = entry_point.resolve()
    replacements = _replacements_for_dist(entry_point.dist)

    formatter = string.Formatter()

    for target, inventory in locations:
        # Extract all format fields
        format_iter = formatter.parse(target)
        if inventory:
            format_iter = itertools.chain(format_iter,
                                          formatter.parse(inventory))
        # Names used in both target and inventory
        fields = {name for _, name, _, _ in format_iter if name}

        if not set(fields) <= set(replacements.keys()):
            log.warning("Invalid replacement fields %s",
                        set(fields) - set(replacements.keys()))
            continue

        target = formatter.format(target, **replacements)
        if inventory:
            inventory = formatter.format(inventory, **replacements)

        targeturl = qurl_from_path(target)
        if not targeturl.isValid():
            continue

        if targeturl.isLocalFile():
            if os.path.exists(os.path.join(target, "objects.inv")):
                inventory = QUrl.fromLocalFile(
                    os.path.join(target, "objects.inv"))
            else:
                log.info("Local doc root '%s' does not exist.", target)
                continue

        else:
            if not inventory:
                # Default inventory location
                inventory = targeturl.resolved(QUrl("objects.inv"))

        if inventory is not None:
            return provider.IntersphinxHelpProvider(
                inventory=inventory, target=target)
    return None
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:45,代码来源:manager.py

示例13: url_from_value

    def url_from_value(self, value):
        base = value.variable.attributes.get("origin", "")
        if QDir(base).exists():
            base = QUrl.fromLocalFile(base)
        else:
            base = QUrl(base)

        path = base.path()
        if path.strip() and not path.endswith("/"):
            base.setPath(path + "/")

        url = base.resolved(QUrl(str(value)))
        return url
开发者ID:biolab,项目名称:orange3-imageanalytics,代码行数:13,代码来源:owimagegrid.py

示例14: __init__

    def __init__(self, parent=None, bridge=None, *, style='', javascript=''):

        class _Bridge(QObject):
            @pyqtSlot('QVariantList')
            def on_selected_points(_, indices):
                self.on_selected_points([np.sort(np.array(selected)).astype(int)
                                         for selected in indices])

            @pyqtSlot('QVariantList')
            def on_selected_range(_, ranges):
                self.on_selected_range(ranges)

        if bridge is not None:
            # Patch existing user-passed bridge with our selection callbacks
            assert isinstance(bridge, QObject), 'bridge needs to be a QObject'
            _Bridge = type(bridge.__class__.__name__,
                           bridge.__class__.__mro__,
                           dict(bridge.__dict__,
                                on_selected_points=_Bridge.on_selected_points,
                                on_selected_range=_Bridge.on_selected_range))

        super().__init__(parent=parent,
                         bridge=_Bridge(),
                         url=QUrl.fromLocalFile(path.join(path.dirname(__file__),
                                                          '_plotly', 'html.html')))
        if style:
            if path.isfile(style):
                with open(style, encoding='utf-8') as f:
                    style = f.read()
            # Add each of the rules of the stylesheet into the document
            # If you feel this is overly complicated, be my guest to improve it
            for i, style in enumerate(filter(None, style.replace(' ', '').replace('\n', '').split('}'))):
                self.evalJS("document.styleSheets[0].insertRule('%s }', 0);" % style)

        if javascript:
            if isinstance(javascript, str):
                javascript = [javascript]
            for js in javascript:
                if path.isfile(js):
                    with open(js, encoding='utf-8') as f:
                        js = f.read()
                self.evalJS(js)
开发者ID:pavlin-policar,项目名称:orange3-prototypes,代码行数:42,代码来源:plotly_widget.py

示例15: test_drop

 def test_drop(self):
     widget = self.widget
     with tempfile.TemporaryDirectory() as tmpdir:
         urlpath = QUrl.fromLocalFile(tmpdir)
         data = QMimeData()
         data.setUrls([urlpath])
         pos = widget.recent_cb.rect().center()
         actions = Qt.LinkAction | Qt.CopyAction
         ev = QDragEnterEvent(pos, actions, data,
                              Qt.LeftButton, Qt.NoModifier)
         assert QApplication.sendEvent(widget.recent_cb, ev)
         self.assertTrue(ev.isAccepted())
         del ev
         ev = QDropEvent(pos, actions, data,
                         Qt.LeftButton, Qt.NoModifier, QDropEvent.Drop)
         assert QApplication.sendEvent(widget.recent_cb, ev)
         self.assertTrue(ev.isAccepted())
         del ev
         self.assertEqual(widget.recent_paths[0].abspath,
                          urlpath.toLocalFile())
         self._startandwait(widget)
         self.widget.commit()
开发者ID:biolab,项目名称:orange3-imageanalytics,代码行数:22,代码来源:test_owimageimport.py


注:本文中的AnyQt.QtCore.QUrl类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。