Example #1
0
class TestWindow(QtGui.QWidget):
    def __init__(self, parent = None):
        super(TestWindow, self).__init__(parent)

        self.palette = QtGui.QPalette()
        self.gridLayout = QtGui.QGridLayout()
        self.centralWidget = QtGui.QWidget()
        self.button = QtGui.QPushButton("Click")
        self.setWindowTitle("UNIX")
        self.resize(1200,700)
        self.button.clicked.connect(self.clicked)
        self.b = QWebView()
        self.b.load(QUrl('http://www.google.com'))
        IEdit = QtGui.QLineEdit()
        self.Trans = QtGui.QTextEdit()

        self.gridLayout.addWidget(IEdit,0,0)
        self.gridLayout.addWidget(self.button,1,0)
        self.gridLayout.addWidget(self.b,2,0)
        self.gridLayout.addWidget(self.Trans,3,0)

        
        self.setLayout(self.gridLayout)


    def clicked(self):
            self.b.load(QUrl('http://yahoo.com.tw'))
            self.Trans.setText('HI')
Example #2
0
class Browser(QWidget, BaseCentralWidget):
    def __init__(self, URL, process=None):
        QWidget.__init__(self)
        BaseCentralWidget.__init__(self)
        self.path = URL
        self.process = process

        v_box = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView()
        self.webFrame.load(QUrl(URL))

        v_box.addWidget(self.webFrame)

        if process is not None:
            time.sleep(0.5)
            self.webFrame.reload()

    def shutdown_pydoc(self):
        if self.process is not None:
            self.process.kill()

    def find_match(self, word, back=False, sensitive=False, whole=False):
        b = QWebPage.FindBackward if back else None
        s = QWebPage.FindCaseSensitively if sensitive else None
        self.webFrame.page().findText(word)
Example #3
0
class Browser (QWidget, BaseCentralWidget):

    def __init__(self, URL, process=None):
        QWidget.__init__(self)
        BaseCentralWidget.__init__(self)
        self.path = URL
        self.process = process
        
        v_box = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView()
        self.webFrame.load(QUrl(URL))
        
        v_box.addWidget(self.webFrame)

        if process is not None:
            time.sleep(0.5)
            self.webFrame.reload()

    def shutdown_pydoc(self):
        if self.process is not None:
            self.process.kill()

    def find_match(self, word, back=False, sensitive=False, whole=False):
        b = QWebPage.FindBackward if back else None
        s = QWebPage.FindCaseSensitively if sensitive else None
        self.webFrame.page().findText(word)
    def _create_view(self, svg, section=None):
        view = QWebView(self)
        view.setRenderHint(QtGui.QPainter.TextAntialiasing, False)
        view.setPage(LoggingWebPage())
        view.setContextMenuPolicy(QtCore.Qt.PreventContextMenu)

        # the HTML page that will contain the SVG
        path = os.path.dirname(os.path.realpath(__file__))
        html = QUrl(os.path.join(path, "index.html"))  # make file configurable

        # setup the JS interface
        frame = view.page().mainFrame()
        self.js = JSInterface(frame)
        #self.js.registered.connect(self.register)
        self.js.visibility.connect(self.listen)

        # mouse interaction signals
        self.clicked = self.js.leftclicked
        self.rightClicked = self.js.rightclicked

        # Inject JSInterface into the JS global namespace as "Widget"
        frame.addToJavaScriptWindowObject('Widget', self.js)  # confusing?

        # when the page (and all the JS) has loaded, load the SVG
        def load_svg():
            print "blorrt", svg
            self.js.load(svg, section)
        view.loadFinished.connect(load_svg)

        # load the page
        # print "url", QUrl(url)
        view.load(html)

        return view
Example #5
0
class HelpView(SizePersistedDialog):
    '''
    Modeless dialog for presenting HTML help content
    '''
    def __init__(self, parent, icon, prefs, html=None, page=None, title=''):
        self.prefs = prefs
        #QDialog.__init__(self, parent=parent)
        super(HelpView, self).__init__(parent, 'help_dialog')
        self.setWindowTitle(title)
        self.setWindowIcon(icon)
        self.l = QVBoxLayout(self)
        self.setLayout(self.l)

        self.wv = QWebView()
        if html is not None:
            self.wv.setHtml(html)
        elif page is not None:
            self.wv.load(QUrl(page))
        self.wv.setMinimumHeight(100)
        self.wv.setMaximumHeight(16777215)
        self.wv.setMinimumWidth(400)
        self.wv.setMaximumWidth(16777215)
        self.wv.setGeometry(0, 0, 400, 100)
        self.wv.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.l.addWidget(self.wv)

        # Sizing
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.resize_dialog()
class BrowserOwner(object):
    def __init__(self, vkRequestProcessor):
        self.vkRequestProcessor = vkRequestProcessor
        self.vkRequestProcessor.openUrl.connect(self.openUrl)
        self.vkRequestProcessor.hideBrowser.connect(self.hideBrowser)
        self.vkRequestProcessor.captchaNeeded.connect(self.showCaptcha)
        self.browser = QWebView()
        self.browser.urlChanged.connect(self.urlChanged)

    def openUrl(self, url):
        self.browser.load(QUrl(url))
        self.browser.show()

    def showCaptcha(self, url):
        captchaDialog = CaptchaDialog(self, url, self.captchaTyped)
        captchaDialog.captchaTyped.connect(self.captchaTyped)
        captchaDialog.exec_()

    def hideBrowser(self):
        self.browser.hide()

    def urlChanged(self, url):
        self.vkRequestProcessor.urlChanged(url)

    def captchaTyped(self, captchaText):
        self.vkRequestProcessor.setCaptchaText(unicode(captchaText))
Example #7
0
class DocWindow(QWidget):
    app = None

    def __init__(self, app):
        super(DocWindow, self).__init__()
        DocWindow.app = app
        self.vlayout = QVBoxLayout()
        self.view = DocView()
        self.backbtn = QPushButton('Back')
        self.closebtn = QPushButton('Close')
        self.vlayout.setContentsMargins(1, 1, 1, 1)
        self.vlayout.setSpacing(1)
        self.vlayout.addWidget(self.view)
        hlayout = QHBoxLayout()
        buttonbox = QWidget()
        buttonbox.setLayout(hlayout)
        self.vlayout.addWidget(buttonbox)
        hlayout.addWidget(self.closebtn)
        hlayout.addWidget(self.backbtn)
        self.closebtn.clicked.connect(self.hide)
        self.backbtn.clicked.connect(self.view.back)
        self.setLayout(self.vlayout)
        self.setWindowTitle('BlueSky documentation')

    def show_cmd_doc(self, cmd):
        if not cmd:
            cmd = 'Command-Reference'
        self.view.load(
            QUrl.fromLocalFile(
                QFileInfo('data/html/' + cmd.lower() +
                          '.html').absoluteFilePath()))
Example #8
0
class HelpWidget(QtGui.QDialog):

    force_quit = QtCore.pyqtSignal()

    def __init__(self, parent=None):

        super(HelpWidget, self).__init__(parent)
        self._layout = None
        self._msg_widget = None
        self._url_widget = None

        self._init_ui()

        return

    def _init_ui(self):

        self._layout = QtGui.QVBoxLayout(self)

        man_paths = self._get_man_paths()

        if man_paths is None:
            self._init_message()
        else:
            self._init_help(man_paths)

        self.setLayout(self._layout)

        self.resize(900, 800)
        self.setWindowTitle("DTOcean User Manual")

        return

    def _init_message(self):

        text = "No manuals installated"
        self._msg_widget = Message(self, text)

        self._layout.addWidget(self._msg_widget)

        return

    def _init_help(self, path_dict):

        index_path = os.path.join(path_dict["man_user_path"], "index.html")
        url = QUrl.fromLocalFile(index_path)

        self._url_widget = QWebView(self)
        self._url_widget.load(url)
        self._url_widget.show()

        self._layout.addWidget(self._url_widget)

        return

    def _get_man_paths(self):

        path_dict = get_install_paths()

        return path_dict
Example #9
0
class KontenaApp(object):

    def __init__(self, argv):
        self.app = app = QApplication(argv)
        self.browser = QWebView()
        requests_table = RequestsTable()
        manager = KontenaManager(self, requests_table)
        page = QWebPage()
        page.setNetworkAccessManager(manager)
        self.browser.setPage(page)
        grid = QGridLayout()
        grid.addWidget(self.browser, 0, 0)
        # grid.addWidget(requests_table, 4, 0)
        self.window = QWidget()
        self.window.setLayout(grid)

    def open_app(self, data):
        data.seek(23)
        self.kontena = ZipFile(data)

    def read_file(self, file_name):
        return self.kontena.read(file_name)

    def exe(self):
        self.browser.load(QUrl('file:///index.html'))
        self.window.show()
        sys.exit(self.app.exec_())
    def initUI(self,x,y,url):
        self.setGeometry(x,y,650,400)

        print url
        browser = QWebView(self)
        browser.load(QUrl(url))
        browser.show()
Example #11
0
class DocWindow(QWidget):
    app = None

    def __init__(self, app):
        super(DocWindow, self).__init__()
        DocWindow.app = app
        self.vlayout  = QVBoxLayout()
        self.view     = DocView()
        self.backbtn  = QPushButton('Back')
        self.closebtn = QPushButton('Close')
        self.vlayout.setContentsMargins(1, 1, 1, 1)
        self.vlayout.setSpacing(1)
        self.vlayout.addWidget(self.view)
        hlayout = QHBoxLayout()
        buttonbox = QWidget()
        buttonbox.setLayout(hlayout)
        self.vlayout.addWidget(buttonbox)
        hlayout.addWidget(self.closebtn)
        hlayout.addWidget(self.backbtn)
        self.closebtn.clicked.connect(self.hide)
        self.backbtn.clicked.connect(self.view.back)
        self.setLayout(self.vlayout)
        self.setWindowTitle('BlueSky documentation')

    def show_cmd_doc(self, cmd):
        if not cmd:
            cmd = 'Command-Reference'
        self.view.load(QUrl.fromLocalFile(QFileInfo('data/html/' + cmd.lower() + '.html').absoluteFilePath()))
Example #12
0
    def _create_view(self, svg, section=None):
        view = QWebView(self)
        view.setRenderHint(QtGui.QPainter.TextAntialiasing, False)
        view.setPage(LoggingWebPage())
        view.setContextMenuPolicy(QtCore.Qt.PreventContextMenu)

        # the HTML page that will contain the SVG
        path = os.path.dirname(os.path.realpath(__file__))
        html = QUrl(os.path.join(path, "index.html"))  # make file configurable

        # setup the JS interface
        frame = view.page().mainFrame()
        self.js = JSInterface(frame)
        #self.js.registered.connect(self.register)
        self.js.visibility.connect(self.listen)

        # mouse interaction signals
        self.clicked = self.js.leftclicked
        self.rightClicked = self.js.rightclicked

        # Inject JSInterface into the JS global namespace as "Widget"
        frame.addToJavaScriptWindowObject('Widget', self.js)  # confusing?

        # when the page (and all the JS) has loaded, load the SVG
        def load_svg():
            print "blorrt", svg
            self.js.load(svg, section)

        view.loadFinished.connect(load_svg)

        # load the page
        # print "url", QUrl(url)
        view.load(html)

        return view
Example #13
0
def mainPyQt4Youtube():
    # 必要なモジュールのimport
    from PyQt4.QtCore import QUrl
    from PyQt4.QtGui import QApplication
    from PyQt4.QtWebKit import QWebView, QWebSettings
    from PyQt4.QtNetwork import QNetworkProxyFactory

    url = 'https://www.youtube.com/?hl=ja&gl=JP'

    app = QApplication(sys.argv)

    # Youtube動画を読み込むための設定
    QNetworkProxyFactory.setUseSystemConfiguration(True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.DnsPrefetchEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.JavascriptEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.AutoLoadImages, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.LocalStorageEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.PrivateBrowsingEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)

    # QWebViewによるWebページ表示
    browser = QWebView()
    browser.load(QUrl(url))
    browser.setEnabled(True)
    browser.show()
    sys.exit(app.exec_())
class HelpView(SizePersistedDialog):
    """
    Modeless dialog for presenting HTML help content
    """

    def __init__(self, parent, icon, prefs, html=None, page=None, title=""):
        self.prefs = prefs
        # QDialog.__init__(self, parent=parent)
        super(HelpView, self).__init__(parent, "help_dialog")
        self.setWindowTitle(title)
        self.setWindowIcon(icon)
        self.l = QVBoxLayout(self)
        self.setLayout(self.l)

        self.wv = QWebView()
        if html is not None:
            self.wv.setHtml(html)
        elif page is not None:
            self.wv.load(QUrl(page))
        self.wv.setMinimumHeight(100)
        self.wv.setMaximumHeight(16777215)
        self.wv.setMinimumWidth(400)
        self.wv.setMaximumWidth(16777215)
        self.wv.setGeometry(0, 0, 400, 100)
        self.wv.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.l.addWidget(self.wv)

        # Sizing
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.resize_dialog()
Example #15
0
    def showAuthDialog(self):
        from PyQt4.QtWebKit import QWebView

        win = QWebView()
        win.titleChanged.connect(self.getKey)
        win.show()
        win.load(QUrl(self.auth_url))
Example #16
0
	def setMailData(self, d):
		ll = d['data'][0]
		data = d['data'][1]
		i = 0
		for m in self.mails :
			if m.idx == d['number'] : break
			else : i += 1
		fileName = None
		if d['type'] == 'html' :
			_data = changeImagePath(data, d['boundary'])
			''' create temporary html-file '''
			fileName = os.path.join(self.iconDatabasePath, randomString(24) + '.html')
			try :
				with open(fileName, 'w') as f :
					f.write(insertMetaData(_data))
			except Exception, err :
				print dateStamp(), err
				with open(fileName, 'w') as f :
					f.write(str(err))
			finally : pass 
			wdg = QWebView()
			wdg.triggerPageAction(QWebPage.Reload, True)
			wdg.triggerPageAction(QWebPage.Stop, True)
			wdg.triggerPageAction(QWebPage.Back, True)
			wdg.triggerPageAction(QWebPage.Forward, True)
			wdg.settings().setAttribute(QWebSettings.AutoLoadImages, \
										self.Parent.autoLoadImage)
			wdg.settings().setAttribute(QWebSettings.PrivateBrowsingEnabled, \
										self.Parent.privateEnable)
			if wdg.settings().iconDatabasePath().isEmpty() :
				wdg.settings().setIconDatabasePath(self.iconDatabasePath)
			wdg.load(QUrl('file://' + fileName))
			#print dateStamp(), QUrl('file://' + fileName), '  created'
			wdg.show()
			self.webViewWDGs.append(wdg)
Example #17
0
def mainPyQt4Youtube():
    # 必要なモジュールのimport
    from PyQt4.QtCore import QUrl
    from PyQt4.QtGui import QApplication
    from PyQt4.QtWebKit import QWebView, QWebSettings
    from PyQt4.QtNetwork import QNetworkProxyFactory

    url = "https://www.youtube.com/?hl=ja&gl=JP"

    app = QApplication(sys.argv)

    # Youtube動画を読み込むための設定
    QNetworkProxyFactory.setUseSystemConfiguration(True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.DnsPrefetchEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.JavascriptEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.AutoLoadImages, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.LocalStorageEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.PrivateBrowsingEnabled, True)
    QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)

    # QWebViewによるWebページ表示
    browser = QWebView()
    browser.load(QUrl(url))
    browser.setEnabled(True)
    browser.show()
    sys.exit(app.exec_())
Example #18
0
class UploadFiles(QWidget):
    
    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        self.web = QWebView()
        self.web.load(QUrl('http://wingedbox.com/upload_files'))
        vbox.addWidget(self.web)
Example #19
0
class Gafica_ruta(QDialog):
	def __init__(self,parent=None):
		QWidget.__init__(self, parent)
		self.resize(530,540)
		self.webview =QWebView()
		self.webview.load(QUrl("file:///home/cidte/programas de python/Ejercicio de Python/partes del codigo/data_table.html"))
		self.la=QVBoxLayout()
		self.la.addWidget(self.webview)
		self.setLayout(self.la)
Example #20
0
 def showThumbnail(self, record):
     d = QDialog()
     webView = QWebView(d)
     webView.setGeometry(300, 300, 300, 300)
     webView.load(QUrl(record["thumbnail"]))
     d.setWindowTitle("Thumbnail: " + record["satelliteName"] + ":" +
                      record["productId"])
     d.setWindowModality(Qt.ApplicationModal)
     d.exec_()
	def _run(self):
		self.retval = 'NOK'

		self.handler_response_cache = []

		injected_qt_request = InjectedQNetworkRequest(self.start_urllib_request)

		self.nam = InjectedQNetworkAccessManager(ignore_ssl_errors=True)
		self.nam.setInjectedResponse(
			self.start_urllib_request,
			self.start_urllib_response,
			self.cookie_jar
			)
		self.nam.setAutoCloseUrls(self.auto_close_urls)

		self.nam.autocloseOk.connect(self.autoclose_ok)
		self.nam.autocloseFailed.connect(self.autoclose_failed)

		self.nam.requestFinishing.connect(self._update_handler_results)

		app = QApplication([])
		grid = QGridLayout()
		browser = QWebView()

		page = browser.page()
		page.setNetworkAccessManager(self.nam)

		browser.load(injected_qt_request, self.nam.GetOperation)

		test_ok_button = QPushButton("Test &OK")
		test_ok_button.clicked.connect(self.button_ok)

		test_failed_button = QPushButton("Test &Failed")
		test_failed_button.clicked.connect(self.button_failed)

		test_abort_button = QPushButton("Abort Test")
		test_abort_button.clicked.connect(self.button_abort)

		url_input = UrlInput(browser)

		grid.addWidget(test_ok_button, 1, 0)
		grid.addWidget(test_failed_button, 1, 1)
		grid.addWidget(test_abort_button, 1, 2)
		grid.addWidget(url_input, 2, 0, 1, 3)
		grid.addWidget(browser, 4, 0, 1, 3)

		main_frame = QWidget()
		main_frame.setLayout(grid)
		main_frame.show()

		app.exec_()

		processed = False
		if self.retval == 'OK' or self.retval == 'NOK':
			processed = True

		return self.retval
Example #22
0
    def __init__(self, gamedata_edit, QWidget=None):
        QtGui.QVBoxLayout.__init__(self, QWidget)
        self.gamedata_edit = gamedata_edit

        web_view = QWebView()
        web_view.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        web_view.connect(web_view, SIGNAL("linkClicked(const QUrl&)"), self.link_clicked)
        web_view.load(QUrl(WEBSITE_ADDRESS))
        self.addWidget(web_view)
Example #23
0
class Dialog(QWidget):
    def __init__(self):
        super(Dialog, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                            | Qt.Popup | Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setWindowOpacity(app.DialogOpacity)
        self.resize(app.DialogWidth, app.DialogHeight)
        point = Utils.getDesktopCenterPoint(self)
        self.move(point["x"], point["y"])
        self.webview = QWebView(self)
        self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled,
                                             True)
        self.webview.settings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, app.Debug)
        self.webview.settings().setAttribute(
            QWebSettings.LocalContentCanAccessRemoteUrls, True)
        self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled,
                                             True)
        self.webview.settings().setLocalStoragePath(app.HomeDir + "/data")
        #self.webview.setContextMenuPolicy(Qt.NoContextMenu)
        self.webview.settings().setDefaultTextEncoding("utf-8")
        self.webview.setGeometry(1, 1, self.width() - 2, self.height() - 2)
        self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(
            self.setJavaScriptObject)
        self.webview.setStyleSheet(
            "QWebView{background-color: rgba(255, 193, 245, 0%); }")
        self.webview.page().networkAccessManager().setCookieJar(app.CookieJar)
        self.webview.load(QUrl.fromLocalFile(app.ViewDir + app.DialogSrc))

    def setJavaScriptObject(self):
        self.webview.page().mainFrame().addToJavaScriptWindowObject(
            "_window_", self)
        self.webview.page().mainFrame().addToJavaScriptWindowObject(
            "_notifications_", app._notifications_)

    @pyqtSignature("")
    def quit(self):
        self.close()

    @pyqtSignature("int,int")
    def moveTo(self, offsetX, offsetY):
        self.move(self.x() + offsetX, self.y() + offsetY)

    @pyqtSignature("", result="QString")
    def loadHtml(self):
        if app.NewDialogHtml != "":
            return app.NewDialogHtml

        file_object = open(app.ViewDir + app.DialogCon)
        try:
            dialogHtml = file_object.read()
        finally:
            file_object.close()
        app.NewDialogHtml = dialogHtml
        return dialogHtml
Example #24
0
class ReportWidget(QtGui.QWidget):
    def __init__(self, url, parent=None):
        super(ReportWidget, self).__init__(parent)
        layout = QtGui.QVBoxLayout(self)
        self.web = QWebView()
        layout.addWidget(self.web)
        self.load_url(url)

    def load_url(self, url):
        self.web.load(QUrl(url))
Example #25
0
    def showDocumentation(self):
        if self._documentation is None:
            doc = QWebView(self)
            doc.load(QUrl("doc/html/index.html"))
            self._documentation = QDockWidget("Documentation", self)
            self._documentation.setWidget(doc)
            self._documentation.closeEvent = lambda _: self.hide_documentation(
            )

        self.addDockWidget(Qt.LeftDockWidgetArea, self._documentation)
 def _add_html5_toolbar(self):
     from PyQt4.QtCore import QUrl
     from PyQt4.QtWebKit import QWebView, QWebSettings
     view = QWebView()
     view.load(QUrl("dimensionality_reduction/html5/index.html?stylesheet=ui_720p"))
     view.show()
     view.setFixedSize(self.args.preferred_width, HTML5_TOOLBAR_HEIGHT)
     self.setFixedSize(self.args.preferred_width, self.args.preferred_height)
     self.outer_vertical_layout.addWidget(view)
     view.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
class NotificationPresenter(QDialog):
    def __init__(self):
        super(NotificationPresenter, self).__init__()
        rect = QApplication.desktop().availableGeometry()
        self.setGeometry(QRect(rect.width() - 300, 0, 300, rect.height()))
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                            | Qt.Popup | Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.webview = QWebView(self)
        self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled,
                                             True)
        self.webview.settings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        self.webview.settings().setAttribute(
            QWebSettings.LocalContentCanAccessRemoteUrls, True)
        self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled,
                                             True)
        self.webview.settings().setLocalStoragePath(AppProperty.HomeDir +
                                                    "/data")
        self.webview.setContextMenuPolicy(Qt.NoContextMenu)
        self.webview.settings().setDefaultTextEncoding("utf-8")
        self.webview.setGeometry(0, 0, self.width(), self.height())
        self.webview.setStyleSheet(
            "QWebView{background-color: rgba(255, 193, 245, 0%); }")
        self.webview.load(
            QUrl.fromLocalFile(AppProperty.HomeDir +
                               "/html/notification.html"))
        self.webview.page().linkClicked.connect(self.linkClicked)
        self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(
            self.setJavaScriptObject)
        self.webview.page().setLinkDelegationPolicy(
            self.webview.page().DelegateAllLinks)

    def linkClicked(self, url):
        webbrowser.open_new_tab(url.toString())

    def setJavaScriptObject(self):
        self.webview.page().mainFrame().addToJavaScriptWindowObject(
            "_notifications_", self)

    @pyqtSignature("QString,QString,QString,int")
    def showNotification(self, title, flag, html, delay):
        self.show()
        self.webview.page().mainFrame().evaluateJavaScript(
            'showNotification("%s","%s","%s",%d)' % (title, flag, html, delay))

    @pyqtSignature("QString")
    def cleanNotification(self, flag):
        self.webview.page().mainFrame().evaluateJavaScript(
            'removeNotice("%s")' % (flag))

    @pyqtSignature("int")
    def sleep(self, ms):
        time.sleep(ms / 1000)
Example #28
0
    def addDocumentationTab(self, dlgProcessTab, abstract):
        # Check for URL
        if str(abstract).find("http://") == 0:
            textBox = QWebView(dlgProcessTab)
            textBox.load(QUrl(abstract))
            textBox.show()
        else:
            textBox = QTextBrowser(dlgProcessTab)
            textBox.setText(QString(abstract))

        dlgProcessTab.addTab(textBox, "Documentation")
Example #29
0
def main():
    """
		Run CLIkipedia in GUI mode.
	"""
    app = QApplication(sys.argv)
    browser = QWebView()
    start_server()
    time.sleep(3)
    browser.load(QUrl('http://localhost:9001'))
    browser.show()
    sys.exit(app.exec_())
Example #30
0
 def start(self, urls):
     for browser_id, url in enumerate(urls):
         self.page_url = self._path(url)
         web_view = QWebView()
         web_view.settings().setAttribute(QWebSettings.AutoLoadImages,
                                          False)
         loaded = partial(self._load_finished, browser_id)
         web_view.loadFinished.connect(loaded)
         web_view.load(QUrl(url))
         self.browsers[browser_id] = (web_view, False)
     return self.result
Example #31
0
    def runConfigWizard(self):
        try:
            oAuthHandler = tweepy.OAuthHandler(self.options_string['hidden_application_key'],
                                               self.options_string['hidden_application_secret'])
            authorizationURL = oAuthHandler.get_authorization_url(True)

            self.wizard.setWindowTitle('Twitter plugin configuration wizard')
            page1 = QWizardPage()
            page2 = QWizardPage()
            layout1 = QVBoxLayout()
            layout2 = QVBoxLayout()
            layoutInputPin = QHBoxLayout()

            label1a = QLabel(
                'Click next to connect to twitter.com . Please login with your account and follow the instructions in '
                'order to authorize creepy')
            label2a = QLabel(
                'Copy the PIN that you will receive once you authorize cree.py in the field below and click finish')
            pinLabel = QLabel('PIN')
            inputPin = QLineEdit()
            inputPin.setObjectName('inputPin')

            analysisHtml = QWebView()
            analysisHtml.load(QUrl(authorizationURL))

            layout1.addWidget(label1a)
            layout2.addWidget(analysisHtml)
            layout2.addWidget(label2a)
            layoutInputPin.addWidget(pinLabel)
            layoutInputPin.addWidget(inputPin)
            layout2.addLayout(layoutInputPin)

            page1.setLayout(layout1)
            page2.setLayout(layout2)
            page2.registerField('inputPin*', inputPin)
            self.wizard.addPage(page1)
            self.wizard.addPage(page2)
            self.wizard.resize(800, 600)

            if self.wizard.exec_():
                try:
                    oAuthHandler.get_access_token(str(self.wizard.field('inputPin').toString()).strip())
                    self.options_string['hidden_access_token'] = oAuthHandler.access_token
                    self.options_string['hidden_access_token_secret'] = oAuthHandler.access_token_secret
                    self.saveConfiguration(self.config)
                except Exception, err:
                    logger.error(err)
                    self.showWarning('Error completing the wizard',
                                     'We were unable to obtain the access token for your account, please try to run '
                                     'the wizard again. Error was {0}'.format(err.message))

        except Exception, err:
            logger.error(err)
            self.showWarning('Error completing the wizard', 'Error was: {0}'.format(err.message))
Example #32
0
class QT_url(QDialog):
	def __init__(self,direc,w,h,nom,parent=None):
		QWidget.__init__(self, parent)
		self.resize(w,h)
		#print nom
		self.setWindowTitle(nom)
		self.webview = QWebView()
		self.webview.load(QUrl(direc))
		self.la=QVBoxLayout()
		self.la.addWidget(self.webview)
		self.setLayout(self.la)
Example #33
0
    def run(field, value):
        """
        Run an action with only one value as parameter

        @param field:Type of the action
        @type field:str
        @param value:Value of the field for one entity
        @type value:str
        """

        if value == '':
            iface.messageBar().pushMessage(tr(
                "QuickOSM",
                u"Sorry man, this field is empty for this entity."),
                                           level=QgsMessageBar.WARNING,
                                           duration=7)
        else:
            field = unicode(field, "UTF-8")
            value = unicode(value, "UTF-8")

            if field in ["url", "website", "wikipedia"]:
                var = QDesktopServices()
                url = None

                if field == "url" or field == "website":
                    url = value

                if field == "ref_UAI":
                    url = "http://www.education.gouv.fr/pid24302/annuaire-" \
                          "resultat-recherche.html?lycee_name=" + value

                if field == "wikipedia":
                    url = "http://en.wikipedia.org/wiki/" + value

                var.openUrl(QUrl(url))

            elif field == "josm":
                import urllib2
                try:
                    url = "http://localhost:8111/load_object?objects=" + value
                    urllib2.urlopen(url).read()
                except urllib2.URLError:
                    iface.messageBar().pushMessage(
                        tr("QuickOSM",
                           u"The JOSM remote seems to be disabled."),
                        level=QgsMessageBar.CRITICAL,
                        duration=7)

            # NOT USED
            elif field == "rawedit":
                url = QUrl("http://rawedit.openstreetmap.fr/edit/" + value)
                web_browser = QWebView(None)
                web_browser.load(url)
                web_browser.show()
Example #34
0
def createGuiFor(application):
    qtapp = QApplication(sys.argv)
    webapp = FlaskThread(application)
    webapp.start()
    qtapp.aboutToQuit.connect(webapp.terminate)
    webview = QWebView()
    webview.load(QUrl(ROOT_URL))
    webview.show()
    webview.setWindowTitle("MyApp")
    webview.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
    return qtapp.exec_()
Example #35
0
  def addDocumentationTab(self, dlgProcessTab,  abstract):
    # Check for URL
    
    try:
      textBox = QWebView(dlgProcessTab)
      textBox.load(QUrl(abstract))
      textBox.show()
    except:
      textBox = QTextBrowser(dlgProcessTab)
      textBox.setText(pystring(abstract))

    dlgProcessTab.addTab(textBox, "Documentation")
class Widgets(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Simple Web Browser")
        self.widget = QWidget(self)
        self.webview = QWebView()
        self.webview.load(QUrl("http://www.recursospython.com/"))
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.webview)
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)
        QMetaObject.connectSlotsByName(self)
Example #37
0
    def run(field, value):
        """
        Run an action with only one value as parameter

        @param field:Type of the action
        @type field:str
        @param value:Value of the field for one entity
        @type value:str
        """

        if value == '':
            iface.messageBar().pushMessage(
                tr("OSMData",
                   u"Sorry man, this field is empty for this entity."),
                level=QgsMessageBar.WARNING, duration=7)
        else:
            field = unicode(field, "UTF-8")
            value = unicode(value, "UTF-8")

            if field in ["url", "website", "wikipedia"]:
                var = QDesktopServices()
                url = None

                if field == "url" or field == "website":
                    url = value

                if field == "ref_UAI":
                    url = "http://www.education.gouv.fr/pid24302/annuaire-" \
                          "resultat-recherche.html?lycee_name=" + value

                if field == "wikipedia":
                    url = "http://en.wikipedia.org/wiki/" + value

                var.openUrl(QUrl(url))

            elif field == "josm":
                import urllib2
                try:
                    url = "http://localhost:8111/load_object?objects=" + value
                    urllib2.urlopen(url).read()
                except urllib2.URLError:
                    iface.messageBar().pushMessage(
                        tr("OSMData",
                           u"The JOSM remote seems to be disabled."),
                        level=QgsMessageBar.CRITICAL,
                        duration=7)

            # NOT USED
            elif field == "rawedit":
                url = QUrl("http://rawedit.openstreetmap.fr/edit/" + value)
                web_browser = QWebView(None)
                web_browser.load(url)
                web_browser.show()
Example #38
0
class ShoutCastForm(PluginBase.PluginBase):
    '''Grab Shoutcast streams and save them as "bookmarks" - and play them on
       the currently selected server.

       General shoutcast information is not preserved between runs. Also, the
       shoutcast server/API is pretty lame so timeouts actually occur quite
       frequently.
    '''
    moduleName = '&Shoutcast'
    moduleIcon = "network-workgroup"

    def load(self):
        pass

    def event(self, event):
        if event.type() == QEvent.Paint:
            if not hasattr(self, 'webView'):
                self._load()
                self.event = super(ShoutCastForm, self).event
        return False

    def _load(self):
        self.cookie = QNetworkCookie('Settings', 'Player~others|Bandwidth~ALL|Codec~ALL')
        self.cookie.setDomain('.shoutcast.com')
        self.cookie.setExpirationDate(QDateTime())
        self.cookie.setPath('/')

        self.webView = QWebView(self)
        self.webPage = self.webView.page()
        self.cookiejar = QNetworkCookieJar()
        self.cookiejar.setAllCookies([self.cookie])
        self.webPage.networkAccessManager().setCookieJar(self.cookiejar)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.webView)
        self.webView.load(QUrl(HOMEURL))
        self.webPage.setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
        self.connect(self.webPage, SIGNAL('linkClicked(const QUrl&)'), self._processLink)

    def _processLink(self, url):
        if url.host() == TUNEIN:
            self._playStation(unicode(url.toString()))
        else:
            self.webView.load(url)
            self.webView.show()

    def _playStation(self, url):
        try:
            streamList = streamTools.getStreamList(url)
        except streamTools.ParseError:
            return
        if streamList:
            self.modelManager.playQueue.extend(streamList)
Example #39
0
class WebKitFrame(qg.QFrame):
    def __init__(self, url=None, parent=None):
        from PyQt4.QtWebKit import QWebView

        qg.QFrame.__init__(self, parent)
        layout = qg.QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.setLayout(layout)
        self.web_widget = QWebView()
        layout.addWidget(self.web_widget, 0, 0)
        if url:
            self.web_widget.load(qc.QUrl(url))
Example #40
0
class HelpWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint | Qt.Window)
        self.setVisible(False)

        self._view_help = QWebView(self)
        self._view_help.load(resource_html("helppage.html"))
        self._view_help.show()

        f_layout = QHBoxLayout()
        f_layout.addWidget(self._view_help)

        self.setLayout(f_layout)
Example #41
0
class WebKitFrame(QFrame):

    def __init__(self, url=None, parent=None):
        from PyQt4.QtWebKit import QWebView

        QFrame.__init__(self, parent)
        layout = QGridLayout()
        layout.setContentsMargins(0,0,0,0)
        layout.setSpacing(0)
        self.setLayout(layout)
        self.web_widget = QWebView()
        layout.addWidget(self.web_widget, 0,0)
        if url:
            self.web_widget.load(QUrl(url))
Example #42
0
class WebRender(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        vbox = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView()
        QWebSettings.globalSettings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        vbox.addWidget(self.webFrame)

    def render_page(self, url):
        self.webFrame.load(QUrl('file:///' + url))
Example #43
0
class TweetWindow(QWidget):
    def __init__(self):  
        super(TweetWindow, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint|Qt.Popup|Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground,True)
        self.resize(550,520)
        point = Utils.getDesktopCenterPoint(self)
        self.move(point["x"],point["y"])
        self.webview = QWebView(self)
        self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
        self.webview.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.webview.settings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
        self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled, True)
        self.webview.settings().setLocalStoragePath(AppProperty.HomeDir+"/data")
        #self.webview.setContextMenuPolicy(Qt.NoContextMenu)
        self.webview.settings().setDefaultTextEncoding("utf-8")
        self.webview.setGeometry(1,1,self.width()-2,self.height()-2)
        self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(self.setJavaScriptObject)
        self.webview.setStyleSheet("QWebView{background-color: rgba(255, 193, 245, 0%); }")
        self.webview.page().networkAccessManager().setCookieJar(AppProperty.CookieJar)
        self.webview.load(QUrl.fromLocalFile(AppProperty.HomeDir+"/html/tweetWindow.html"))
        
    def setJavaScriptObject(self):
        self.webview.page().mainFrame().addToJavaScriptWindowObject("_window_", self)
        #self.webview.page().mainFrame().addToJavaScriptWindowObject("_service_", self._service_)
        self.webview.page().mainFrame().addToJavaScriptWindowObject("_notifications_", AppProperty._notifications_)
          
    @pyqtSignature("")
    def quit(self):
        self.close()
    
    @pyqtSignature("int,int")
    def moveTo(self,offsetX,offsetY):
        self.move(self.x()+offsetX,self.y()+offsetY)
    
    @pyqtSignature("",result="QString")
    def loadHtml(self):
        if AppProperty.NewTweetHtml!="":
            return AppProperty.NewTweetHtml
        
        file_object = open('html/sendTweetPage.html')
        try:
            tweetHtml = file_object.read()
        finally:
            file_object.close()
        tweetHtml = tweetHtml.replace("${home}","file:///"+AppProperty.HomeDir.replace("\\","/")+"/")
        AppProperty.NewTweetHtml = tweetHtml
        return tweetHtml
def url2image(url, file_name=None):
    """Function at the specified url downloads the page and stores it QImage object and returns it.
    If you pass file_name, then the function will save the picture in the file.

    Функция по указанному url загружает страницу и сохраняет ее объект QImage и возвращает его.
    Если передать file_name, тогда функция сохранит в файл картинку.
    """

    # Нужно создавать только один раз
    global qApp
    if qApp is None:
        qApp = QApplication([])

        # Пришлось добавить из-за того, что картинки не прогружались
        load_pyqt4_plugins()

    # TODO: прятать вертикальный и горизонтальный ползунки
    # Загрузка url и ожидание ее
    view = QWebView()
    view.setPage(WebPage())
    # view.show()

    view.load(QUrl(url))
    loop = QEventLoop()
    view.loadFinished.connect(loop.quit)
    loop.exec_()

    # Запрашиваем через javascript размеры страницы сайта
    width = view.page().mainFrame().evaluateJavaScript(
        "window.document.body.scrollWidth")
    height = view.page().mainFrame().evaluateJavaScript(
        "window.document.body.scrollHeight")

    # Устанавливаем границы документа
    view.page().setViewportSize(QSize(width, height))

    img = QImage(width, height, QImage.Format_ARGB32)
    painter = QPainter(img)
    painter.setRenderHint(QPainter.HighQualityAntialiasing)
    view.page().mainFrame().render(painter)
    painter.end()

    if file_name:
        img.save(file_name)

    # qApp.exec()

    return img
Example #45
0
class MainWindow(QMainWindow):
    def __init__(self, model):
        super(MainWindow, self).__init__()
        self.model = model
        self.model.friendsReady.connect(self.showFriends)
        self.initUI()

    def initUI(self):
        self.setGeometry(windowLeft, windowTop, windowWidth, windowHeight)
        self.setWindowTitle(u"Бугагашенька")    

        mainWidget = QWidget()
        mainLayout = QVBoxLayout()
        authButton = QPushButton(u"Получить список друзей")
        authButton.clicked.connect(self.authButtonClicked)
        mainLayout.addWidget(authButton)
        self.textEdit = QTextEdit()
        mainLayout.addWidget(self.textEdit)
        mainWidget.setLayout(mainLayout)
        self.setCentralWidget(mainWidget)

        self.browser = QWebView()
        self.browser.urlChanged.connect(self.browserUrlChanged)

        self.show()

    def authButtonClicked(self):
        if len(self.model.accessToken) < 10:
            self.browser.load(QUrl(authUrl))
            self.browser.show()
        else:
            self.model.getFriendsAsync()	

    def browserUrlChanged(self, url):
        urlStr = url.toString()
        if urlStr[:len(authorizedUrl)] == authorizedUrl:
            fragment = str(url.fragment())
            fragmentParameters = [param.split("=") for param in fragment.split("&")]
            for param in fragmentParameters:
                if param[0] == "access_token":
                    self.model.setAccessToken(param[1])
                    break

            self.browser.hide()
            self.model.getFriendsAsync()

    def showFriends(self, friendsStr):
        self.textEdit.setText(friendsStr)
Example #46
0
class DWebview(QtGui.QDialog):
    def __init__(self, html_file, title=u"Information", parent=None):
        QtGui.QDialog.__init__(self, parent)

        layout = QtGui.QVBoxLayout(self)

        self._webview = QWebView(self)
        self._webview.load(QtCore.QUrl(html_file))
        layout.addWidget(self._webview)

        buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok)
        buttons.accepted.connect(self.accept)
        layout.addWidget(buttons)

        self.setWindowTitle(title)
        self.adjustSize()
Example #47
0
def mainPyQt4Simple():
    # 必要なモジュールのimport
    from PyQt4.QtCore import QUrl
    from PyQt4.QtGui import QApplication
    from PyQt4.QtWebKit import QWebView

    url = "https://github.com/tody411/PyIntroduction"

    app = QApplication(sys.argv)

    # QWebViewによるWebページ表示
    browser = QWebView()
    browser.load(QUrl(url))
    browser.show()

    sys.exit(app.exec_())
Example #48
0
def mainPyQt4Simple():
    # 必要なモジュールのimport
    from PyQt4.QtCore import QUrl
    from PyQt4.QtGui import QApplication
    from PyQt4.QtWebKit import QWebView

    url = 'https://github.com/tody411/PyIntroduction'

    app = QApplication(sys.argv)

    # QWebViewによるWebページ表示
    browser = QWebView()
    browser.load(QUrl(url))
    browser.show()

    sys.exit(app.exec_())
Example #49
0
class DWebview(QtGui.QDialog):
    def __init__(self, html_file, title=u"Information", parent=None):
        QtGui.QDialog.__init__(self, parent)

        layout = QtGui.QVBoxLayout(self)

        self._webview = QWebView(self)
        self._webview.load(QtCore.QUrl(html_file))
        layout.addWidget(self._webview)

        buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok)
        buttons.accepted.connect(self.accept)
        layout.addWidget(buttons)

        self.setWindowTitle(title)
        self.adjustSize()
Example #50
0
class BrowserWidget(QWidget, itab_item.ITabItem):

    ###############################################################################
    # RecentProjectItem SIGNALS
    ###############################################################################
    """
    openProject(QString)
    openPreferences()
    dontOpenStartPage()
    """

    ###############################################################################

    def __init__(self, url, process=None, parent=None):
        QWidget.__init__(self, parent)
        itab_item.ITabItem.__init__(self)
        self._id = url
        self._process = process
        vbox = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView(self)
        self.webFrame.setAcceptDrops(False)

        self.webFrame.load(QUrl(url))

        vbox.addWidget(self.webFrame)

        if process is not None:
            time.sleep(0.5)
            self.webFrame.load(QUrl(url))

        self.webFrame.page().currentFrame().setScrollBarPolicy(
            Qt.Vertical, Qt.ScrollBarAsNeeded)
        self.webFrame.page().currentFrame().setScrollBarPolicy(
            Qt.Horizontal, Qt.ScrollBarAsNeeded)

    def start_page_operations(self, url):
        opt = file_manager.get_basename(url.toString())
        self.emit(SIGNAL(opt))

    def shutdown_pydoc(self):
        if self._process is not None:
            self._process.kill()

    def find_match(self, word, back=False, sensitive=False, whole=False):
        self.webFrame.page().findText(word)
Example #51
0
class BrowserWidget(QWidget, itab_item.ITabItem):

###############################################################################
# RecentProjectItem SIGNALS
###############################################################################
    """
    openProject(QString)
    openPreferences()
    dontOpenStartPage()
    """
###############################################################################

    def __init__(self, url, process=None, parent=None):
        QWidget.__init__(self, parent)
        itab_item.ITabItem.__init__(self)
        self._id = url
        self._process = process
        vbox = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView(self)
        self.webFrame.setAcceptDrops(False)

        self.webFrame.load(QUrl(url))

        vbox.addWidget(self.webFrame)

        if process is not None:
            time.sleep(0.5)
            self.webFrame.load(QUrl(url))

        self.webFrame.page().currentFrame().setScrollBarPolicy(
            Qt.Vertical, Qt.ScrollBarAsNeeded)
        self.webFrame.page().currentFrame().setScrollBarPolicy(
            Qt.Horizontal, Qt.ScrollBarAsNeeded)

    def start_page_operations(self, url):
        opt = file_manager.get_basename(url.toString())
        self.emit(SIGNAL(opt))

    def shutdown_pydoc(self):
        if self._process is not None:
            self._process.kill()

    def find_match(self, word, back=False, sensitive=False, whole=False):
        self.webFrame.page().findText(word)
class NotificationPresenter(QDialog):
    
    def __init__(self):
        super(NotificationPresenter, self).__init__()
        rect = QApplication.desktop().availableGeometry()
        self.setGeometry(QRect(rect.width()-300,0,300,rect.height()))
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint|Qt.Popup|Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground,True)
        self.webview = QWebView(self)
        self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
        self.webview.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.webview.settings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
        self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled, True)
        self.webview.settings().setLocalStoragePath(AppProperty.HomeDir+"/data")
        self.webview.setContextMenuPolicy(Qt.NoContextMenu)
        self.webview.settings().setDefaultTextEncoding("utf-8")
        self.webview.setGeometry(0,0,self.width(),self.height())
        self.webview.setStyleSheet("QWebView{background-color: rgba(255, 193, 245, 0%); }")
        self.webview.load(QUrl.fromLocalFile(AppProperty.HomeDir+"/html/notification.html"))
        self.webview.page().linkClicked.connect(self.linkClicked)        
        self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(self.setJavaScriptObject)
        self.webview.page().setLinkDelegationPolicy(self.webview.page().DelegateAllLinks)
        
    def linkClicked(self,url):
        webbrowser.open_new_tab(url.toString())
        
    def setJavaScriptObject(self):
        self.webview.page().mainFrame().addToJavaScriptWindowObject("_notifications_", self)
        
    @pyqtSignature("QString,QString,QString,int")
    def showNotification(self,title,flag,html,delay):
        self.show()
        self.webview.page().mainFrame().evaluateJavaScript('showNotification("%s","%s","%s",%d)' %(title,flag,html,delay))
        
    @pyqtSignature("QString")
    def cleanNotification(self,flag):
        self.webview.page().mainFrame().evaluateJavaScript('removeNotice("%s")' %(flag))
        
    @pyqtSignature("int")
    def sleep(self,ms):
        time.sleep(ms/1000)
         
        

        
Example #53
0
def render_url(url, dest, quality=-1, min_width=800, min_height=600):

    format = get_image_format(dest)

    if format is None:
        raise RuntimeError("Can't handle the specified image format")

    app = QApplication(sys.argv)
    web = QWebView()
    web.load(QUrl(url))

    def save_image():

        try:
            page = web.page()
            frame = page.currentFrame()

            # Grow the viewport to make it fit the whole document
            width = min_width
            height = min_height

            page.setViewportSize(QSize(width, height))

            while frame.scrollBarMaximum(Qt.Horizontal) != 0:
                width += 1
                page.setViewportSize(QSize(width, height))

            while frame.scrollBarMaximum(Qt.Vertical) != 0:
                height += 1
                page.setViewportSize(QSize(width, height))

            # Render the document to an image file
            image = QPixmap(width, height)
            painter = QPainter()
            painter.begin(image)
            frame.render(painter)
            painter.end()
            image.save(dest, format, quality)

        finally:
            QApplication.exit()

    QObject.connect(web, SIGNAL("loadFinished(bool)"), save_image)
    app.exec_()
Example #54
0
class Render(QWebView):
    def __init__(self, url):
        def worker():
            output = False
            running = True
            i = 0
            if output: print 'rendering page...'
            while running:
                time.sleep(5)
                i += 5
                if output: print "in queue", i, "sec"

                self.result = str(
                    self.browser.page().currentFrame().toHtml().toAscii())
                tree = html.fromstring(self.result)
                content = tree.xpath(
                    '//span[@class="venue-name ng-binding"]//text()')
                if len(content) > 0:
                    if output: print "waiting..."
                    time.sleep(5)
                    self.result = str(
                        self.browser.page().currentFrame().toHtml().toAscii())
                    self.app.quit()
                    running = False
                    if output: print "rendering finished\n"
                if i >= 120:
                    self.result = ""
                    self.app.quit()
                    running = False
                    if output: print "rendering failed..."

        self.app = QApplication(sys.argv)
        self.browser = QWebView()
        self.browser.load(QUrl(url))
        #~ self.browser.show()

        thread = threading.Thread(target=worker)
        thread.setDaemon(True)
        thread.start()

        self.app.exec_()
        #~ self.browser.close()
        self.date = datetime.now()
Example #55
0
class Browser(QWidget, BaseCentralWidget):
    def __init__(self, URL, process=None, main=None):
        QWidget.__init__(self)
        BaseCentralWidget.__init__(self)
        self.path = URL
        self.process = process

        v_box = QVBoxLayout(self)
        #Web Frame
        QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled,
                                                   True)
        self.webFrame = QWebView()
        self.webFrame.setAcceptDrops(False)
        factory = WebPluginFactory(self, main)
        self.webFrame.page().setPluginFactory(factory)
        self.webFrame.load(QUrl(URL))

        v_box.addWidget(self.webFrame)

        if process is not None:
            time.sleep(0.5)
            self.webFrame.reload()

        if self.path.endswith(
                'startPage.html') and sys.platform.find('win') != -1:
            content = manage_files.read_file_content(self.path)
            pathCss = os.path.join(resources.PRJ_PATH, 'doc', 'styles',
                                   'ninja.css')
            pathJs = os.path.join(resources.PRJ_PATH, 'doc', 'rsc')
            content = content.replace('styles/ninja.css',
                                      pathCss).replace('src="rsc',
                                                       'src="' + pathJs)
            self.webFrame.setHtml(content)

    def shutdown_pydoc(self):
        if self.process is not None:
            self.process.kill()

    def find_match(self, word, back=False, sensitive=False, whole=False):
        b = QWebPage.FindBackward if back else None
        s = QWebPage.FindCaseSensitively if sensitive else None
        self.webFrame.page().findText(word)
Example #56
0
def renderpdf(url, dest):

    app = QApplication(sys.argv)
    web = QWebView()

    request = QNetworkRequest(QUrl(url))
    request.setRawHeader("X-Rendering-PDF", "true")
    web.load(request)

    printer = QPrinter()
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setOutputFileName(dest)

    def print_file():
        web.print_(printer)
        QApplication.exit()

    QObject.connect(web, SIGNAL("loadFinished(bool)"), print_file)
    app.exec_()
Example #57
0
class LicenseWidget(QtGui.QDialog):
    def __init__(self):
        super(LicenseWidget, self).__init__()
        self.setModal(True)
        self.browser = QWebView()
        self.browser.load(
            QtCore.QUrl('http://www.gnu.org/licenses/gpl-3.0.txt'))
        self.setWindowTitle(i18n("License Agreement - Gobstones"))
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.browser)
        self.setLayout(layout)

    def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.Antialiasing
        painter.begin(self)
        rect = QtCore.QRect(0, 0, 1920, 1080)
        img = QtGui.QImage(':/backgroundWidget.png')
        painter.drawImage(rect, img)
        painter.end()
Example #58
0
class WebRender(QWidget):
    """Render a web page inside the tools dock area."""
    def __init__(self):
        super(WebRender, self).__init__()

        vbox = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView()
        QWebSettings.globalSettings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        vbox.addWidget(self.webFrame)

    def render_page(self, url):
        """Render a web page from a local file."""
        self.webFrame.load(QUrl('file:///' + url))

    def render_from_html(self, html, url=None):
        """Render a webpage from a string."""
        url = url and QUrl(url) or ""
        self.webFrame.setHtml(html, url)
Example #59
-1
class BrowserWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        vlayout = QVBoxLayout()
        
        vlayout.addLayout(self.get_url_bar())
        
        javascript_bar = self.get_javascript_bar()
        vlayout.addLayout(javascript_bar)

        self.browser = QWebView(self)
        self.browser_frame = self.browser.page().currentFrame()
        
        self.connect(self.browser_frame, SIGNAL('javaScriptWindowObjectCleared()'),
                      self.add_javascript_bridge);
        vlayout.addWidget(self.browser)
        
        vlayout.addWidget(QuitButton())
        self.setLayout(vlayout)


    def get_url_bar(self):
        url_bar = QHBoxLayout()
    
        self.url_box = QLineEdit()
        self.connect(self.url_box, SIGNAL('returnPressed()'), self.show_browser)
        
        go = QPushButton(self)
        go.setText("Go")
        self.connect(go, SIGNAL('clicked()'), self.show_browser)
        
        url_bar.addWidget(self.url_box)
        url_bar.addWidget(go)
        return url_bar


    def get_javascript_bar(self):
        javascript_bar = QHBoxLayout()

        self.javascript_box = QLineEdit()
        self.connect(self.javascript_box, SIGNAL('returnPressed()'), self.send_javascript)
        
        ex = QPushButton(self)
        ex.setText("Execute on page")
        self.connect(ex, SIGNAL('clicked()'), self.send_javascript)
        
        javascript_bar.addWidget(self.javascript_box)
        javascript_bar.addWidget(ex)
        return javascript_bar

    def add_javascript_bridge(self):
        self.browser_frame.addToJavaScriptWindowObject("webkitBridge", WebkitBridge())

    def send_javascript(self):
        self.browser.page().currentFrame().evaluateJavaScript(self.javascript_box.text())

    
    def show_browser(self):
        url = QUrl(self.url_box.text())
        self.browser.load(url)