示例#1
0
def commandLineUrlArgument() -> QUrl:
    args = QCoreApplication.arguments()
    for arg in args[1:]:
        if not arg.startswith("_"):
            return QUrl.fromUserInput(arg)

    return QUrl("https://www.qt.io")
示例#2
0
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self.setupUi(self)

        self.m_content = Document()
        self.m_filePath = ""

        self.editor.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont))
        self.preview.setContextMenuPolicy(Qt.NoContextMenu)

        page = PreviewPage(self)
        self.preview.setPage(page)

        self.editor.textChanged.connect(
            lambda: self.m_content.setText(self.editor.toPlainText()))

        channel = QWebChannel(self)
        channel.registerObject("content", self.m_content)
        page.setWebChannel(channel)

        self.preview.setUrl(QUrl("qrc:/index.html"))

        self.actionNew.triggered.connect(self.onFileNew)
        self.actionOpen.triggered.connect(self.onFileOpen)
        self.actionSave.triggered.connect(self.onFileSave)
        self.actionSaveAs.triggered.connect(self.onFileSaveAs)
        self.actionExit.triggered.connect(self.onExit)

        self.editor.document().modificationChanged.connect(
            self.actionSave.setEnabled)

        defaultTextFile = QFile(":/default.md")
        defaultTextFile.open(QIODevice.ReadOnly)
        self.editor.setPlainText(defaultTextFile.readAll().data().decode())
示例#3
0
 def acceptNavigationRequest(self, url: QUrl,
                             _type: QWebEnginePage.NavigationType,
                             isMainFrame: bool) -> bool:
     if url.scheme() == "qrc":
         return True
     QDesktopServices.openUrl(url)
     return False
示例#4
0
    def url(self):
        """
        Returns the url path
        :return: QUrl
        """

        return QUrl(self.path())
示例#5
0
class WebUiHandler(QWebEngineUrlSchemeHandler):
    def requestStarted(self, job: QWebEngineUrlRequestJob) -> None:
        webUiOrigin = QUrl(SCHEMENAME + ":")
        GET: QByteArray = QByteArray(b"GET")
        POST: QByteArray = QByteArray(b"POST")

        method = job.requestMethod()
        url = job.requestUrl()
        initiator = job.initiator()
        if method == GET and url == WebUiHandler.aboutUrl:
            f = QFile(":/about.html", job)
            f.open(QIODevice.ReadOnly)
            job.reply(b"text/html", f)
        elif (method == POST and url == WebUiHandler.aboutUrl
              and initiator == webUiOrigin):
            job.fail(QWebEngineUrlRequestJob.RequestAborted)
            QApplication.exit()
        else:
            job.fail(QWebEngineUrlRequestJob.UrlNotFound)

    @classmethod
    def registerUrlScheme(cls):
        webUiScheme = QWebEngineUrlScheme(cls.schemeName)
        webUiScheme.setFlags(QWebEngineUrlScheme.SecureScheme
                             | QWebEngineUrlScheme.LocalScheme
                             | QWebEngineUrlScheme.LocalAccessAllowed)
        QWebEngineUrlScheme.registerScheme(webUiScheme)

    schemeName: QByteArray = SCHEMENAME.encode()
    aboutUrl: QUrl = QUrl(SCHEMENAME + ":about")
示例#6
0
def main():
    import sys

    QGuiApplication.setApplicationName("Gallery")
    QGuiApplication.setOrganizationName("QtProject")
    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    app = QGuiApplication(sys.argv)

    QIcon.setThemeName("gallery")

    settings = QSettings()

    style = QQuickStyle.name()
    if style:
        settings.setValue("style", style)
    else:
        QQuickStyle.setStyle(settings.value("style"))

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("availableStyles",
                                            QQuickStyle.availableStyles())
    engine.load(QUrl("qrc:/gallery.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
示例#7
0
def main():
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # QtWebEngine::initialize()

    if QT_NO_WIDGETS:
        app = QApplication(sys.argv)
    else:
        app = QGuiApplication(sys.argv)

    engine = QQmlApplicationEngine()
    server = Server(engine)

    engine.load(QUrl("qrc:/main.qml"))
    QTimer.singleShot(0, server.run)

    proxy = QNetworkProxy()
    proxy.setType(QNetworkProxy.HttpProxy)
    proxy.setHostName("localhost")
    proxy.setPort(5555)
    QNetworkProxy.setApplicationProxy(proxy)

    sys.exit(app.exec_())
示例#8
0
    def __init__(self, page, parent=None):
        super(HelpForm, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAttribute(Qt.WA_GroupLeader)

        backAction = QAction(QIcon(":/back.png"), "&Back", self)
        backAction.setShortcut(QKeySequence.Back)
        homeAction = QAction(QIcon(":/home.png"), "&Home", self)
        homeAction.setShortcut("Home")
        self.pageLabel = QLabel()

        toolBar = QToolBar()
        toolBar.addAction(backAction)
        toolBar.addAction(homeAction)
        toolBar.addWidget(self.pageLabel)
        self.textBrowser = QTextBrowser()

        layout = QVBoxLayout()
        layout.addWidget(toolBar)
        layout.addWidget(self.textBrowser, 1)
        self.setLayout(layout)

        backAction.triggered.connect(self.tbackward)
        homeAction.triggered.connect(self.thome)
        self.textBrowser.sourceChanged.connect(self.updatePageTitle)

        self.textBrowser.setSearchPaths([":/help"])
        self.textBrowser.setSource(QUrl(page))
        self.resize(400, 600)
        self.setWindowTitle("{0} Help".format(QApplication.applicationName()))
示例#9
0
    def __init__(self, url: QUrl) -> None:
        super().__init__()
        self.setupUi(self)

        self.m_cookies = []

        self.m_urlLineEdit.setText(url.toString())

        self.m_layout = QVBoxLayout()
        self.m_layout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding))
        self.m_layout.setContentsMargins(0, 0, 0, 0)
        self.m_layout.setSpacing(0)

        w = QWidget()
        p = w.palette()
        p.setColor(self.widget.backgroundRole(), Qt.white)
        w.setPalette(p)
        w.setLayout(self.m_layout)

        self.m_scrollArea.setWidget(w)
        self.m_scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.m_scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        self.m_urlButton.clicked.connect(self.handleUrlClicked)
        self.m_deleteAllButton.clicked.connect(self.handleDeleteAllClicked)
        self.m_newButton.clicked.connect(self.handleNewClicked)

        self.m_store: QWebEngineCookieStore = self.m_webview.page().profile(
        ).cookieStore()
        self.m_store.cookieAdded.connect(self.handleCookieAdded)
        self.m_store.loadAllCookies()
        self.m_webview.load(url)
示例#10
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.m_view = QWebEngineView()
        self.setCentralWidget(self.m_view)

        page = self.m_view.page()
        page.featurePermissionRequested.connect(self.on_featurePermissionRequested)
        page.load(QUrl("https://maps.google.com"))
示例#11
0
def main():
    import sys

    app = QApplication(sys.argv)

    QQuickWindow.setDefaultAlphaBuffer(True)

    QCoreApplication.setApplicationName("Photosurface")
    QCoreApplication.setOrganizationName("QtProject")
    QCoreApplication.setApplicationVersion(__qt_version__)
    parser = QCommandLineParser()
    parser.setApplicationDescription("Qt Quick Demo - Photo Surface")
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument("directory", "The image directory or URL to show.")
    parser.process(app)

    initialUrl = QUrl()
    if parser.positionalArguments():
        initialUrl = QUrl.fromUserInput(
            parser.positionalArguments()[0], QDir.currentPath(), QUrl.AssumeLocalFile
        )
        if not initialUrl.isValid():
            print(
                'Invalid argument: "',
                parser.positionalArguments()[0],
                '": ',
                initialUrl.errorString(),
            )
            sys.exit(1)

    nameFilters = imageNameFilters()

    engine = QQmlApplicationEngine()
    context: QQmlContext = engine.rootContext()

    picturesLocationUrl = QUrl.fromLocalFile(QDir.homePath())
    picturesLocations = QStandardPaths.standardLocations(
        QStandardPaths.PicturesLocation
    )
    if picturesLocations:
        picturesLocationUrl = QUrl.fromLocalFile(picturesLocations[0])
        if not initialUrl and QDir(picturesLocations[0]).entryInfoList(
            nameFilters, QDir.Files
        ):
            initialUrl = picturesLocationUrl

    context.setContextProperty("contextPicturesLocation", picturesLocationUrl)
    context.setContextProperty("contextInitialUrl", initialUrl)
    context.setContextProperty("contextImageNameFilters", nameFilters)

    engine.load(QUrl("qrc:///photosurface.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
示例#12
0
    def url(self):
        """
        Used by the mime data when dragging/droping the item
        :return: Qurl
        """

        if not self._url:
            self._url = QUrl(self.text(0))

        return self._url
示例#13
0
 def acceptNavigationRequest(
     self,
     url: QUrl,
     navigation_type: QWebEnginePage.NavigationType,
     is_main_frame: bool,
 ) -> bool:
     if url.scheme() != "https":
         return True
     QDesktopServices.openUrl(url)
     return False
示例#14
0
def main():
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    app = QApplication(sys.argv)
    url = QUrl()

    if len(sys.argv) > 1:
        url = QUrl.fromUserInput(sys.argv[1])
    else:
        url = QUrl("http://www.google.com/ncr")

    browser = MainWindow(url)
    browser.resize(1024, 768)
    browser.show()

    sys.exit(app.exec_())
示例#15
0
def main():
    import sys

    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)

    engine = QQmlApplicationEngine()
    engine.addImportPath(":/imports")
    engine.load(QUrl("qrc:/flatstyle.qml"))

    sys.exit(app.exec_())
示例#16
0
    def download(self):
        grab = QPoint(0, 0)
        for x in range(self.m_tilesRect.width() + 1):
            for y in range(self.m_tilesRect.height() + 1):
                tp = self.m_tilesRect.topLeft() + QPoint(x, y)
                if QPointH(tp) not in self.m_tilePixmaps:
                    grab = tp
                    break

        if grab == QPoint(0, 0):
            self.m_url = QUrl()
            return
        path = "http://tile.openstreetmap.org/%d/%d/%d.png"
        self.m_url = QUrl(path % (self.zoom, grab.x(), grab.y()))
        request = QNetworkRequest()
        request.setUrl(self.m_url)
        request.setRawHeader(b"User-Agent",
                             b"The Qt Company (Qt) Graphics Dojo 1.0")
        request.setAttribute(QNetworkRequest.User, grab)
        self.m_manager.get(request)
示例#17
0
def main():
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # QtWebEngine::initialize()

    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load(QUrl("qrc:/WebBrowser.qml"))

    sys.exit(app.exec_())
示例#18
0
def main():
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    app = QApplication(sys.argv)
    w = MainWindow(QUrl("http://qt.io"))
    w.resize(1024, 768)
    w.show()

    sys.exit(app.exec_())
示例#19
0
    def url(self):
        """
        Used by the mime data when dragging/droping the item
        :return: Qurl
        """

        # if self.path():
        #     file_path = path_utils.clean_path(os.path.join(self.path(), self.name()))
        #     if not os.path.isfile(file_path):
        #         file_path = self.path()
        #     return QUrl('file:///{}'.format(file_path))

        return QUrl('file:///{}'.format(self.path()))
示例#20
0
def main():
    import sys

    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QGuiApplication(sys.argv)

    QFontDatabase.addApplicationFont(":/fonts/fontello.ttf")

    engine = QQmlApplicationEngine()
    engine.load(QUrl("qrc:/swipetoremove.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
示例#21
0
    def from_file(cls, file, **data):
        """Construct from file path.

        Args:
            file (str): qml file path.
            data (dict, optional): Data will be used in qml as `DATA`.
        """

        ret = Notify()
        context = ret.rootContext()
        context.setContextProperty('DATA', data)
        context.setContextProperty('VIEW', ret)
        ret.setSource(QUrl.fromLocalFile(file))
        QApplication.processEvents()
        return ret
示例#22
0
    def __init__(self, parent: QObject = None) -> None:
        super().__init__(parent)

        self.width: int = 400
        self.height: int = 300
        self.zoom: int = 15
        self.latitude: float = 59.9138204
        self.longitude: float = 10.7387413

        self.m_offset = QPoint()
        self.m_tilesRect = QRect()

        self.m_emptyTile = QPixmap(tdim, tdim)
        self.m_emptyTile.fill(Qt.lightGray)

        self.m_tilePixmaps: typing.Dict[QPointH, QPixmap] = dict()
        self.m_manager = QNetworkAccessManager()
        self.m_url = QUrl()

        cache = QNetworkDiskCache()
        cache.setCacheDirectory(
            QStandardPaths.writableLocation(QStandardPaths.CacheLocation))
        self.m_manager.setCache(cache)
        self.m_manager.finished.connect(self.handleNetworkData)
示例#23
0
def main():
    import sys

    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QCoreApplication.setOrganizationName("QtExamples")

    app = QGuiApplication(sys.argv)

    engine = QQmlApplicationEngine()
    engine.addImportPath(":/imports")
    engine.load(QUrl("qrc:/main.qml"))

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
示例#24
0
def main():
    import sys

    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QCoreApplication.setOrganizationName("QtExamples")

    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.engine().quit.connect(app.quit)
    view.setSource(QUrl("qrc:/demos/calqlatr/calqlatr.qml"))
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.show()

    sys.exit(app.exec_())
示例#25
0
 def __init__(self, url=None, update=True, truncated=False):
     """ Initialize the FileStatus cache
     
     :Parameters:
         url : `QtCore.QUrl`
             File URL
         update : `bool`
             Immediately update file status or not, like checking if it's writable.
         truncated : `bool`
             If the file was truncated on read, and therefore should never be edited.
     """
     self.url = url if url else QUrl()
     self.path = "" if self.url.isEmpty() else self.url.toLocalFile()
     self.status = self.FILE_NEW
     self.fileInfo = None
     if update:
         self.updateFileStatus(truncated)
示例#26
0
    def requestStarted(self, job: QWebEngineUrlRequestJob) -> None:
        webUiOrigin = QUrl(SCHEMENAME + ":")
        GET: QByteArray = QByteArray(b"GET")
        POST: QByteArray = QByteArray(b"POST")

        method = job.requestMethod()
        url = job.requestUrl()
        initiator = job.initiator()
        if method == GET and url == WebUiHandler.aboutUrl:
            f = QFile(":/about.html", job)
            f.open(QIODevice.ReadOnly)
            job.reply(b"text/html", f)
        elif (method == POST and url == WebUiHandler.aboutUrl
              and initiator == webUiOrigin):
            job.fail(QWebEngineUrlRequestJob.RequestAborted)
            QApplication.exit()
        else:
            job.fail(QWebEngineUrlRequestJob.UrlNotFound)
示例#27
0
def main():
    import sys

    QGuiApplication.setApplicationName("Automotive")
    QGuiApplication.setOrganizationName("QtProject")
    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QGuiApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)

    app = QGuiApplication(sys.argv)

    QIcon.setThemeName("automotive")

    engine = QQmlApplicationEngine()
    engine.load(QUrl("qrc:/qml/automotive.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
示例#28
0
def main():
    import os
    import sys

    CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
    os.environ["QTWEBENGINE_DICTIONARIES_PATH"] = os.path.join(
        CURRENT_DIR, "qtwebengine_dictionaries")

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)

    view = WebView()
    view.setUrl(QUrl("qrc:/index.html"))
    view.resize(500, 640)
    view.show()

    sys.exit(app.exec_())
示例#29
0
def main():
    import os
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QGuiApplication(sys.argv)

    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"

    engine = QQmlApplicationEngine()

    isEmbedded = False

    engine.rootContext().setContextProperty("isEmbedded", isEmbedded)

    engine.load(QUrl("qrc:/qml/main.qml"))

    sys.exit(app.exec_())
示例#30
0
    def startDrag(self, supported_actions):
        """
        Function that is called when we start dragging an item
        This function set ups the mime data and creates a copy of the image
        of the item that is show in cursor position while dragging action
        is enabled
        """

        index = self.currentIndex()
        model = self.model()
        item = model.itemFromIndex(index)
        drag = QDrag(self)
        mime_data = QMimeData()
        mime_data.setData('item_text', QByteArray(str(item.text())))
        mime_data.setData('item_size', QByteArray('%.1f %.1f' % (item.size.width(), item.size.height())))
        url = QUrl.fromLocalFile(item.text())
        mime_data.setUrls(url)
        drag.setMimeData(mime_data)
        pixmap = item.icon().pixmap(50, 50)
        drag.setDragCursor(pixmap, Qt.CopyAction)
        drag.start()