def __init__(self, parent=None): super(Text, self).__init__(parent) # Sentence view self.view, self.page = QWebView(), QWebPage() self.view.setPage(self.page) # TODO: update dynamically on parent widget resize events (somehow?) self.view.setMinimumSize(parent.width(), parent.height() / 2) # Info view self.infoView, self.infoPage = QWebView(), QWebPage() self.infoView.setPage(self.infoPage) self.infoView.setMaximumSize(parent.width() / 2, parent.height()) # Active terms and sentence self.terms, self.example = {}, u'' # Default style self.css = 'solarized-light' # Composition self.compose({QHBoxLayout(): [self.infoView, self.view]}) # Initialize events self.page.linkHovered.connect(self.showInfo) self.page.setLinkDelegationPolicy(QWebPage.DelegateExternalLinks) self.page.linkClicked.connect(self.queryServer) # Initialize style self.clearPages()
def testQVariantListProperty(self): class Obj(object): list = ['foo', 'bar', 'baz'] obj = Obj() wrapper_dict = {} for name in ['list']: getter = lambda arg=None, name=name: getattr(obj, name) wrapper_dict[name] = Property('QVariantList', getter) wrapper = type('PyObj', (QObject,), wrapper_dict) view = QWebView() frame = view.page().mainFrame() frame.addToJavaScriptWindowObject('py_obj', wrapper()) html = ''' <html><body> <script type="text/javascript"> document.write(py_obj.list) </script> </body></html> ''' view.setHtml(html) view.show() self.app.exec_()
def setUp(self): #Acquire resources TimedQApplication.setUp(self, timeout=1000) self.view = QWebView() QObject.connect(self.view, SIGNAL('loadFinished(bool)'), self.load_finished) self.called = False
def webkit_download(url): app = QApplication([]) webview = QWebView() webview.loadFinished.connect(app.quit) webview.load(url) app.exec_() # delay here until download finished return webview.page().mainFrame().toHtml()
def browse(url, name='', icon=''): from PySide.QtGui import QApplication, QIcon from PySide.QtCore import QUrl from PySide.QtWebKit import QWebView for try_ in range(10): try: assert urllib2.urlopen(url).code == 200 except (AssertionError, urllib2.URLError): time.sleep(0.25) else: print "Started Qt Web View after %i ticks." % try_ break else: sys.exit("Error initializing Qt Web View.") qtapp = QApplication(name) web = QWebView() web.load(QUrl(url)) if icon: print "Setting Icon to", icon web.setWindowIcon(QIcon(icon)) else: print "WARNING: No icon found in settings.py" web.setWindowTitle(name) web.show() qtapp.exec_()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() # 创建QEventLoop对象,该对象用于创建本地时间循环 webview.loadFinished.connect(loop.quit) # QWebView对象的loadFinished回调连接了QEventLoop的quit方法,从而可以在网页加载完成之后停止事件循环 webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() # QwebView的加载方法是异步的,执行过程会在网页加载时立即传入下一行, # 但我们希望等待网页加载完成,因此需要在事件循环启动时调用loop.exec_() webview.show() # 调用QWebViewGUI的show()方法来显示渲染窗口,以方便调试 frame = webview.page().mainFrame() # 创建一个指代框架的变量 # 使用CSS模式在框架中定位元素,然后设置搜索参数 frame.findFirstElement('#search_term').setAttribute('Value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') # 使用evaluate JavaScript()方法提交事件,模拟点击事件 frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_() # 进入应用的事件循环,可以对表单操作进行复查,如果没有使用该方法,脚本就会直接结束 # 等待结果,三种方法处理: # 1、等待一定时间,期望AJAX事件能够在此时刻之前完成 # 2、重写Qt的网络管理器,跟踪URL请求完成的事件 # 3、轮询网页,等待特定内容出现,下面采用第三种方法 elements = None while not elements: app.processEvents() # 用于给Qt事件循环执行任务的事件,比如响应点击事件和更新GUI elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
def testBug899(self): html = ''' <html><body> <script type="text/javascript"> document.write("<p>"+py_obj.list1+"</p>") document.write("<p>"+py_obj.list2+"</p>") </script> </body></html> ''' class Obj(object): list1 = ['foo', 'bar', 'baz'] list2 = ['fi', 'fo', 'fum'] obj = Obj() wrapper_dict = {} for name in ('list1', 'list2'): getter = lambda arg=None, name=name: getattr(obj, name) wrapper_dict[name] = Property('QVariantList', getter) wrapper = type('PyObj', (QObject, ), wrapper_dict) view = QWebView() view.page().mainFrame().addToJavaScriptWindowObject( 'py_obj', wrapper()) view.setHtml(html)
def get_site_text(url='https://test.api.unistream.com/help/index.html'): """Функция возвращает содержимое по указанному url.""" import sys from PySide.QtGui import QApplication from PySide.QtCore import QEventLoop from PySide.QtWebKit import QWebSettings, QWebPage, QWebView from PySide.QtNetwork import QNetworkProxyFactory # Чтобы не было проблем запуска компов с прокси: QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) class WebPage(QWebPage): def userAgentForUrl(self, url): return 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0' if QApplication.instance() is None: QApplication(sys.argv) view = QWebView() view.setPage(WebPage()) view.load(url) # Ждем пока прогрузится страница loop = QEventLoop() view.loadFinished.connect(loop.quit) loop.exec_() doc = view.page().mainFrame().documentElement() print(len(doc.toOuterXml()), len(doc.toPlainText())) return doc.toPlainText()
def initUI(self): hbox = QtGui.QVBoxLayout() #hbox.addStretch() plot_view = QWebView() self.page = _LoggedPage() #page.newData.connect(onNewData) self.page.commandRecieved.connect(self.commandRecieved) self.page.helpNeeded.connect(self.helpNeeded) self.page.tabPressed.connect(self.tabPressed) plot_view.setPage(self.page) #plot_path = 'test.html' dir_path = os.path.dirname(os.path.realpath(__file__)) plot_view.load(QUrl('file:///%s/ptty.html' % dir_path)) plot_view_settings = plot_view.settings() plot_view_settings.setAttribute(QWebSettings.WebGLEnabled, True) plot_view_settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) hbox.addWidget(plot_view) self.setLayout(hbox) self.setWindowTitle('WTerminal') self.show()
def __init__(self): QWidget.__init__(self) self.title = "报告" self.__path = None self.__service = ReportDetService() # report view self.__wid_display = QWebView() # buttons _wid_buttons = ViewButtons( [dict(id="refresh", name=u'更新'), dict(id="export", name=u'导出')]) _wid_buttons.align_back() # main layout _layout = QVBoxLayout() _layout.addWidget(self.__wid_display) _layout.addWidget(_wid_buttons) self.setLayout(_layout) _layout.setContentsMargins(0, 0, 0, 0)
def webView(self): if not self._webView: dprint("create web view") from PySide.QtWebKit import QWebView self._webView = QWebView(self.parent) update_web_settings(self._webView.settings()) self._webView.resize(0, 0) # zero size return self._webView
def displayHtml(parent, title, html): win = QtGui.QDialog(parent) win.setWindowTitle(title) layout = QtGui.QVBoxLayout() win.setLayout(layout) view = QWebView() view.setHtml(html) layout.addWidget(view) win.show()
def __init__(self): self.network_manager = QNetworkAccessManager() self.network_manager.createRequest = self._create_request self.network_manager.finished.connect(self._request_finished) self.web_page = QWebPage() self.web_page.setNetworkAccessManager(self.network_manager) self.web_view = QWebView() self.web_view.setPage(self.web_page)
def createInstance(self): global functionID self._view = QWebView() self._jsfuncs = JSFuncs() functionID = -1 self._view.page().mainFrame().addToJavaScriptWindowObject( "jsfuncs", self._jsfuncs) self._view.loadFinished[bool].connect(self.onLoadFinished) self._view.load(PAGE_DATA % FUNCTIONS_LIST[self._functionID]) self._view.show()
def __init__(self, media, parent): super(WebMediaView, self).__init__(media, parent) self._widget = QWebView(parent) self._widget.setGeometry(media['_geometry']) self.set_default_widget_prop() self._widget.setDisabled(True) self._widget.page().mainFrame().setScrollBarPolicy( Qt.Vertical, Qt.ScrollBarAlwaysOff) self._widget.page().mainFrame().setScrollBarPolicy( Qt.Horizontal, Qt.ScrollBarAlwaysOff)
def __init__(self, app): self.network_manager = QNetworkAccessManager() self.network_manager.createRequest = self._create_request self.web_page = QWebPage() self.web_page.setNetworkAccessManager(self.network_manager) self.web_view = QWebView() self.web_view.setPage(self.web_page) self.html_data = None self.app = app self.finished = threading.Event()
def createWidgets(self): self.backButton = QToolButton() self.backButton.setIcon(QIcon(":/go-back.svg")) self.backButton.setText("&Back") self.backButton.setToolTip("""\ <p><b>Back</b> ({})</p> <p>Navigate to the previous page.</p>""".format( QKeySequence("Alt+Left").toString())) self.forwardButton = QToolButton() self.forwardButton.setIcon(QIcon(":/go-forward.svg")) self.forwardButton.setText("&Forward") self.forwardButton.setToolTip("""\ <p><b>Forward</b> ({})</p> <p>Navigate to the page you've just come back from.</p>""".format( QKeySequence("Alt+Right").toString())) self.contentsButton = QToolButton() self.contentsButton.setIcon(QIcon(":/go-home.svg")) self.contentsButton.setText("&Contents") self.contentsButton.setToolTip("""\ <p><b>Contents</b> ({})</p> <p>Navigate to the contents page.</p>""".format( QKeySequence("Alt+Home").toString())) self.searchLineEdit = Widgets.LegendLineEdit.LineEdit( "Search (F3 or Ctrl+F)") self.searchLineEdit.setToolTip("""\ <p><b>Search editor</p> <p>Type in a word to search for in the online help pages and press <b>Enter</b> or <b>F3</b> to search.</p>""") self.zoomInButton = QToolButton() self.zoomInButton.setIcon(QIcon(":/zoomin.svg")) self.zoomInButton.setText("&Zoom In") self.zoomInButton.setToolTip("""\ <p><b>Zoom In</b> ({})</p> <p>Make the text bigger.</p>""".format( QKeySequence("Alt++").toString())) self.zoomOutButton = QToolButton() self.zoomOutButton.setIcon(QIcon(":/zoomout.svg")) self.zoomOutButton.setText("Zoom &Out") self.zoomOutButton.setToolTip("""\ <p><b>Zoom Out</b> ({})</p> <p>Make the text smaller.</p>""".format( QKeySequence("Alt+-").toString())) width = self.fontMetrics().width(self.zoomOutButton.text() + " ") for button in (self.backButton, self.forwardButton, self.contentsButton, self.zoomInButton, self.zoomOutButton): button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) button.setMinimumWidth(width) button.setFocusPolicy(Qt.NoFocus) self.browser = QWebView() page = self.browser.page() page.setLinkDelegationPolicy(QWebPage.DelegateAllLinks) if self.debug: self.urlLabel = QLabel()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) #Validators for data input ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") ipValidator = QRegExpValidator(self.leGraylogIP) ipValidator.setRegExp(ipRegex) self.leGraylogIP.setValidator(ipValidator) self.leGraylogPort.setValidator(QIntValidator(1, 65535)) self.leGraylogHttpPort.setValidator(QIntValidator(1, 65535)) ipValidator = QRegExpValidator(self.leAsterixIP) ipValidator.setRegExp(ipRegex) self.leAsterixIP.setValidator(ipValidator) self.leAsterixPort.setValidator(QIntValidator(1, 65535)) self.leAsterixSic.setValidator(QIntValidator(1, 256)) self.leIamodPort.setValidator(QIntValidator(1, 65535)) self.leIamodThreshold.setValidator(QIntValidator(0, 99999)) #Define functions for GUI actions self.pbStart.clicked.connect(self.__startServer) self.pbStop.clicked.connect(self.__stopServer) self.actionLicense.triggered.connect(self.__license) self.actionLoad_Config_File.triggered.connect(self.__dialogConfigFile) self.pbSaveConfiguration.clicked.connect(self.__writeConfigFile) self.pbStart.setEnabled(False) if self.__checkServerIsRunning(): self.__serverStatusImage(True) else: self.__serverStatusImage(False) self.configFile = ConfigParser.ConfigParser() self.view = QWebView() self.webLayout.addWidget(self.view) self.view.settings().setAttribute( QWebSettings.JavascriptCanOpenWindows, True) self.view.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.pbConnect.clicked.connect(self.__connectHttpServer) l = QVBoxLayout(self.tab2) sc = StaticCanvas(self.tab2, width=5, height=4, dpi=100) dc = DynamicCanvas(self.tab2, width=5, height=4, dpi=100) l.addWidget(sc) l.addWidget(dc)
def show(self): self.battery = Battery() self.wifi = Wifi() self.url = QUrl("qt.html") self.web = QWebView() self.web.loadFinished.connect(self.onLoad) self.web.load(self.url) self.web.show()
def test_qt(): a = QApplication(sys.argv) w = QWebView() w.show() g = GoogleTtsPlayer('qt') g.setParentWidget(w) QTimer.singleShot(1000, lambda: g.speak(q, language='ja')) ret = a.exec_() print "leave: ret = %i" % ret
def createWebView( nIndex ): global functionID global currentWebView functionID = nIndex currentWebView = QWebView() currentWebView._jsfuncs = JSFuncs() currentWebView.page().mainFrame().addToJavaScriptWindowObject("jsfuncs", currentWebView._jsfuncs) QObject.connect( currentWebView, QtCore.SIGNAL('loadFinished( bool )'), onLoadFinished ) currentWebView.load(PAGE_DATA % FUNCTIONS_LIST[ nIndex ]) currentWebView.show()
def main(): app = QtGui.QApplication(sys.argv) browser = QWebView() browser.setWindowTitle('CreativeDrive Brazil') browser.setUrl(QUrl('http://127.0.0.1:5000')) browser.showMaximized() w = QtGui.QWidget() trayIcon = SystemTrayIcon(QtGui.QIcon("static/images/ico.png"), w) trayIcon.show() sys.exit(app.exec_())
def test_native(): #url = 'http://translate.google.com/translate_tts' url = 'http://translate.google.com/translate_tts?tl=ja' url = QUrl(url) url.addEncodedQueryItem('q', QUrl.toPercentEncoding(q)) print url.toString() update_web_settings() a = QApplication(sys.argv) w = QWebView() w.load(url) w.show() ret = a.exec_()
def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(804, 604) self.layout = QVBoxLayout(Dialog) self.qwebview = QWebView(Dialog) self.qwebview.setGeometry(QtCore.QRect(0, 50, 800, 600)) self.qwebview.setObjectName(_fromUtf8("kwebview")) self.lineEdit = QtGui.QLineEdit(Dialog) self.lineEdit.setGeometry(QtCore.QRect(10, 20, 790, 25)) self.lineEdit.setObjectName(_fromUtf8("lineEdit")) self.layout.addWidget(self.lineEdit) self.layout.addWidget(self.qwebview) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog)
def show(self): #It is IMPERATIVE that all forward slashes are scrubbed out, otherwise QTWebKit seems to be # easily confused kickOffHTML = join( dirname(__file__).replace('\\', '/'), "templates/index.html").replace('\\', '/') #This is basically a browser instance self.web = QWebView() #Unlikely to matter but prefer to be waiting for callback then try to catch # it in time. self.web.loadFinished.connect(self.onLoad) self.web.load(kickOffHTML) self.web.show()
def main(): app = QApplication([]) view = QWebView() fac = PluginFactory() view.page().setPluginFactory(fac) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) view.load(QUrl(sys.argv[1])) view.resize(840, 600) view.show() return app.exec_()
def convert_html_to_pdf(source, destination, page_size=QPrinter.Letter, print_format=QPrinter.PdfFormat, timeout=10000, app=None): """Converts an .html file at the source to a .pdf at the destination Any external files linked in the source file must be paths relative to the location of the source file itself. If building the html file dynamically, the rel_path function can be used to create proper relative paths using the .html location as the source location. The conversion is done using th ability of a QPrinter to print a QWebView to a PDF. This means we must have some Qt bindings, either PySide (default) or PyQt4 (5 support incoming?), but then are only limited by what the QWebView can display. While the intent is so print to a PDF, the format parameter is exposed so that this can be used to print directly to a printer or (if >=Qt4.2) PostScript format. If this is being used in a larger QApplication, we should only have one instance of QApplication, so pass the existing instance to the `app` parameter. """ if app is None: app = QApplication(sys.argv) view = QWebView() # We want to ensure the page was fully loaded before printing, so # we wait for the loadFinished event to fire. with wait_for_signal(view.loadFinished, timeout=timeout): # QUrl requires absolute path names view.load(QUrl.fromLocalFile(os.path.abspath(source))) # With the QWebView loaded, we now print to the destination PDF printer = QPrinter() printer.setPageSize(page_size) printer.setOutputFormat(print_format) printer.setOutputFileName(destination) view.print_(printer) # Exit the application app.exit()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') frame.findFirstElement('#search').evaluateJavaScript('this.click()') elements = None while not elements: app.processEvents()
def testPlugin(self): view = QWebView() fac = PluginFactory() view.page().setPluginFactory(fac) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) view.load( QUrl( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'qmlplugin', 'index.html'))) view.resize(840, 600) view.show() QTimer.singleShot(500, self.app.quit) self.app.exec_()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option').setPlainText('1000') #设置纯文本 frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_() elements = None while not elements: app.processEvents() elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries