def test_connection(self): self.message.setText( '<span style="font-size: 10px; color: #000000;">' + 'Verbindung wird getestet.' + '</span>') self.nam.finished.connect(self.test_reply) self.nam.sslErrors.connect(self.ssl_errors) ssl_config = QSslConfiguration().defaultConfiguration() ssl_config.setCiphers(QSslSocket().supportedCiphers()) if self.certificate: certificate = QSslCertificate(encoded=self.certificate, format=QSsl.Pem) ssl_config.setCaCertificates([certificate]) else: ssl_config.setCaCertificates([]) url = QUrl(self.url_edit.text()) url.setPath("/".join( filter(bool, (url.path() + "/ajax/read.php").split("/")))) request = QNetworkRequest(url) request.setSslConfiguration(ssl_config) request.setRawHeader( "Authorization", "Basic ".encode('utf-8') + b64encode( (self.username_edit.text() + ":" + self.password_edit.text()).encode('utf-8'))) request.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded") self.replies.add(self.nam.post(request, QByteArray()))
def _urlencode_request_data(self, raw_data): # the data which we want to send to the server must be urlencoded request_data = QUrl() for (name, value) in raw_data.items(): request_data.addQueryItem(name, unicode(value)) return request_data.encodedQuery()
def __init__(self, url, image_path): QObject.__init__(self) self.url = QUrl(url) self.image_path = image_path self.webpage = QWebPage(self) self.webpage.loadFinished.connect(self.render) self.webpage.mainFrame().load(self.url)
def testResourceListCtor(self): resourceList = [QMediaResource(QUrl('http://example.com/movie.mov'))] media = QMediaContent(resourceList) self.assertEqual(media.canonicalUrl(), QUrl('http://example.com/movie.mov')) self.assertEqual(media.canonicalResource().url(), QUrl('http://example.com/movie.mov'))
def testEquality(self): ''' Test operators '==' and '!='.''' media1 = QMediaContent() media2 = QMediaContent() media3 = QMediaContent( QMediaResource(QUrl('http://example.com/movie.mov'))) media4 = QMediaContent( QMediaResource(QUrl('http://example.com/movie.mov'))) media5 = QMediaContent( QMediaResource(QUrl('file:///some/where/over/the/rainbow.mp3'))) # '==' and '!=' operators -- null == null self.assert_(media1 == media2) self.assertFalse(media1 != media2) # '==' and '!=' operators -- null != something self.assertFalse(media1 == media3) self.assert_(media1 != media3) # equiv self.assert_(media3 == media4) self.assertFalse(media3 != media4) # not equiv self.assertFalse(media4 == media5) self.assert_(media4 != media5)
def parseMarkdown(self): """ Parse the Markdown stuff. """ self.updateStructure() if self.sync is False: return y = self.web.page().mainFrame().scrollPosition().y() txt = self.editor.toPlainText().encode('utf-8') if txt is '' or None: return p = Popen([self.parser], stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=False) grep_stdout = p.communicate(input=txt)[0].decode('utf-8') path = QUrl.fromUserInput(os.getcwd() + os.sep) grep_stdout = grep_stdout.replace('img src=\"', 'img src=\"' + path.toString()) # Can't use baseUrl=path because external img will not be loaded # than :-/ self.web.setHtml(grep_stdout) self.web.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(os.getcwd() + os.sep + "/style.css")) if y: self.web.scroll(0, y) self.web.page().mainFrame().scroll(0, y) self.web.page().mainFrame().setScrollPosition(QPoint(0, y))
def parseMarkdown(self): """ Parse the Markdown stuff. """ self.updateStructure() if self.sync is False: return y = self.web.page().mainFrame().scrollPosition().y() txt = self.editor.toPlainText().encode('utf-8') if txt is '' or None: return p = Popen([self.parser], stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=False) grep_stdout = p.communicate(input=txt)[0].decode('utf-8') path = QUrl.fromUserInput(os.getcwd() + os.sep) grep_stdout = grep_stdout.replace('img src=\"', 'img src=\"' + path.toString()) # Can't use baseUrl=path because external img will not be loaded # than :-/ self.web.setHtml(grep_stdout) self.web.settings().setUserStyleSheetUrl( QUrl.fromLocalFile(os.getcwd() + os.sep + "/style.css")) if y: self.web.scroll(0, y) self.web.page().mainFrame().scroll(0, y) self.web.page().mainFrame().setScrollPosition(QPoint(0, y))
def testSetQueryItems(self): #QUrl.setQueryItems urla = QUrl('http://www.google.com/search?q=python&hl=en') urlb = QUrl('http://www.google.com/search') urlb.setQueryItems(urla.queryItems()) self.assertEqual(urla, urlb)
def email_note(self): body = self.page.mainFrame().toPlainText()[ len(self.title): ].strip() url = QUrl("mailto:") url.addQueryItem("subject", self.title) url.addQueryItem("body", body) QDesktopServices.openUrl(url)
def urlExists(self, value): if not value: return False url = QUrl(value) if not url.isLocalFile(): return True path = url.toLocalFile() return os.path.exists(path)
def testAllEncodedQueryItemsValues(self): #QUrl.allEncodedQueryItemValues url = QUrl() key = 'key' valid_data = ['data', 'valid', 'test'] for i, data in enumerate(valid_data): url.addQueryItem(key, data) self.assertEqual(url.allEncodedQueryItemValues(key), list(valid_data[:i+1]))
def testAllEncodedQueryItemsValues(self): #QUrl.allEncodedQueryItemValues url = QUrl() key = 'key' valid_data = ['data', 'valid', 'test'] for i, data in enumerate(valid_data): url.addQueryItem(key, data) self.assertEqual(url.allEncodedQueryItemValues(key), list(valid_data[:i + 1]))
def testRequestCtor(self): request = QNetworkRequest(QUrl('http://example.com/movie.mov')) request.setAttribute(QNetworkRequest.User, 1234) media = QMediaContent(request) self.assertEqual(media.canonicalUrl(), QUrl('http://example.com/movie.mov')) self.assertEqual(media.canonicalResource().request(), request) self.assertEqual(media.canonicalResource().url(), QUrl('http://example.com/movie.mov'))
def download_file(self, path, setting): version_file = self.settings['base_url'].format(self.selected_version()) location = self.get_setting('download_dir').value versions = re.findall('v(\d+)\.(\d+)\.(\d+)', path)[0] minor = int(versions[1]) if minor >= 12: path = path.replace('node-webkit', 'nwjs') self.progress_text = 'Downloading {}'.format(path.replace(version_file, '')) url = QUrl(path) file_name = setting.save_file_path(self.selected_version(), location) archive_exists = QFile.exists(file_name) #dest_files_exist = False # for dest_file in setting.dest_files: # dest_file_path = os.path.join('files', setting.name, dest_file) # dest_files_exist &= QFile.exists(dest_file_path) forced = self.get_setting('force_download').value if archive_exists and not forced: self.continue_downloading_or_extract() return self.out_file = QFile(file_name) if not self.out_file.open(QIODevice.WriteOnly): error = self.out_file.error().name self.show_error('Unable to save the file {}: {}.'.format(file_name, error)) self.out_file = None self.enable_ui() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.http_request_aborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.http_get_id = self.http.get(path, self.out_file)
def test_edit_order_add_rename_documents(self): app = self.app widget = self.widget mw = self.mw widget.edit_new_order(self.customer_id) widget.controller_part.view.setFocus(Qt.OtherFocusReason) self._fill_order_part("Order part one") # Put the cursor back on the first line so the next document drop is tied to it. QTest.keyEvent(QTest.Click, widget.controller_part.view, Qt.Key_Up) app.processEvents() # app.exec_() # Drop a document tmp_file, tmp_path = self._make_tmp_file() mime_data = QMimeData() url = "file:///{}".format(os.path.abspath(tmp_path).replace('\\', '/')) mainlog.debug("Dropping at {}".format(QUrl(url).toString())) mime_data.setUrls([QUrl(url)]) make_document_drop(widget.documents_widget.view, QPoint(10, 10), mime_data) self._clear_tmp_file(tmp_file, tmp_path) # Now it has been dropped, rename it # (this tests things like non-delayed create, delayed rename) model = widget.documents_widget.model fn_ndx = model.prototype.index_of("filename") ndx = model.index(0, fn_ndx) model.setData(ndx, "New name", Qt.UserRole) #app.exec_() # Now save the whole order widget.setFocus() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() order = dao.order_dao.find_by_id(widget._current_order.order_id) #app.exec_() self.assertEqual(1, len(order.parts[0].documents), "One document was added on the first part") documents = [d for d in order.parts[0].documents] # Set to array self.assertEqual("New name", documents[0].filename, "Rename should've been applied")
def __init__(self): QApplication.__init__(self, sys.argv) self.setOrganizationName("Khertan Software") self.setOrganizationDomain("khertan.net") self.setApplicationName("KhtNotes") self.settings = Settings() self.view = FilteredDeclarativeView(settings=self.settings) if os.path.exists('/etc/mer-release'): fullscreen = True elif os.path.exists('/etc/aegis'): fullscreen = True self.glformat = QGLFormat().defaultFormat() self.glformat.setSampleBuffers(False) self.glw = QGLWidget(self.glformat) self.glw.setAutoFillBackground(False) self.view.setViewport(self.glw) else: fullscreen = False self.notesModel = NotesModel() self.note = Note(settings=self.settings) self.conboyImporter = TomboyImporter() self.syncer = Sync() self.rootContext = self.view.rootContext() self.rootContext.setContextProperty("argv", sys.argv) self.rootContext.setContextProperty("__version__", __version__) self.rootContext.setContextProperty("__upgrade__", __upgrade__ .replace('\n', '<br />')) self.rootContext.setContextProperty("Settings", self.settings) self.rootContext.setContextProperty("Sync", self.syncer) self.rootContext.setContextProperty("Importer", self.conboyImporter) self.rootContext.setContextProperty('notesModel', self.notesModel) self.rootContext.setContextProperty('Note', self.note) try: self.view.setSource(QUrl.fromLocalFile( os.path.join(os.path.dirname(__file__), 'qml', 'Harmattan_main.qml'))) except: self.view.setSource(QUrl.fromLocalFile( os.path.join(os.path.dirname(__file__), 'qml', 'Desktop_main.qml'))) self.rootObject = self.view.rootObject() if fullscreen: self.view.showFullScreen() else: self.view.show() self.note.on_error.connect(self.rootObject.onError) self.syncer.on_error.connect(self.rootObject.onError) self.syncer.on_finished.connect(self.rootObject.refresh) self.conboyImporter.on_finished.connect(self.notesModel.reload)
def testResources(self): resourceList = [ QMediaResource(QUrl('http://example.com/movie-main.mov')), QMediaResource(QUrl('http://example.com/movie-big.mov')) ] media = QMediaContent(resourceList) res = media.resources() self.assertEqual(len(res), 2) self.assertEqual( res[0], QMediaResource(QUrl('http://example.com/movie-main.mov'))) self.assertEqual( res[1], QMediaResource(QUrl('http://example.com/movie-big.mov')))
def play(self, url, **kwargs): """ @param url str or QUrl """ if not isinstance(url, QUrl): url = QUrl(url) for k, v in kwargs.iteritems(): #url.addQueryItem(k, v) if not isinstance(v, basestring): v = "%s" % v url.addEncodedQueryItem(k, QUrl.toPercentEncoding(v)) self.__d.webView.load(url)
def serve_forever(self): self.jid = 'Err@localhost' self.connect() # be sure we are "connected" before the first command self.connect_callback() # notify that the connection occured # create window and components app = QtGui.QApplication(sys.argv) self.mainW = QtGui.QWidget() self.mainW.setWindowTitle('Err...') icon_path = os.path.dirname(errbot.__file__) + os.sep + 'err.svg' bg_path = os.path.dirname(errbot.__file__) + os.sep + 'err-bg.svg' self.mainW.setWindowIcon(QtGui.QIcon(icon_path)) vbox = QtGui.QVBoxLayout() help = QtGui.QLabel( "CTRL+Space to autocomplete -- CTRL+Enter to send your message") self.input = CommandBox(self.cmd_history, self.commands) self.output = QtWebKit.QWebView() # init webpage self.buffer = """<html> <head> <link rel="stylesheet" type="text/css" href="%s/style/style.css" /> </head> <body style=" background-image: url('%s'); background-repeat: no-repeat; background-position:center center; background-attachment:fixed; background-size: contain; margin:0;"> """ % (QUrl.fromLocalFile(BOT_DATA_DIR).toString(), QUrl.fromLocalFile(bg_path).toString()) self.output.setHtml(self.buffer) # layout vbox.addWidget(self.output) vbox.addWidget(self.input) vbox.addWidget(help) self.mainW.setLayout(vbox) # setup web view to open liks in external browser self.output.page().setLinkDelegationPolicy( QtWebKit.QWebPage.DelegateAllLinks) # connect signals/slots self.output.page().mainFrame().contentsSizeChanged.connect( self.scroll_output_to_bottom) self.output.page().linkClicked.connect(QtGui.QDesktopServices.openUrl) self.input.newCommand.connect(self.send_command) self.conn.newAnswer.connect(self.new_message) self.mainW.show() try: app.exec_() finally: self.disconnect_callback() self.shutdown() exit(0)
def test_edit_order_documents(self): app = self.app widget = self.widget mw = self.mw # order = self._make_order() # order_id = order.order_id # widget.reset_order(order.order_id) widget.edit_new_order(self.customer_id) widget.controller_part.view.setFocus(Qt.OtherFocusReason) # QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_Escape) # modifier, delay # QTest.keyEvent(QTest.Click, widget.controller_part.view, Qt.Key_F5, Qt.ShiftModifier) # modifier, delay # app.processEvents() self._fill_order_part("Order part two") # Put the cursor back on the first line so the next document drop is tied to it. QTest.keyEvent(QTest.Click, widget.controller_part.view, Qt.Key_Up) app.processEvents() # app.exec_() tmp_file, tmp_path = self._make_tmp_file() mime_data = QMimeData() url = "file:///{}".format(os.path.abspath(tmp_path).replace('\\', '/')) mainlog.debug("Dropping at {}".format(QUrl(url).toString())) mime_data.setUrls([QUrl(url)]) make_document_drop(widget.documents_widget.view, QPoint(10, 10), mime_data) self._clear_tmp_file(tmp_file, tmp_path) # That's fine, but I'll need to pilot the file chooser dialog, and that's hard :-( # But even if I find my way around that, I'll have to mock the file server... :-( # b.click() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() order = dao.order_dao.find_by_id(widget._current_order.order_id) #app.exec_() self.assertEqual(1, len(order.parts[0].documents), "One document was added on the first part")
def serve_forever(self): self.jid = 'Err@localhost' self.connect() # be sure we are "connected" before the first command self.connect_callback() # notify that the connection occured # create window and components app = QtGui.QApplication(sys.argv) self.mainW = QtGui.QWidget() self.mainW.setWindowTitle('Err...') icon_path = os.path.dirname(errbot.__file__) + os.sep + 'err.svg' bg_path = os.path.dirname(errbot.__file__) + os.sep + 'err-bg.svg' self.mainW.setWindowIcon(QtGui.QIcon(icon_path)) vbox = QtGui.QVBoxLayout() help = QtGui.QLabel("CTRL+Space to autocomplete -- CTRL+Enter to send your message") self.input = CommandBox(self.cmd_history, self.commands) self.output = QtWebKit.QWebView() # init webpage self.buffer = """<html> <head> <link rel="stylesheet" type="text/css" href="%s/style/style.css" /> </head> <body style=" background-image: url('%s'); background-repeat: no-repeat; background-position:center center; background-attachment:fixed; background-size: contain; margin:0;"> """ % (QUrl.fromLocalFile(BOT_DATA_DIR).toString(), QUrl.fromLocalFile(bg_path).toString()) self.output.setHtml(self.buffer) # layout vbox.addWidget(self.output) vbox.addWidget(self.input) vbox.addWidget(help) self.mainW.setLayout(vbox) # setup web view to open liks in external browser self.output.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks) # connect signals/slots self.output.page().mainFrame().contentsSizeChanged.connect(self.scroll_output_to_bottom) self.output.page().linkClicked.connect(QtGui.QDesktopServices.openUrl) self.input.newCommand.connect(self.send_command) self.conn.newAnswer.connect(self.new_message) self.mainW.show() try: app.exec_() finally: self.disconnect_callback() self.shutdown() exit(0)
class ImageRenderer(QObject): def __init__(self, url, image_path): QObject.__init__(self) self.url = QUrl(url) self.image_path = image_path self.webpage = QWebPage(self) self.webpage.loadFinished.connect(self.render) self.webpage.mainFrame().load(self.url) def render(self, ok): if ok: print('Loaded {0}'.format(self.url.toString())) self.webpage.setViewportSize( self.webpage.mainFrame().contentsSize()) image = QImage(self.webpage.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.webpage.mainFrame().render(painter) painter.end() if image.save(self.image_path): print('Saved image to {0}'.format(self.image_path)) else: print('Could not save to {0}'.format(self.image_path)) else: print('Could not load {0.toString()}'.format(self.url)) QApplication.instance().quit()
def testAbstractItemModelTransferToQML(self): view = QDeclarativeView() view.setSource(QUrl.fromLocalFile(adjust_filename('bug_814.qml', __file__))) root = view.rootObject() model = ListModel() root.setProperty('model', model) view.show()
def open(self, address, method='get', headers={}, auth=None, body=None, default_popup_response=None): """Opens a web page. :param address: The resource URL. :param method: The Http method. :param headers: An optional dict of extra request hearders. :param auth: An optional tuple of HTTP auth (username, password). :param body: An optional string containing a payload. :param default_popup_response: the default response for any confirm/ alert/prompt popup from the Javascript (replaces the need for the with blocks) :return: Page resource, All loaded resources. """ body = body or QByteArray() try: method = getattr(QNetworkAccessManager, "%sOperation" % method.capitalize()) except AttributeError: raise Error("Invalid http method %s" % method) request = QNetworkRequest(QUrl(address)) request.CacheLoadControl(0) for header in headers: request.setRawHeader(header, headers[header]) self._auth = auth self._auth_attempt = 0 # Avoids reccursion self.main_frame.load(request, method, body) self.loaded = False if default_popup_response is not None: Ghost._prompt_expected = (default_popup_response, None) Ghost._confirm_expected = (default_popup_response, None) return self.wait_for_page_loaded()
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 requestPixmap(self, path, rsize, size): """@reimp @public @param[in] providerId unicode unused @param[out] rsize QSize @param[in] size QSize @return QPixmap not None virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) """ ret = QPixmap(QUrl(path).toLocalFile()) if ret.isNull(): derror("failed to load image: '%s'" % path) elif size != ret.size() and not size.isEmpty() and not ret.size( ).isEmpty(): if ret.width() * size.height() > ret.height() * size.width(): ret = ret.scaledToHeight(min(800, size.height()), Qt.SmoothTransformation) else: w = 1000 if ret.width() > ret.height() else 600 ret = ret.scaledToWidth(min(w, size.width()), Qt.SmoothTransformation) #elif size != ret.size(): # ret = (ret.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if not size.isEmpty() else # ret.scaledToWidth(size.width(), Qt.SmoothTransformation) if size.width() > 0 else # ret.scaledToHeight(size.height(), Qt.SmoothTransformation) if size.height() > 0 else # ret) rsize.setWidth(ret.width()) rsize.setHeight(ret.height()) return ret
def __init__(self): QApplication.__init__(self, sys.argv) self.setOrganizationName("Khertan Software") self.setOrganizationDomain("khertan.net") self.setApplicationName("KhtNotes") self.view = QtDeclarative.QDeclarativeView() self.glw = QGLWidget() self.view.setViewport(self.glw) self.notesModel = NotesModel() self.note = Note() self.conboyImporter = TomboyImporter() self.syncer = Sync() self.rootContext = self.view.rootContext() self.rootContext.setContextProperty("argv", sys.argv) self.rootContext.setContextProperty("__version__", __version__) self.rootContext.setContextProperty("__upgrade__", __upgrade__ .replace('\n', '<br>')) self.rootContext.setContextProperty("Settings", Settings()) self.rootContext.setContextProperty("Sync", self.syncer) self.rootContext.setContextProperty("Importer", self.conboyImporter) self.rootContext.setContextProperty("QmlDirReaderWriter", QmlDirReaderWriter()) self.rootContext.setContextProperty('notesModel', self.notesModel) self.rootContext.setContextProperty('Note', self.note) self.view.setSource(QUrl.fromLocalFile( os.path.join(os.path.dirname(__file__), 'qml', 'Harmattan_main.qml'))) self.rootObject = self.view.rootObject() self.view.showFullScreen() self.note.on_error.connect(self.rootObject.onError) self.syncer.on_error.connect(self.rootObject.onError) self.syncer.on_finished.connect(self.notesModel.reload) self.conboyImporter.on_finished.connect(self.notesModel.reload)
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 image_url(name): """ @param name str id @return QUrl not None @throw KeyError when unknown name """ return QUrl.fromLocalFile(os.path.abspath(image_path(name)))
def test_open_note_links(self): """Test open note links""" guid = 'guid' note = Note( id=123, ) self.app.open = MagicMock() self.service.get_note_by_guid = MagicMock( return_value=note.struct, ) link = "evernote:///view/123/123/{guid}/123/".format( guid=guid, ) self.editor = Editor(self.note) self.editor.note_edit.link_clicked(QUrl(link)) self.assertEqual( self.service.get_note_by_guid.call_args[0][0], guid, ) self.assertEqual( self.app.open.call_args[0][0].id, note.id, ) del self.app.open
def qml_url(name): """ @param name unicode @return QUrl @throw KeyError when unknown name """ return QUrl.fromLocalFile(config.QML_LOCATIONS[name])
def __init__(self, url, filename, image_crop, translate_page, parent=None): super(Render, self).__init__(parent) self.image_crop = image_crop self.fileName = time.strftime("%Y%m%d%H%M%S", time.localtime()) + "_test.jpg" self.finished = False # Settings s = self.page().settings() s.setAttribute(QWebSettings.AutoLoadImages, True) s.setAttribute(QWebSettings.PluginsEnabled, True) s.setAttribute(QWebSettings.JavascriptEnabled, True) s.setAttribute(QWebSettings.JavaEnabled, False) s.setAttribute(QWebSettings.JavascriptCanOpenWindows, False) s.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) #self.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) self.timerScreen = QTimer() self.timerScreen.setInterval(10000) self.timerScreen.setSingleShot(True) self.timerScreen.timeout.connect(self.takeScreenshot) self.loadFinished.connect(self.timerScreen.start) self.load(QUrl(url))
def testMetaData(self): self.view = QWebView() QObject.connect(self.view, SIGNAL('loadFinished(bool)'), self.load_finished) url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__)) self.view.setUrl(url) self.app.exec_()
def __init__(self): QApplication.__init__(self, sys.argv) self.setOrganizationName("Khertan Software") self.setOrganizationDomain("khertan.net") self.setApplicationName("KhtSimpleText") self.view = QtDeclarative.QDeclarativeView() #Are we on mer ? So don't use opengl #As it didn't works on all devices if not os.path.exists('/etc/mer-release'): self.glformat = QGLFormat().defaultFormat() self.glformat.setSampleBuffers(False) self.glw = QGLWidget(self.glformat) self.glw.setAutoFillBackground(False) self.view.setViewport(self.glw) self.document = Document('~') self.documentsModel= DocumentsModel(currentDoc=self.document) self.rootContext = self.view.rootContext() self.rootContext.setContextProperty("argv", sys.argv) self.rootContext.setContextProperty("__version__", __version__) self.rootContext.setContextProperty("__upgrade__", __upgrade__ .replace('\n', '<br>')) self.rootContext.setContextProperty("Settings", Settings()) self.rootContext.setContextProperty("DocumentsModel", self.documentsModel) self.rootContext.setContextProperty("Document", self.document) self.view.setSource(QUrl.fromLocalFile( os.path.join(os.path.dirname(__file__), 'qml', 'main.qml'))) self.rootObject = self.view.rootObject() self.view.showFullScreen()
def printFile(self): """Generates a PDF file with all sentences included in database.""" pdfdlg = pdf_dlg.PDFDialog(self.preferences, self.workspace) if pdfdlg.exec_(): # We need to change this, pass the marker # inside of the function you divide it - pattern! marker = self.preferences['marker'] marker_beg = marker[:len(marker) / 2] marker_end = marker[len(marker) / 2:] pdf_writer.exportToPDF( self.preferences['pdf']['path'], self.preferences['title'], self.preferences['author'], self.preferences['description'], self.container, marker_beg, marker_end, self.preferences['where'], self.preferences['replace_by'], self.preferences['pdf']['margin_top'], self.preferences['pdf']['margin_bottom'], self.preferences['pdf']['margin_left'], self.preferences['pdf']['margin_right'], self.preferences['pdf']['font'], self.preferences['pdf']['size'], self.preferences['pdf']['mode']) try: if self.preferences['pdf']['auto_open']: QDesktopServices.openUrl( QUrl("file:///" + self.preferences['pdf']['path'], QUrl.TolerantMode)) except: pass
def __init__(self): self.network_manager = CustomNetworkAccessManager.getInstance() self.axis = [] self.human_events = {} self.node_collected_data = {} self.last_url = None self.current_url = QUrl() self.current_axis_id = None self.crossed_axis_method = None self.crossed_axes = [] self.crossed_axes_string = '' self.cross_axis_delay = QTimer() self.cross_axis_delay.setSingleShot(True) self.cross_axis_delay.timeout.connect(self.crossedAxis) self.cross_axis_params = None self.loading_timeout = QTimer() self.loading_timeout.setSingleShot(True) self.loading_timeout.setInterval(30000) self.loading_timeout.timeout.connect(self.loadingTimeoutAction) self.inactivity_timeout = QTimer() self.inactivity_timeout.setSingleShot(True) self.inactivity_timeout.setInterval(10000) self.inactivity_timeout.timeout.connect(self.inactivityTimeoutAction) self.page_reloads = 0 Logger.getLoggerFor(self.__class__)
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 start(self): global client if (len(self.email) > 0 and len(self.password) > 0): self.email = str(self.email[0]) self.password = str(base64.b64decode(self.password[0])) client = Client(self.email, self.password) response = client.login() if (response['result'] == 'ok'): startup = client.notify_startup() if (not startup): print_message("Could not startup!") else: print_message("Notified!") else: Mbox("Budibox", "Credentials undefined or incorrect. Please login again.") # Create the QML user interface. view = QDeclarativeView() view.setSource(QUrl('qml/main.qml')) view.setWindowTitle("Budibox") view.setWindowIcon(QIcon("qml/budibox.jpg")) context = view.rootContext() context.setContextProperty("send_data",Receive_data()) # Display the user interface and allow the user to interact with it. view.setGeometry(360, 360, 360, 360) view.setMaximumSize(360, 360) view.show() app.exec_()
def testSignalEmission(self): qmlRegisterType(MyItem, "my.item", 1, 0, "MyItem") view = QDeclarativeView() view.setSource(QUrl.fromLocalFile(adjust_filename('bug_951.qml', __file__))) self.app.exec_() self.assertTrue(MyItem.COMPONENT_COMPLETE_CALLED)
def linkClicked(self, url): fragment = None if url.hasFragment(): fragment = url.fragment() _url = QUrl(url.toString()[:url.toString().find('#%s'%fragment)]) if _url.toString() != 'about:blank' and _url.path() != self.current_position: url = _url fragment = None if fragment: page = self.view.page() page.mainFrame().scrollToAnchor(fragment) elif url.path() in self.contents.keys(): self.current_position = url.path() self.loadPage(self.contents[url.path()]) elif url.path().startswith('http://') or url.path().startswith('www.'): print 'pass the address to the system browser'
def testAbstractItemModelTransferToQML(self): view = QDeclarativeView() view.setSource( QUrl.fromLocalFile(adjust_filename('bug_814.qml', __file__))) root = view.rootObject() model = ListModel() root.setProperty('model', model) view.show()
def testAddQueryItem(self): #QUrl.addQueryItem url = QUrl() valid_data = [('hl', 'en'), ('user', 'konqui')] url.addQueryItem(*valid_data[0]) self.assertEqual(url.queryItems()[0], valid_data[0]) url.addQueryItem(*valid_data[1]) self.assertEqual(sorted(url.queryItems()), sorted(valid_data))
def __init__(self, accountJid): _d = UIDebug() self._d = _d.d self.initializationDone = False bus = dbus.SessionBus() mybus = bus.get_object('com.nokia.video.Thumbnailer1', '/com/nokia/video/Thumbnailer1') self.iface = dbus.Interface( mybus, 'org.freedesktop.thumbnails.SpecializedThumbnailer1') self.iface.connect_to_signal("Finished", self.thumbnailUpdated) contactsbus = bus.get_object( 'com.nokia.maemo.meegotouch.Contacts', '/', follow_name_owner_changes=True, ) self.contactsbus = dbus.Interface( contactsbus, 'com.nokia.maemo.meegotouch.ContactsInterface') self.contactsbus.connect_to_signal("contactsPicked", self.contactPicked) camerabus = bus.get_object( 'com.nokia.maemo.CameraService', '/', follow_name_owner_changes=True, ) self.camera = dbus.Interface( camerabus, 'com.nokia.maemo.meegotouch.CameraInterface') self.camera.connect_to_signal("captureCompleted", self.captureCompleted) self.camera.connect_to_signal("cameraClosed", self.captureCanceled) self.selectedJid = "" super(WAUI, self).__init__() url = QUrl('/opt/waxmppplugin/bin/wazapp/UI/main.qml') self.filelist = [] self.accountJid = accountJid self.accountPushName = None self.rootContext().setContextProperty("waversion", Utilities.waversion) self.rootContext().setContextProperty("WAConstants", WAConstants.getAllProperties()) self.rootContext().setContextProperty("myAccount", accountJid) currProfilePicture = WAConstants.CACHE_PROFILE + "/" + accountJid.split( "@")[0] + ".jpg" self.rootContext().setContextProperty( "currentPicture", currProfilePicture if os.path.exists(currProfilePicture) else "") self.setSource(url) self.focus = False self.whatsapp = None self.idleTimeout = None
def iconName(self): if 'Icon' in self._prop.keys(): icon_name = './qml/icons/%s.png' % self._prop['Icon'] if not os.path.exists(icon_name): icon_name = './qml/icons/unknow.png' else: icon_name = './qml/icons/unknow.png' return QUrl.fromLocalFile(icon_name)
def testQDeclarativeNetworkFactory(self): view = QDeclarativeView() url = QUrl.fromLocalFile(adjust_filename('hw.qml', __file__)) view.setSource(url) view.show() self.assertEqual(view.status(), QDeclarativeView.Ready) self.app.exec_()
def drawMap(self): #======================================================================= # with open("sweattrails/qt/maps.html") as fd: # html = fd.read() # templ = string.Template(html) # html = templ.substitute( # bgcolor = "#343434", # fgcolor = "#FFFFFF", # mapskey = gripe.Config.app["config"].google_api_key) #======================================================================= self.setUrl(QUrl.fromLocalFile(os.path.join(gripe.root_dir(), "sweattrails/qt/maps.html")))
def __init__(self, parent=None): super(MainLogic, self).__init__(parent) self.setWindowTitle("RDA") # Renders given file self.setSource(QUrl.fromLocalFile("gui/main.qml")) # QML resizes to main window self.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.rootContext().setContextProperty("Logic", self) self.connected = False # get an instance of the network client self.net = Client()
def __init__(self): QApplication.__init__(self, sys.argv) self.setOrganizationName("Khertan Software") self.setOrganizationDomain("khertan.net") self.setApplicationName("BitPurse") self.view = QtDeclarative.QDeclarativeView() # Are we on mer ? So don't use opengl # As it didn't works on all devices if os.path.exists('/etc/mer-release'): fullscreen = True elif os.path.exists('/etc/aegis'): fullscreen = True self.glformat = QGLFormat().defaultFormat() self.glformat.setSampleBuffers(False) self.glw = QGLWidget(self.glformat) self.glw.setAutoFillBackground(False) self.view.setViewport(self.glw) else: fullscreen = False self.walletController = WalletController() self.rootContext = self.view.rootContext() self.rootContext.setContextProperty("argv", sys.argv) self.rootContext.setContextProperty("__version__", __version__) self.rootContext.setContextProperty("__upgrade__", __upgrade__ .replace('\n', '<br />')) self.rootContext.setContextProperty('WalletController', self.walletController) self.rootContext.setContextProperty('AddressesModel', self.walletController .addressesModel) self.rootContext.setContextProperty('TransactionsModel', self.walletController .transactionsModel) self.rootContext.setContextProperty('Settings', self.walletController .settings) self.view.setSource(QUrl.fromLocalFile( os.path.join(os.path.dirname(__file__), 'qml', 'main.qml'))) self.rootObject = self.view.rootObject() if fullscreen: self.view.showFullScreen() else: self.view.show() # self.loginPage = self.rootObject.findChild(QObject, "loginPage") self.sendPage = self.rootObject.findChild(QObject, "sendPage") self.aboutPage = self.rootObject.findChild(QObject, "aboutPage") self.walletController.onError.connect(self.rootObject.onError) # self.walletController.onConnected.connect(self.loginPage.onConnected) self.walletController.onTxSent.connect(self.sendPage.onTxSent)
def testModelExport(self): view = QDeclarativeView() dataList = [MyObject("Item 1"), MyObject("Item 2"), MyObject("Item 3"), MyObject("Item 4")] ctxt = view.rootContext() ctxt.setContextProperty("myModel", dataList) url = QUrl.fromLocalFile(adjust_filename("viewmodel.qml", __file__)) view.setSource(url) view.show() self.assertEqual(view.status(), QDeclarativeView.Ready)
def handle_url(path, style, url, for_import=False): if ((url.startswith('"') and url.endswith('"')) or (url.startswith("'") and url.endswith("'"))): url = url[1:-1] # Make a QUrl. url = QUrl(url.decode('unicode_escape')) if url.scheme() == 'data': return data_url(url) # If it's relative, build an absolute URL. If not, return. if not url.isRelative(): return url = url.toLocalFile() if url.startswith('/'): url = url[1:] else: url = style.path.join(path, url) if for_import: return url return find_url(style, url)
def createQmlComponent(filename, engine, context, parent=None): # Load the QML UI (this could take a while...) qcomponent = QDeclarativeComponent( engine, QUrl.fromLocalFile(QML(filename)), parent ) qobject = qcomponent.create(context) error = qcomponent.errorString() if len(error) > 0: print('Error while loading QML file: ' + error) return QmlGuiComponent(qobject, qcomponent)
def test_connection(self): self.message.setText('<span style="font-size: 10px; color: #000000;">' + 'Verbindung wird getestet.' + '</span>') self.nam.finished.connect(self.test_reply) self.nam.sslErrors.connect(self.ssl_errors) ssl_config = QSslConfiguration().defaultConfiguration() ssl_config.setCiphers(QSslSocket().supportedCiphers()) if self.certificate: certificate = QSslCertificate(encoded=self.certificate, format=QSsl.Pem) ssl_config.setCaCertificates([certificate]) else: ssl_config.setCaCertificates([]) url = QUrl(self.url_edit.text()) url.setPath("/".join(filter(bool, (url.path() + "/ajax/read.php").split("/")))) request = QNetworkRequest(url) request.setSslConfiguration(ssl_config) request.setRawHeader("Authorization", "Basic ".encode('utf-8') + b64encode((self.username_edit.text() + ":" + self.password_edit.text()).encode('utf-8'))) request.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded") self.replies.add(self.nam.post(request, QByteArray()))
def __init__(self, filename): QMainWindow.__init__(self) self.playButton = QPushButton('Play!') self.source = QUrl.fromLocalFile(filename) self.player = QMediaPlayer() self.player.setMedia(self.source) self.playButton.clicked.connect(self.play) self.setCentralWidget(self.playButton) self.playButton.show()
def takeEntryPoint(self): g = GraphParser.getInstance() for ax in self.axis: self.logger.info('Axis : %s' % ax) if g.entry_point: self.logger.info('Taking the entry point %s' % g.entry_point) self.last_url = QUrl(g.entry_point) inst = Jaime.getInstance() inst.view.load(QUrl(g.entry_point)) return True self.logger.error("Can't take entry point, graph has't entry point") return False
def newMessage(self,jid,contactName,message,picture=None,callback=False): activeConvJId = self.ui.getActiveConversation() max_len = min(len(message),20) if self.enabled: if(activeConvJId == jid or activeConvJId == ""): if self.vibra: self.vibra.start() return n = MNotification("wazapp.message.new",contactName, message); n.image = picture n.manager = self.manager; action = lambda: self.notificationCallback(jid) n.setAction(action); notifications = n.notifications(); if self.notifications.has_key(jid): nId = self.notifications[jid]['id']; for notify in notifications: if int(notify[0]) == nId: n.id = nId break if n.id != nId: del self.notifications[jid] if(n.publish()): nId = n.id; self.saveNotification(jid,{"id":nId,"callback":callback}); #if self.vibra: # self.vibra.start() if self.audio: soundPath = self.getCurrentSoundPath(); self._d(soundPath) self.audio.setMedia(QUrl.fromLocalFile(soundPath)); self.audio.play();