class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): vbox = QVBoxLayout(self) self.webEngineView = QWebEngineView() self.loadPage() vbox.addWidget(self.webEngineView) self.setLayout(vbox) self.setGeometry(300, 300, 350, 250) self.setWindowTitle('QWebEngineView') self.show() def loadPage(self): with open('test.html', 'r') as f: html = f.read() self.webEngineView.setHtml(html)
class Demo(QWidget): def __init__(self): super(Demo, self).__init__() self.resize(1000, 1000) self.setWindowTitle("Powered By PyQt5") self.user_label = QLabel("Subjects", self) self.user_line = QLineEdit(self) self.pwd_label = QLabel("Rate", self) self.pwd_line = QLineEdit(self) self.log_btn = QPushButton("Save", self) self.sign_btn = QPushButton("Clear", self) self.view = QWebEngineView() self.view.setHtml(raw_html) self.cb = QComboBox(self) self.cb.addItem("X") self.cb.addItem("Y") self.grid_layout = QGridLayout() self.grid_layout.addWidget(self.user_label, 0, 0) self.grid_layout.addWidget(self.user_line, 0, 1) self.grid_layout.addWidget(self.pwd_label, 1, 0) self.grid_layout.addWidget(self.pwd_line, 1, 1) self.h_layout = QHBoxLayout() self.h_layout.addWidget(self.log_btn) self.h_layout.addWidget(self.sign_btn) self.v_layout = QVBoxLayout() self.v_layout.addLayout(self.grid_layout) self.v_layout.addLayout(self.h_layout) self.v_layout.addWidget(self.view) self.setLayout(self.v_layout)
class MapWidget(QWidget): def __init__(self, parent: typing.Optional['QWidget']) -> None: super().__init__(parent=parent) self.ui() def ui(self): self.left = 50 * 2 self.top = 50 * 2 self.width = 640 self.height = 480 # self.setGeometry(self.left,self.top,self.width,self.height) # ------------------------- # init map widget # ------------------------- fMap = folium.Map(location=[user_lat, user_lon], tiles='Stamen Terrain', default_zoom_start=15) for _, row in hospitals_df.iterrows(): folium.Marker(location=[row['lat'], row['lon']]).add_to(fMap) data = io.BytesIO() fMap.save(data, close_file=False) self.map_widget = QWebEngineView(self) self.map_widget.resize(410, 460) # self.map_widget.move(5, 5) self.map_widget.setHtml(data.getvalue().decode()) self.show()
def init_UI(self): webview = QWebEngineView(self) webview.setHtml(self.question.content) webview.show() self.grid = QGridLayout() self.grid.setSpacing(10) passbtn = QPushButton("Pass", self) passbtn.clicked.connect(lambda: self.input_handler(None)) passbtn.resize(passbtn.sizeHint()) answer_buttons = [] for answer in self.question.answers: answer_button = QPushButton(answer.content, self) answer_button.clicked.connect(lambda: self.input_handler(None)) answer_button.resize(answer_button.sizeHint()) answer_buttons.append(answer_button) self.grid.addWidget(webview, 1, 1) self.grid.addWidget(passbtn, 1, 2) for idx, answer_button in enumerate(answer_buttons): self.grid.addWidget(answer_button, idx + 3, 1) self.setLayout(self.grid) self.setGeometry(300, 300, 1280, 720) self.setWindowTitle("Question {0}".format(self.id))
class WebEngineView(QMainWindow): def __init__(self): super(WebEngineView, self).__init__() self.setWindowTitle("打开网页例子") self.webView = QWebEngineView() self.setGeometry(5, 30, 1355, 730) # self.webView.setUrl("www.bing.com") # self.resize(1024,768) url = os.getcwd() + '\\web\\test.html' print(url) # self.webView.load(QUrl.fromLocalFile(url)) self.webView.setHtml(''' <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>标题1</h1> <h2>标题2</h2> </body> </html> ''') self.setCentralWidget(self.webView)
class App(QWidget): # 初期化 def __init__(self): super().__init__() self.browser = QWebEngineView() self.model = QStandardItemModel() self.listWidget = QListView() self.init_ui() # ユーザーインターフェイスを初期化する def init_ui(self): self.listWidget.setModel(self.model) self.listWidget.setAlternatingRowColors(True) self.listWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) self.listWidget.setSelectionMode( QAbstractItemView.SingleSelection ) self.listWidget.selectionModel().selectionChanged.connect(self.load_html) self.listWidget.setItemDelegate(ItemDelegate(self.listWidget)) grid = QGridLayout() grid.setSpacing(10) splitter = QSplitter(Qt.Horizontal) splitter.addWidget(self.listWidget) splitter.addWidget(self.browser) grid.addWidget(splitter,1,0) self.init_list_items() self.setLayout(grid) self.resize(1200, 800) self.listWidget.setMinimumWidth(600) self.browser.setMinimumWidth(600) self.show() # 記事本文をデータベースから取り出す(URLの) @classmethod #これはあってもなくても良い def fetch_contents(self, url): with closing(sqlite3.connect('articles.db')) as conn: c = conn.cursor() c.execute("SELECT contents FROM articles WHERE url=?;", [url]) rows = c.fetchall() for row in rows: return row[0] # ブラウザに記事をセットする def load_html(self): for i in self.listWidget.selectedIndexes(): html = '<h1>' + i.data()[1] + '</h1>' + self.fetch_contents(i.data()[0]) self.browser.setHtml(html) # リストを初期化する def init_list_items(self): with closing(sqlite3.connect('articles.db')) as conn: c = conn.cursor() c.execute("SELECT url,title FROM articles;") rows = c.fetchall() for row in rows: item = QStandardItem() item.setData(row, Qt.DisplayRole) item.setSizeHint(QSize(20, 30)) self.model.appendRow(item)
class WebEngineView(QMainWindow): def __init__(self): super(WebEngineView, self).__init__() self.setWindowTitle('打开外部网页例子') self.setGeometry(5, 30, 1355, 730) self.initUI() def initUI(self): self.browser = QWebEngineView() #显示网页 #self.browser.load(QUrl('https://www.jd.com')) #显示本地页面 url = os.getcwd() + '/test.html' #self.browser.load(QUrl.fromLocalFile(url)) #显示嵌入web代码页面 self.browser.setHtml(''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试页面</title> </head> <body> <h1>Hello world PyQt5</h1> <h1>Hello world PyQt5</h1> <h1>Hello world PyQt5</h1> <h1>Hello world PyQt5</h1> <h1>Hello world PyQt5</h1> </body> </html>''') self.setCentralWidget(self.browser)
class DocumentationWidget(QWidget): def __init__(self, content=None, parent=None): super(DocumentationWidget, self).__init__(parent) self.setWindowTitle("Документация") self.__docs_view = QWebEngineView(self) self.__content = content self.__docs_file = os.getcwd() + '/common/docs.html' self.load_from_html_doc(self.__docs_file) self.setup_ui() def setup_ui(self): hbox_layout = QHBoxLayout() hbox_layout.addWidget(self.__docs_view) self.setLayout(hbox_layout) def load_from_html_doc(self, file_name): with open(file_name, 'r', encoding='utf-8') as f: self.__content = f.read() self.__docs_view.setHtml(self.__content)
class ResultsWidget(QWidget): def __init__(self, html, markdown): super(ResultsWidget, self).__init__() self.markdown = markdown QBtn = QDialogButtonBox.Ok self.layout = QVBoxLayout() self.webrenderer = QWebEngineView() self.webrenderer.setHtml(html) self.layout.addWidget(self.webrenderer) if platform.system() in ["Darwin", "Windows"]: self.mdbutton = QPushButton("Copy Markdown to clipboard") self.mdbutton.clicked.connect(self.md_to_clipboard) self.layout.addWidget(self.mdbutton) self.setLayout(self.layout) def md_to_clipboard(self): if platform.system() == "Darwin": self.setClipboardDataMac(self.markdown) else: self.setClipboardDataWin(self.markdown) self.mdbutton.setText("Copied!") def setClipboardDataWin(self, data): win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_TEXT, data) def setClipboardDataMac(self, data): p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE) p.stdin.write(data.encode("utf-8")) p.stdin.close() retcode = p.wait()
def __init__(self): super().__init__() self.setWindowTitle('Car rental branches') self.window_width, self.window_height = 650, 450 self.setMinimumSize(self.window_width, self.window_height) layout = QVBoxLayout() self.setLayout(layout) #Folium map initialization coordinate = (13.746556162678786, 100.53081701876293) m = folium.Map(tiles='Stamen Terrain', zoom_start=15, location=coordinate) #Location marker folium.Marker( location=[13.746556162678786, 100.53081701876293], popup="Pathumwan branch", icon=folium.Icon(icon="cloud"), ).add_to(m) # save map data to data object data = io.BytesIO() m.save(data, close_file=False) webView = QWebEngineView() webView.setHtml(data.getvalue().decode()) layout.addWidget(webView)
class FormWidget(QWidget): def __init__(self, parent): super(FormWidget, self).__init__(parent) self.__controls() self.__layout() def __controls(self): html = open(f"{data_dir}/test.html", 'r').read() self.browser = QWebEngineView() self.browser.setPage(WebEnginePage(self.browser)) self.browser.setHtml(html) self.browser.loadFinished.connect(self.onLoadFinished) def onLoadFinished(self, ok): if ok: self.browser.page().runJavaScript("helloWorld(1, \"12\")", self.ready) def __layout(self): self.vbox = QVBoxLayout() self.hBox = QVBoxLayout() self.hBox.addWidget(self.browser) self.vbox.addLayout(self.hBox) self.setLayout(self.vbox) def ready(self, returnValue): print(returnValue)
def print_to_pdf(html, pdf_file): from PyQt5.QtCore import QUrl from PyQt5 import QtGui, QtCore global qapp if qapp is None: qapp = QApplication(['--disable-gpu', '--disable-extension']) view = QWebEngineView() page = QWebEnginePage() view.setPage(page) def pdf_printed(*args, **kwargs): page.pdfPrintingFinished.disconnect() page.loadFinished.disconnect() qapp.quit() def page_loaded(*args, **kwargs): page.pdfPrintingFinished.connect(pdf_printed) page.printToPdf( pdf_file, QtGui.QPageLayout( QtGui.QPageSize(QtGui.QPageSize.A4), QtGui.QPageLayout.Portrait, QtCore.QMarginsF(25, 25, 25, 25) ) ) page.loadFinished.connect(page_loaded) if isinstance(html, bytes): html = html.decode('utf-8') view.setHtml(html, QUrl('file://')) qapp.exec_() return os.path.basename(pdf_file)
class MyWebEngineView(QWebEngineView): def __init__(self, main): super().__init__() self.main = main self.view = QWebEngineView() self.update_button(main, parent=QAction) # To-do: --> self.auto_update self.web_dockwidget = QDockWidget(MDV_TITLE, self) self.web_dockwidget.setWidget(self.view) self.web_dockwidget.setAllowedAreas(Qt.RightDockWidgetArea) self.web_dockwidget.setMinimumWidth(MDV_MINIMUM_WIDTH) def update_button(self, main, parent): update_button = QPushButton(main) update_button.setText("Update") update_button.setShortcut(QKeySequence.Refresh) update_button.clicked.connect(self.md_to_html) main.menuBar().setCornerWidget(update_button, corner=Qt.TopRightCorner) def md_to_html(self): md = Markdown() raw_text = self.main.raw_editor.toPlainText() content = md.convert(raw_text) self.view.setHtml(content)
class MarkdownPreview(QDockWidget): def __init__(self, file, text): super().__init__() self.file = file self.text = text self.setWindowTitle('Markdown Preview') self.markdown_extras = ['tables', 'fenced-code-blocks', 'task-list'] text.textChanged.connect(self.on_update) self.text.verticalScrollBar().valueChanged.connect(self.sync_scroll) self.web = QWebEngineView() self.web.setHtml(markdown2.markdown(self.text.toPlainText(), extras=self.markdown_extras), baseUrl=QUrl.fromLocalFile(file)) self.web.loadFinished.connect(self.sync_scroll) self.setWidget(self.web) def sync_scroll(self): self.web.page().runJavaScript( f'scrollTo({self.text.horizontalScrollBar().value()}, document.body.scrollHeight * {self.text.verticalScrollBar().value()} / {self.text.verticalScrollBar().maximum()});' ) def on_update(self): self.web.page().setHtml(markdown2.markdown( self.text.toPlainText(), extras=self.markdown_extras), baseUrl=QUrl.fromLocalFile(self.file))
class MainWindow(QMainWindow): def __init__(self): super(QMainWindow, self).__init__() screen = QDesktopWidget().screenGeometry() self.resize(screen.width(), screen.height()) self.setWindowIcon(QIcon('./static/images/group_five.ico')) self.setWindowTitle("五人小组") #相当于初始化这个加载web的控件 self.browser = QWebEngineView() self.browser.setHtml(''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>Hello PyQt5</h1> <h1>Hello PyQt5</h1> <h1>hello PyQt5</h1> <h1>hello PyQt5</h1> <h1>hello PyQt5</h1> <h1>Hello PyQt5</h1> </body> </html> ''') self.setCentralWidget(self.browser)
class DataFrameView(QWidget): def __init__(self): super().__init__() vbox = QVBoxLayout(self) self.webEngineView = QWebEngineView() self.setData() vbox.addWidget(self.webEngineView) self.setLayout(vbox) self.setGeometry(GEOMETRY[0], GEOMETRY[1], GEOMETRY[2], GEOMETRY[3]) self.setWindowTitle('Search Data') logger.debug("DataFrameView object created!") def setData(self, df=None): html = "" html += "<html><style>" html += TABLE_CSS html += "</style><body><div class=\"container\">" if df is not None: html += df.to_html() html += "</div></body></html>" self.webEngineView.setHtml(html) logger.info("Data Frame View added the HTML data along with css!")
class BookView(QSplitter): def __init__(self, parent=None): super(BookView, self).__init__(parent=parent) self.create_layout() self.create_connections() def create_layout(self): self.web_view = QWebEngineView() self.chapter_list = QListWidget() self.next_button = QPushButton("Next chapter") self.previous_button = QPushButton("Previous chapter") hbox = QHBoxLayout() hbox.addStretch() hbox.addWidget(self.previous_button) hbox.addWidget(self.next_button) vbox = QVBoxLayout() vbox.addWidget(QLabel("Chapters")) vbox.addWidget(self.chapter_list) vbox.addLayout(hbox) widget = QWidget() widget.setLayout(vbox) self.web_view.setUrl(QtCore.QUrl("http://")) self.webPage = self.web_view.page() self.addWidget(self.web_view) self.addWidget(widget) def create_connections(self): chlist = self.chapter_list self.next_button.clicked.connect(lambda: chlist.setCurrentRow(0 if chlist.currentRow() == chlist.count() - 1 else chlist.currentRow() + 1)) self.previous_button.clicked.connect(lambda: chlist.setCurrentRow(chlist.count() - 1 if chlist.currentRow() == 0 else chlist.currentRow() - 1)) self.chapter_list.currentRowChanged[int].connect(self.set_chapter) def set_chapter(self, num=None): if num is None: num = self.chapter_list.currentRow() if num < 0: num = len(self.book.chapters) - 1 elif num >= len(self.book.chapters): num = 0 self.web_view.setHtml(self.book.get_chapter(num).decode(encoding="utf-8")) self.webPage = self.web_view.page() self.webPage.setZoomFactor(2) def load_book(self, book_id): self.book = Book(book_id) self.chapter_list.clear() for chapter in self.book.chapters: self.chapter_list.addItem(chapter[0]) self.chapter_list.setCurrentRow(0)
class TabWelcome(QWidget): #------------------------------------------------------------------------------- # __init__() #------------------------------------------------------------------------------- def __init__(self, parent=None): QWidget.__init__(self, parent) self.txtWelcome = QWebEngineView() self.txtWelcome.setHtml(welcome) vLayout = QVBoxLayout(self) vLayout.addWidget(self.txtWelcome)
async def _print(webview: QWebEngineView, html, printer): """печать протокола испытания""" webview.setZoomFactor(1) # webview.setBaseSize(3508, 2480) webview.setHtml(html, baseUrl=QUrl("file://")) print("Report\t\t->диалог выбора принтера") if QPrintDialog(printer).exec_(): print("Report\t\t->отправка протокола на печать") page = webview.page() page.print(printer, Report._onPrinted)
class BrowserWidget(QtWidgets.QWidget): def __init__(self): """ Create main window with browser and a button """ super(BrowserWidget, self).__init__() self.layout = QtWidgets.QHBoxLayout() self.setLayout(self.layout) self.webview = QWebView() self.layout.addWidget(self.webview) self.webview.urlChanged.connect(self.url_changed) self.set_form_handler(self._default_form_handler) #self.default_url = "https://dokit.met.no/fou/kl/prosjekter/eemep/esnap_userdoc" #self.tb_url.setText(self.default_url) #self.browse() def browse(self): """browse an url""" url = self.tb_url.text() if self.tb_url.text() else self.default_url self.webview.setPage(QWebPage()) self.webview.load(QtCore.QUrl(url)) self.webview.show() def url_changed(self, url): """ Triggered when the url is changed """ def set_html(self, text: str): """ set html string""" self.web_page = StartWebPage() self.webview.setPage(self.web_page) self.webview.page().formSubmitted.connect(self._handle_formSubmitted) self.webview.setHtml(text) @staticmethod def _default_form_handler(dict): for key, value in dict: print(str.format("{0} => {1}", key, value)) def set_form_handler(self, handler): """ the form handler should accept a dictionary with query results as input """ self.form_handler = handler def evaluate_javaScript(self, jscript): self.webview.page().mainFrame().evaluateJavaScript(jscript) def _handle_formSubmitted(self, url): # I don't manage to get the right query strings from the web-page print("handleFromSubmitted:" + url.toString()) self.form_handler( QtCore.QUrlQuery(url).queryItems(QtCore.QUrl.FullyDecoded))
class HiScoresWindow(QtWidgets.QDialog): _TEMPLATE = """<html> <head> <style> table {{ border: 3px double black; width: 100%; }} td.place {{ text-align: center; font-size: 17pt; }} td.name {{ font-size: 17pt; }} td.score {{ font-weight: bold; font-size: 17pt; }} </style> </head> <body> <h1 align='center'>{}</h1> <table>{}</table> </body> </html>""" _ROW_TEMPLATE = """<tr> <td class='place'>{}</td> <td class='name'>{}</td> <td class='score'>{}</td> </tr>""" def __init__(self, scoreboard, size, parent=None): super().__init__(parent) self._size = size self._scores = scoreboard self._viewer = QWebEngineView() self._btns = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) self._btns.accepted.connect(self.close) layout = QtWidgets.QVBoxLayout() layout.addWidget(self._viewer) layout.addWidget(self._btns) self.setLayout(layout) self.setWindowTitle('Go') @staticmethod def _make_row(place, name, score): return HiScoresWindow._ROW_TEMPLATE.format(place, name, score) def prepare(self): scores = self._scores.get_scores(self._size) table = ''.join( HiScoresWindow._make_row(place + 1, name, score) for (place, (name, score)) in enumerate(scores)) self._viewer.setHtml(HiScoresWindow._TEMPLATE.format('Records', table))
def show_qt(fig): raw_html = '<html><head><meta charset="utf-8" />' raw_html += '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>' raw_html += '<body>' raw_html += py.offline.plot(fig, include_plotlyjs=False, output_type='div') raw_html += '</body></html>' fig_view = QWebEngineView() fig_view.setHtml(raw_html) fig_view.show() fig_view.raise_() return fig_view
class MainWin(QMainWindow): """主窗口""" def __init__(self, parent=None): super().__init__(parent=parent) self.setWindowTitle("QWebEngineView 加载本地页面") file_path = "03_高级界面控件/示例内容/sources/htmls/localhtml.html" with open(file_path, 'r') as file: self.browser = QWebEngineView() self.browser.setHtml(file.read()) self.setCentralWidget(self.browser)
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.browser = QWebEngineView() self.browser.setHtml("<h1>Test</h1>") self.browser.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.setCentralWidget(self.browser) self.show() def html(self, value): self.browser.setHtml(value)
class Example(QWidget): def __init__(self): super().__init__() self.resize(640, 320) self.setWindowTitle('PyQt-5 WebEngine') page = "https://www.google.com" self.url = QLineEdit(page) self.url.setPlaceholderText(page) self.go = QPushButton("Ir") self.go.clicked.connect(self.btnIrClicked) self.nav_bar = QHBoxLayout() self.nav_bar.addWidget(self.url) self.nav_bar.addWidget(self.go) self.progress = QProgressBar() self.progress.setValue(0) html = """ <!DOCTYPE HTML> <html> <head> <title>Example Local HTML</title> </head> <body> <p>Este es un archivo <code>HTML</code> local.</p> <p>Si deseas acceder página indica su <code>URL</code> y presiona <b>Ir</b></p> </body> </html> """ self.web_view = QWebEngineView() self.web_view.loadProgress.connect(self.webLoading) self.web_view.setHtml(html) root = QVBoxLayout() root.addLayout(self.nav_bar) root.addWidget(self.web_view) root.addWidget(self.progress) self.setLayout(root) def btnIrClicked(self, event): url = QUrl(self.url.text()) self.web_view.page().load(url) def webLoading(self, event): self.progress.setValue(event)
class PyChrome(QWidget): def __init__(self): super().__init__() self.resize(640, 320) self.setWindowTitle('PyQt-5 WebEngine') page = "https://www.google.com" self.url = QLineEdit(page) self.url.setPlaceholderText(page) self.go = QPushButton("Ir") self.go.clicked.connect(self.btnIrClicked) self.nav_bar = QHBoxLayout() self.nav_bar.addWidget(self.url) self.nav_bar.addWidget(self.go) self.progress = QProgressBar() self.progress.setValue(0) html = """ <!DOCTYPE HTML> <html> <head> <title>Example Local HTML</title> </head> <body> <p>Este es un archivo <code>HTML</code> local.</p> <p>Si deseas acceder página indica su <code>URL</code> y presiona <b>Ir</b></p> </body> </html> """ self.web_view = QWebEngineView() self.web_view.loadProgress.connect(self.webLoading) self.web_view.setHtml(html) root = QVBoxLayout() root.addLayout(self.nav_bar) root.addWidget(self.web_view) root.addWidget(self.progress) self.setLayout(root) def btnIrClicked(self, event): url = QUrl(self.url.text()) self.web_view.page().load(url) def webLoading(self, event): self.progress.setValue(event)
def show_qt(fig): raw_html = '<html><head><meta charset="utf-8" />' raw_html += '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>' raw_html += '<body>' raw_html += po.plot(fig, include_plotlyjs=False, output_type='div') raw_html += '</body></html>' fig_view = QWebEngineView() # setHtml has a 2MB size limit, need to switch to setUrl on tmp file # for large figures. fig_view.setHtml(raw_html) fig_view.show() fig_view.raise_() return fig_view
class TestReportWidget(QWidget): def __init__(self): super().__init__() self.setWindowTitle(f'性能評価 詳細 - {Project.project_name()}') self.test_report_model = TestReportModel() self.web_view = QWebEngineView(self) html_size = QSize(890, 390) self.web_view.setFixedSize(html_size) self.setFixedSize(html_size) def reload_html(self): html = self.test_report_model.generate_test_details() self.web_view.setHtml(html)
def show_qt(fig): # <-- treated as another button raw_html = '<html><head><meta charset="utf-8" />' raw_html += '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>' raw_html += '<body>' raw_html += po.plot(fig, include_plotlyjs=False, output_type='div') # 'div'for embedding graphs in an HTML file with other graphs or HTML markup raw_html += '</body></html>' fig_view = QWebEngineView() # setHtml has a 2MB size limit, need to switch to setUrl on tmp file # for large figures. fig_view.setHtml(raw_html) fig_view.show() # <-- only show in window fig_view.raise_() return fig_view
def init_view(self): """Read HTML file and set it on the page.""" base_url = QUrl( f"http://localhost:{self._mw.mediaServer.getPort()}/" f"_addons/{self.package_name}/web/visualization/graph.html" ) html_path = os.path.join( parent_dir, "web", "visualization", "graph.html" ) with open(html_path, "r", encoding='utf-8') as f: html = f.read() QWebEngineView.setHtml(self, html, baseUrl=base_url)
def __init__(self): super().__init__() self.setWindowTitle('Folium Map') self.showMaximized() layout = QVBoxLayout() self.setLayout(layout) m = folium.Map([37, 0], zoom_start=1, tiles="stamentoner") merc = os.path.join("", "un") # if not os.path.isfile(merc): # print(f"Could not find {merc}") # else: # img = folium.raster_layers.ImageOverlay( # name="Mercator projection SW", # image=merc, # bounds=[[-82, -180], [82, 180]], # opacity=0.6, # interactive=True, # cross_origin=False, # zindex=1, # ) # # folium.Popup("I am an image").add_to(img) # # img.add_to(m) # # m = folium.Map([37, 0], zoom_start=1, tiles="stamentoner") folium.raster_layers.ImageOverlay( image=merc, name="I am a jpeg", bounds=[[-82, -180], [82, 180]], opacity=1, interactive=False, cross_origin=False, zindex=1, alt="Wikipedia File:Mercator projection SW.jpg", ).add_to(m) folium.LayerControl().add_to(m) # save map data to data object data = io.BytesIO() m.save(data, close_file=False) webView = QWebEngineView() webView.setHtml(data.getvalue().decode()) layout.addWidget(webView)
def _load(self): base_url = QUrl( f"http://localhost:{self._mw.mediaServer.getPort()}/" f"_addons/{package}/gui/web/graph.html" ) html_path = os.path.join(parent_dir, "web", "graph.html") with open(html_path, "r") as f: html = f.read() if theme_manager and theme_manager.night_mode: html = html.replace("<body>", "<body class='nightMode night_mode'>") QWebEngineView.setHtml(self, html, baseUrl=base_url)
def __init__(self, title, html_text, width=650, height=400, parent=None): QtWidgets.QDialog.__init__(self, parent) self.setModal(True) self.setWindowTitle(title) layout = QtWidgets.QVBoxLayout(self) web_view = QWebView(self) web_view.setHtml(html_text) text_area = QtWidgets.QScrollArea(self) text_area.setWidget(web_view) text_area.setWidgetResizable(True) text_area.setFixedHeight(height) text_area.setFixedWidth(width) bbox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) bbox.accepted.connect(self.accept) layout.addWidget(text_area) layout.addWidget(bbox)
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) testFile = 'sphinx_cheet_sheet.rst' # text = TEXT with open(testFile,'r') as f: text = f.read() formatter = HtmlFormatter() # html = highlight(text, PythonLexer(), formatter) extra_settings = {'initial_header_level': 4, 'doctitle_xform': 0, 'syntax_highlight': 'short', 'stylesheet - path': 'html4css1.css', 'embed-stylesheet': 'no' } # html = publish_parts(text, writer_name='html',settings_overrides=extra_settings)['html_body'] html = publish_parts(text, writer_name='html',settings_overrides=extra_settings)['whole'] print(html) self.htmlview = QWebEngineView() self.htmlview.setHtml(html) self.setCentralWidget(self.htmlview) self.show()
class MainWindow(QWidget): def __init__(self): QWidget.__init__(self) self.resize(1600, 940) self.setWindowTitle('OpenVR tracking data') self.webview = QWebEngineView() self.button = QPushButton('Quit', self) self.button.clicked.connect(self.close) layout = QVBoxLayout(self) layout.setSpacing(0) # layout.setMargin(0) layout.addWidget(self.button) layout.addWidget(self.webview) # XXX check result openvr.init(openvr.VRApplication_Scene) poses_t = openvr.TrackedDevicePose_t * openvr.k_unMaxTrackedDeviceCount self.poses = poses_t() self.timer = QTimer() self.timer.timeout.connect(self.update_page) self.timer.start(50) # ms def update_page(self): openvr.VRCompositor().waitGetPoses(self.poses, len(self.poses), None, 0) vrsys = openvr.VRSystem() poses = {} hmd_index = openvr.k_unTrackedDeviceIndex_Hmd beacon_indices = [] controller_indices = [] for i in range(len(self.poses)): device_class = vrsys.getTrackedDeviceClass(i) if device_class == openvr.TrackedDeviceClass_Invalid: continue elif device_class == openvr.TrackedDeviceClass_Controller: controller_indices.append(i) elif device_class == openvr.TrackedDeviceClass_TrackingReference: beacon_indices.append(i) model_name = vrsys.getStringTrackedDeviceProperty(i, openvr.Prop_RenderModelName_String) pose = self.poses[i] poses[i] = dict( model_name=model_name, device_is_connected=pose.bDeviceIsConnected, valid=pose.bPoseIsValid, tracking_result=pose.eTrackingResult, d2a=pose.mDeviceToAbsoluteTracking, velocity=pose.vVelocity, # m/s angular_velocity=pose.vAngularVelocity # radians/s? ) template = jinja_env.get_template('status.html') html = template.render(poses=poses, hmd_index=hmd_index, controller_indices=controller_indices, beacon_indices=beacon_indices) self.webview.setHtml(html) self.update() def closeEvent(self, event): openvr.shutdown()
from PyQt5.QtOpenGL import QGLWidget import plots html = '''<html> <head> <title>Plotly Example</title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> %(plot_content)s </body> </html>''' if __name__ == '__main__': app = QApplication(sys.argv) w = QWebView() w.resize(800, 600) w.setWindowTitle('Simple Plot') # QWebSettings.globalSettings().setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) # QWebSettings.globalSettings().setAttribute(QWebSettings.WebGLEnabled, True) plot_content = plots.plot3d() w.setHtml(html%{'plot_content':plot_content}) w.show() sys.exit(app.exec_())
class X0h(XrayServerWidget): name = "X0h" description = "X0h" icon = "icons/x0h.png" maintainer = "Luca Rebuffi" maintainer_email = "luca.rebuffi(@at@)elettra.eu" priority = 1 category = "X0h" keywords = ["data", "file", "load", "read"] want_main_area = 1 outputs = [{"name": "xrayserver_data", "type": DataExchangeObject, "doc": "xrayserver_data", "id": "xrayserver_data"}, ] xway = Setting(2) wave = Setting(0.0) line = Setting("Cu-Ka1") coway = Setting(0) code = Setting("Silicon") amor = Setting("") chem = Setting("") rho = Setting(0.0) i1 = Setting(1) i2 = Setting(1) i3 = Setting(1) df1df2 = Setting(1) detail = Setting(1) def __init__(self): super().__init__() left_box_1 = oasysgui.widgetBox(self.controlArea, "X0h Request Form", addSpace=True, orientation="vertical", width=400, height=630) left_box_2 = oasysgui.widgetBox(left_box_1, "X-rays", addSpace=True, orientation="horizontal", width=380, height=110) left_box_2_1 = oasysgui.widgetBox(left_box_2, "", addSpace=True, orientation="vertical", width=150, height=110) gui.radioButtons(left_box_2_1, self, "xway", ["Wavelength (Å)", "Energy (keV)", "Characteristic line"], callback=self.set_xway ) self.box_wave = oasysgui.widgetBox(left_box_2, "", addSpace=True, orientation="vertical", width=190) gui.separator(self.box_wave, height=10) oasysgui.lineEdit(self.box_wave, self, "wave", label="", labelWidth=0, addSpace=False, valueType=float, orientation="horizontal") self.box_line = oasysgui.widgetBox(left_box_2, "", addSpace=True, orientation="horizontal", width=190, height=110) gui.separator(self.box_line, height=120) XRayServerGui.combobox_text(self.box_line, self, "line", label="", labelWidth=0, items=self.get_lines(), sendSelectedValue=True, orientation="horizontal", selectedValue=self.line) button = gui.button( self.box_line, self, "?", callback=self.help_lines) button.setFixedWidth(15) self.set_xway() left_box_3 = oasysgui.widgetBox(left_box_1, "Target", addSpace=True, orientation="horizontal", width=380, height=140) left_box_3_1 = oasysgui.widgetBox(left_box_3, "", addSpace=True, orientation="vertical", width=125, height=110) gui.radioButtons(left_box_3_1, self, "coway", ["Crystal", "Other Material", "Chemical Formula"], callback=self.set_coway ) self.box_crystal = oasysgui.widgetBox(left_box_3, "", addSpace=True, orientation="horizontal", width=210) XRayServerGui.combobox_text(self.box_crystal, self, "code", label="", labelWidth=0, items=self.get_crystals(), sendSelectedValue=True, orientation="horizontal", selectedValue=self.code) button = gui.button( self.box_crystal, self, "?", callback=self.help_crystals) button.setFixedWidth(15) self.box_other = oasysgui.widgetBox(left_box_3, "", addSpace=True, orientation="horizontal", width=210) gui.separator(self.box_other, height=75) XRayServerGui.combobox_text(self.box_other, self, "amor", label="", labelWidth=0, items=self.get_others(), sendSelectedValue=True, orientation="horizontal", selectedValue=self.amor) button = gui.button( self.box_other, self, "?", callback=self.help_others) button.setFixedWidth(15) self.box_chemical = oasysgui.widgetBox(left_box_3, "", addSpace=True, orientation="vertical", width=210, height=140) gui.separator(self.box_chemical, height=50) oasysgui.lineEdit(self.box_chemical, self, "chem", label=" ", labelWidth=1, addSpace=False, valueType=str, orientation="horizontal", callback=self.set_rho) oasysgui.lineEdit(self.box_chemical, self, "rho", label=u"\u03C1" + " (g/cm3)", labelWidth=60, addSpace=False, valueType=float, orientation="horizontal") self.set_coway() left_box_4 = oasysgui.widgetBox(left_box_1, "Reflection", addSpace=True, orientation="horizontal", width=380, height=60) oasysgui.lineEdit(left_box_4, self, "i1", label="Miller indices", labelWidth=200, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "i2", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "i3", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") left_box_5 = oasysgui.widgetBox(left_box_1, "Database Options for dispersion corrections df1, df2", addSpace=True, orientation="vertical", width=380, height=185) gui.radioButtons(left_box_5, self, "df1df2", ["Auto (Henke at low energy, X0h at mid, Brennan-Cowan\nat high)", "Use X0h data (5-25 keV or 0.5-2.5 A), recommended for\nBragg diffraction", "Use Henke data (0.01-30 keV or 0.4-1200 A),\nrecommended for soft x-rays", "Use Brennan-Cowan data (0.03-700 keV or 0.02-400 A)", "Compare results for all of the above sources"]) left_box_6 = oasysgui.widgetBox(left_box_1, "Output Options", addSpace=True, orientation="vertical", width=380, height=50) gui.checkBox(left_box_6, self, "detail", "Print atomic coordinates", labelWidth=250) button = gui.button(self.controlArea, self, "Get X0h!", callback=self.submit) button.setFixedHeight(30) gui.rubber(self.controlArea) self.tabs = [] self.tabs_widget = oasysgui.tabWidget(self.mainArea) self.initializeTabs() self.x0h_output = QWebView(self.tabs[0]) self.tabs[0].layout().addWidget(self.x0h_output) self.x0h_output.setFixedHeight(640) self.x0h_output.setFixedWidth(740) def getLeftPartWidth(self): return 415 def set_xway(self): self.box_wave.setVisible(self.xway!=2) self.box_line.setVisible(self.xway==2) def set_coway(self): self.box_crystal.setVisible(self.coway==0) self.box_other.setVisible(self.coway==1) self.box_chemical.setVisible(self.coway==2) def set_rho(self): if not self.chem is None: if not self.chem.strip() == "": self.chem = self.chem.strip() self.rho = XRayServerPhysics.getMaterialDensity(self.chem) def initializeTabs(self): current_tab = self.tabs_widget.currentIndex() size = len(self.tabs) for index in range(0, size): self.tabs_widget.removeTab(size-1-index) self.tabs = [gui.createTabPage(self.tabs_widget, "X-ray Server Ouput"), gui.createTabPage(self.tabs_widget, "Critical Angle for TER"), gui.createTabPage(self.tabs_widget, "Darwin Curve (" + u"\u03C3" + " Pol.)"), gui.createTabPage(self.tabs_widget, "Darwin Curve (" + u"\u03C0" + " Pol.)"), ] for tab in self.tabs: tab.setFixedHeight(650) tab.setFixedWidth(750) self.plot_canvas = [None, None, None] self.tabs_widget.setCurrentIndex(current_tab) def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") self.checkFields() parameters = {} parameters.update({"xway" : str(self.xway + 1)}) parameters.update({"wave" : str(self.wave)}) parameters.update({"line" : self.line}) parameters.update({"coway" : str(self.coway)}) parameters.update({"code" : self.code}) parameters.update({"amor" : self.amor}) parameters.update({"chem" : self.chem}) parameters.update({"rho" : str(self.rho)}) parameters.update({"i1" : str(self.i1)}) parameters.update({"i2" : str(self.i2)}) parameters.update({"i3" : str(self.i3)}) parameters.update({"df1df2" : self.decode_df1df2()}) parameters.update({"modeout" : "0" }) parameters.update({"detail" : str(self.detail)}) try: response = HttpManager.send_xray_server_request_GET(APPLICATION, parameters) response = self.clear_response(response) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response) data0, data1, data2 = self.extract_plots(response) try: exchange_data = DataExchangeObject("XRAYSERVER", "X0H") if self.coway == 0: # crystals dictionary = self.extract_structure_data(response) exchange_data.add_content("structure", dictionary["structure"]) exchange_data.add_content("h", self.i1) exchange_data.add_content("k", self.i2) exchange_data.add_content("l", self.i3) exchange_data.add_content("d_spacing", dictionary["d_spacing"]) exchange_data.add_content("energy", dictionary["energy"]) exchange_data.add_content("bragg_angle", dictionary["bragg_angle"]) exchange_data.add_content("xr0", dictionary["xr0"]) exchange_data.add_content("xi0", dictionary["xi0"]) exchange_data.add_content("xrh_s", dictionary["xrh_s"]) exchange_data.add_content("xih_s", dictionary["xih_s"]) exchange_data.add_content("xrh_p", dictionary["xrh_p"]) exchange_data.add_content("xih_p", dictionary["xih_p"]) exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content("x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content("x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) except: #problems with xrayserver, no data found pass except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: ShowTextDialog.show_text("Error", 'Error Occurred.\nReason: ' + str(e), parent=self) self.setStatusMessage("") self.progressBarFinished() def clear_response(self, response): # remove links output = response.split("<hr>")[0] + "\n</body></html>" # remove "get the curve" images output = "".join(output.split("<input type=image src=\"images/get_the_curve.gif\" border=0 width=102 height=12 alt=\"Get the reflectivity curve\">")) output = "".join(output.split("<input type=image src=\"images/get_the_curve.gif\" border=0 width=102 height=12 alt=\"Get the Bragg curve (sigma)\">")) output = "".join(output.split("<input type=image src=\"images/get_the_curve.gif\" border=0 width=102 height=12 alt=\"Get the Bragg curve (pi)\">")) # remove question mark images and links output = "".join(output.split("<a href=\"javascript:void(0)\" onClick=\"Wfloat(\'images/x0h_help_0.gif\',\'x0h_0\',740,357);\"><b>?</b></a> ")) output = "".join(output.split("<a href=\"javascript:void(0)\" onClick=\"Wfloat(\'images/x0h_help_h.gif\',\'x0h_h\',705,853);\"><b>?</b></a> ")) temp_1, temp_2 = output.split("style.css") output = temp_1 + XRAY_SERVER_URL + "/style.css" + temp_2 output = output.split("<td><img src=\"images/x.gif\" width=31 height=32 border=0></td>")[0] + "</tr></tr></body></html>" return output def checkFields(self): pass def decode_df1df2(self): if self.df1df2 == 0: return "-1" elif self.df1df2 == 1: return "0" elif self.df1df2 == 2: return "2" elif self.df1df2 == 3: return "4" elif self.df1df2 == 4: return "10" def extract_structure_data(self, response=""): dictionary = {} try: dictionary["structure"] = response.split(sep="<tr><td>Structure : </td><td>")[1].split("</td></tr>")[0].strip() dictionary["energy"] = float(response.split(sep="<dt>Closest absorption edge (keV) : </dt>")[1].split(sep="<dt>")[3].split(sep="</dt>")[0].strip()) try: x0_string = response.split(sep="Critical angle for TER (degr., mrad) : </dt>")[1].split(sep="<dt>")[1].split(sep=", ") dictionary["xr0"] = float(x0_string[0].strip()) dictionary["xi0"] = float(x0_string[1].split(sep="<sub>")[0].strip()) except: dictionary["xr0"] = 0.0 dictionary["xi0"] = 0.0 try: bragg_angle_d_spacing_string = response.split("<dt> ESinTheta=12.398/(2d) : </dt>")[1].split(sep="<dt>") dictionary["bragg_angle"] = float(bragg_angle_d_spacing_string[1].split(sep="</dt>")[0].strip()) dictionary["d_spacing"] = float(bragg_angle_d_spacing_string[2].split(sep="</dt>")[0].strip()) except: dictionary["bragg_angle"] = 0.0 dictionary["d_spacing"] = 0.0 try: xh_s_string = response.split(sep="<dt><b><i>Sigma <sub> </sub></i></b></dt>")[1].split(sep="<dt>")[1].split(sep=", ") dictionary["xrh_s"] = float(xh_s_string[0].strip()) dictionary["xih_s"] = float(xh_s_string[1].split(sep="<sub>")[0].strip()) except: dictionary["xrh_s"] = 0.0 dictionary["xih_s"] = 0.0 try: xh_p_string = response.split(sep="<dt><b><i>Pi <sub> </sub></i></b></dt>")[1].split(sep="<dt>")[1].split(sep=", ") dictionary["xrh_p"] = float(xh_p_string[0].strip()) dictionary["xih_p"] = float(xh_p_string[1].split(sep="<sub>")[0].strip()) except: dictionary["xrh_p"] = 0.0 dictionary["xih_p"] = 0.0 except: dictionary["structure"] = "Problems while reading structure" dictionary["energy"] = 0.0 return dictionary def extract_plots(self, response): form_1_begin = False form_2_begin = False form_3_begin = False form_1 = None form_2 = None form_3 = None rows = response.split("\n") for row in rows: if form_1_begin: if "<td>" in row: form_1_begin = False elif form_2_begin: if "<td>" in row: form_2_begin = False elif form_3_begin: if "<td>" in row: form_3_begin = False if form_1_begin: form_1.append(row) elif form_2_begin: form_2.append(row) elif form_3_begin: form_3.append(row) if "/cgi/ter_form.pl" in row: if form_1 is None: form_1 = [] form_1_begin = True if "/cgi/gid_form.pl" in row: if form_2 is None: form_2 = [] form_2_begin = True elif form_3 is None: form_3 = [] form_3_begin = True self.setStatusMessage("Plotting Results") if not form_1 is None: x_1, y_1 = self.get_plots_from_form("/cgi/ter_form.pl", form_1) self.plot_histo(x_1, y_1, 40, 1, 0, "Critical Angle for TER", "Incidence angle [degrees]", "Reflectivity") self.tabs_widget.setCurrentIndex(1) else: x_1 = None y_1 = None if not form_2 is None: x_2, y_2 = self.get_plots_from_form("/cgi/gid_form.pl", form_2) self.plot_histo(x_2, y_2, 60, 2, 1, "Darwin Curve ($\sigma$ Pol.)", "Scan Angle [arcsec]", "Diffracted Intensity") self.tabs_widget.setCurrentIndex(2) else: x_2 = None y_2 = None if not form_3 is None: x_3, y_3 = self.get_plots_from_form("/cgi/gid_form.pl", form_3) self.plot_histo(x_3, y_3, 80, 3, 2, "Darwin Curve ($\pi$ Pol.)", "Scan Angle [arcsec]", "Diffracted Intensity") self.tabs_widget.setCurrentIndex(3) else: x_3 = None y_3 = None return [x_1, y_1], [x_2, y_2], [x_3, y_3]
def setHtml(self, html, baseUrl): # A hack to prevent WebEngine from stealing the focus self.setEnabled(False) QWebEngineView.setHtml(self, html, baseUrl) self.setEnabled(True)
import os from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.Qt import QUrl from PyQt5 import QtWidgets, QtGui widget = QWebEngineView() fake_url = QUrl.fromLocalFile(os.path.abspath("seamless.html")) widget.setWindowTitle(PINS.title.get().data) reloadAction = QtWidgets.QAction(QtGui.QIcon('exit.png'), '&Reload', widget) reloadAction.setShortcut('F5') reloadAction.setStatusTip('Reload') reloadAction.triggered.connect(widget.reload) widget.addAction(reloadAction) widget.setHtml(PINS.val.get().data, fake_url) widget.show()
class DrrrWindow(ShadowsWindow): def __init__(self): super(DrrrWindow, self).__init__() self.setWindowTitle("Drrr Chat Room") self.setWindowIcon(QIcon('./img/drrr.ico')) # w = WebView() # w.show() self.getSetting() self.WebView = QWebEngineView() # self.WebView.load(QUrl("file:///E:/Project/DrrrPC/img/index.html")) self.WebView.setZoomFactor(0.8) # 设置加载网页,和网页加载完成以及加载过程信号与槽函数关联 self.WebView.loadStarted.connect(self.loadStarted) self.WebView.loadFinished.connect(self.loadFinished) self.WebView.loadProgress.connect(self.loading) self.cookieJar = QNetworkCookieJar() # self.WebView.page().networkAccessManager().setCookieJar(self.cookieJar) # self.WebView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) # self.WebView.page().linkClicked.connect(self.linkClicked) # self.WebView.page().contentsChanged.connect(self.contentsChanged) # self.WebView.page().networkAccessManager().setHeader(QNetworkRequest.ContentTypeHeader, QVariant("text/html; charset=GBK")) # 重定义QWebEnginePage中javaScriptAlert等函数 self.WebView.page().javaScriptAlert = self._javascript_alert self.WebView.page().javaScriptConsoleMessage = self._javascript_console_message self.WebView.page().javaScriptConfirm = self._javascript_confirm self.WebView.page().javaScriptPrompt = self._javascript_prompt # NetworkAccessManager # self.NetworkAccessManager = QNetworkAccessManager() # self.WebView.page().setNetworkAccessManager(self.NetworkAccessManager) # self.NetworkAccessManager.finished.connect(self.NetworkAccessManagerReplyFinished) # self.NetworkAccessManager.get(QNetworkRequest(QUrl("http://www.baidu.com"))) # self.old_manager = self.WebView.page().networkAccessManager() # self.new_manager = NetworkAccessManager(self.old_manager) # self.WebView.page().setNetworkAccessManager(self.new_manager) self.titlebar = titleBar() self.statusBar = StatusWindow() # 中心窗口布局 self.contentLayout = QVBoxLayout() self.contentWidget = QWidget() self.contentWidget.gridLayout = QtWidgets.QGridLayout(self.contentWidget) self.contentWidget.gridLayout.addLayout(self.contentLayout, 0, 0, 1, 1) self.contentLayout.addWidget(self.WebView) self.contentWidget.gridLayout.setContentsMargins(0,0,0,0) self.contentLayout.setContentsMargins(1,0,1,0) self.contentWidget.setStyleSheet(""" border-left: 1px solid black; border-right: 1px solid black; """) # self.titlebar.titlebarBotton = QPushButton(self.titlebar) # self.titlebar.titlebarBotton.setText('Push ME') # self.titlebar.titlebarBotton.clicked.connect(self.getData) self.main_layout = QVBoxLayout() self.main_layout.addWidget(self.titlebar) self.main_layout.addWidget(self.contentWidget) self.main_layout.addWidget(self.statusBar) self.main_layout.setSpacing(0) # 窗口属性 self.setWindowFlags(Qt.Widget | QtCore.Qt.FramelessWindowHint) self.setAttribute(Qt.WA_NoSystemBackground, True) self.setAttribute(QtCore.Qt.WA_TranslucentBackground,True) self.widget = QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(self.main_layout) self.widget.setMouseTracking(True) # self.resize(500,650) self.resize(650,650) # self.setMaximumHeight(660) self.center() # 将三个按钮点击信号与相关槽函数相关联 self.titlebar.min_button.clicked.connect(self.hideIt) self.titlebar.max_button.clicked.connect(self.MaxAndNormal) self.titlebar.close_button.clicked.connect(self.closeIt) # 状态栏进度条:将LoadProgress信号与loading槽函数相关联 self.WebView.loadProgress.connect(self.loading) # notice sound # self.player = self.WebView.setHtml(WaitingHTML) self.show() self.WebView.setStyleSheet(""" QWebView { background-color:black } QWebView::QScrollBar:Vertical { background-color:black } """) self.WebView.load(QUrl("http://drrr.com/")) def center(self,screenNum=0): '''多屏居中支持''' self.desktop = QApplication.desktop() screen = self.desktop.availableGeometry(screenNum) size = self.geometry() self.normalGeometry2 = QtCore.QRect((screen.width()-size.width())/2+screen.left(), (screen.height()-size.height())/2, size.width(),size.height()) self.setGeometry((screen.width()-size.width())/2+screen.left(), (screen.height()-size.height())/2, size.width(),size.height()) def keyPressEvent(self,event): # F11全屏切换 if event.key()==QtCore.Qt.Key_F11: self.MaxAndNormal() if event.key()==QtCore.Qt.Key_F4: self.WebView.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) def getData(self): # print self.bbb == None # print str(self.bbb) pass @QtCore.pyqtSlot(str) def play(self,content): # ["bubble","userin","userout"] print (content) QtMultimedia.QSound.play("./img/"+content+".wav") def readyRead(self): pass # print self.NetworkAccessManager.readAll() def NetworkAccessManagerReplyFinished(self,response): # NO USE # print response.readAll() # print response.header(QNetworkRequest.ContentTypeHeader) # print response.url() # self.bbb = response.readAll() response.deleteLater() def contentsChanged(self): # print 'contentsChanged' pass def _javascript_alert(self, webframe, message): print ('_javascript_alert') def _javascript_console_message(self, message, line, sourceid): print ("_javascript_console_message") def _javascript_confirm(self, webframe, message): print ("_javascript_confirm") return QWebPage.javaScriptConfirm(self.WebView.page(), webframe, message) def _javascript_prompt(self, webframe, message, defaultvalue, result): print ("_javascript_prompt") def linkClicked(self,url): print (url) # 获取ini格式的设置 def getSetting(self): '''获取应用设置''' self.settings = QtCore.QSettings("DrrrChatRoom.ini", QtCore.QSettings.IniFormat) def loadStarted(self): if 'http://drrr.com/' == str(self.WebView.url().toString()): frame = self.WebView.page() # name = frame.findFirstElement("input#form-name.home-name-input") # username = name.evaluateJavaScript("this.value") # print (username) # language = frame.findFirstElement("#form-language-select") # language = language.evaluateJavaScript("this.value") # print (language) frame.runJavaScript(""" var iconFun = function(){ var elementsLI = document.getElementsByTagName('li') var length = document.getElementsByTagName('li').length; for(var i = 0; i < length ; ++i){ if(elementsLI[i].getElementsByTagName('div')[0].className.indexOf("active")>=0){ var icon = elementsLI[i].getElementsByTagName('input')[0].value; } } return icon }; """) icon = frame.runJavaScript("""iconFun()""") print (icon) # if username:self.settings.setValue('username',username) # if language:self.settings.setValue("language",language) # if icon: # # self.settings.setValue("icon",icon) # pass # else: # if self.settings.value('icon', None): # icon = self.settings.value('icon',None) # frame.findFirstElement('input[value="'+icon+'"]').evaluateJavaScript("this.click()") # if "http://drrr.com/room/?ajax=1" in str(self.WebView.url().toString()): # print "quit room" pass print ('requestedUrl:' + self.WebView.url().toString()) def loadFinished(self, flag): self.statusBar.status.setText(u"Connected") # http://drrr.com/ if 'http://drrr.com/' == str(self.WebView.url().toString()): frame = self.WebView.page() # name = frame.findFirstElement("input#form-name.home-name-input") # if self.settings.value('username', None): # name.setAttribute('value',self.settings.value('username', None)) # language = frame.findFirstElement("#form-language-select") # if self.settings.value('language', None): # language.evaluateJavaScript(''' # sel = document.getElementById("form-language-select"); # for(var i = 0, j = sel.options.length; i < j; ++i) { # if(sel.options[i].value === "'''+self.settings.value('language', "zh-CN")+'''") { # sel.selectedIndex = i; # break; # } # } # ''') # # language.setAttribute('value',self.settings.value('language', None)) # if self.settings.value('icon', None): # icon = self.settings.value('icon',None) # frame.findFirstElement('input[value="'+icon+'"]').evaluateJavaScript("this.click()") # http://drrr.com/create_room/ if 'http://drrr.com/room/' in str(self.WebView.url().toString()): frame = self.WebView.page() # frame.addToJavaScriptWindowObject("drrrWindow", self) frame.runJavaScript(''' var volumeFun = function(b){ return b } ''') frame.runJavaScript(''' var playFun = function(a){ this.volume = volumeFun; drrrWindow.play(a); return this }; ''') frame.runJavaScript('''sound.play = playFun''') def loading(self, percent): self.statusBar.status.setText("Loading %d%%" % percent) def quit(self): sys.exit(0) # QtCore.QCoreApplication.instance().quit() def closeIt(self): self.animation = QtCore.QPropertyAnimation(self,"windowOpacity") self.animation.finished.connect(QtCore.QCoreApplication.instance().quit) self.animation.finished.connect(self.quit) self.animation.setDuration(300) self.animation.setStartValue(1) self.animation.setEndValue(0) self.animation.start() def hideIt(self): self.animation = QtCore.QPropertyAnimation(self,"windowOpacity") self.animation.finished.connect(self.showMinimized2) self.animation.setDuration(300) self.animation.setStartValue(1) self.animation.setEndValue(0) self.animation.start() def leaveEvent(self,event): self.setCursor(QtCore.Qt.ArrowCursor) def keyPressEvent(self,event): # F11全屏切换 if event.key()==QtCore.Qt.Key_F11: self.MaxAndNormal2() def MaxAndNormal2(self): '''全屏与正常大小间切换函数''' if self.showNormal3(): self.showFullScreen3() self.titlebar.hide() self.statusBar.hide() else: self.titlebar.show() self.statusBar.show() def MaxAndNormal(self): '''最大化与正常大小间切换函数''' if self.showNormal3(): self.showFullScreen3() #定义DrrrWindow显示动画 # def showEvent(self,event): # self.animation = QtCore.QPropertyAnimation(self,"windowOpacity") # self.animation.setDuration(300) # self.animation.setStartValue(0) # self.animation.setEndValue(1) # self.animation.start() def showNormal2(self): self.showNormal() self.animationEndFlag = 1 # 动画停止 def showNormal3(self): if self.isFullScreen(): self.main_layout.setContentsMargins(10,7,10,7) self.animation = QtCore.QPropertyAnimation(self,"geometry") self.animation.setDuration(180) self.animation.setEndValue(self.normalGeometry2) self.animation.setStartValue(self.desktop.availableGeometry(self.desktop.screenNumber(self.widget))) self.animation.finished.connect(self.showNormal2) self.animationEndFlag = 0 self.animation.start() return 0 return 1 def showFullScreen2(self): self.animationEndFlag = 1 # 动画停止 self.showFullScreen() def showFullScreen3(self): if not self.isFullScreen(): self.main_layout.setContentsMargins(0,0,0,0) self.animation = QtCore.QPropertyAnimation(self,"geometry") self.animation.setDuration(180) self.animation.setStartValue(self.geometry()) self.animation.setEndValue(self.desktop.availableGeometry(self.desktop.screenNumber(self.widget))) self.animation.finished.connect(self.showFullScreen2) self.animationEndFlag = 0 self.animation.start() def showMinimized2(self): self.setWindowOpacity(1) self.showMinimized()
view.setHtml(''' <html> <head> <title>A Demo Page</title> <script language="javascript"> // Completes the full-name control and // shows the submit button function completeAndReturnName() { var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var full = fname + ' ' + lname; document.getElementById('fullname').value = full; document.getElementById('submit-btn').style.display = 'block'; return full; } </script> </head> <body> <form> <label for="fname">First name:</label> <input type="text" name="fname" id="fname"></input> <br /> <label for="lname">Last name:</label> <input type="text" name="lname" id="lname"></input> <br /> <label for="fullname">Full name:</label> <input disabled type="text" name="fullname" id="fullname"></input> <br /> <input style="display: none;" type="submit" id="submit-btn"></input> </form> </body> </html> ''')
QWebView with static html """ import sys from PyQt5.QtWidgets import QApplication, QWidget #from PyQt5.QtWebKitWidgets import QWebView from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView from PyQt5.QtCore import QUrl html = '''<html> <head> <title>A Sample Page</title> </head> <body> <h1>Hello, World!</h1> <hr /> <p>Simple Paragraph.</> </body> </html>''' if __name__ == '__main__': app = QApplication(sys.argv) w = QWebView() w.resize(800, 600) w.move(300, 300) w.setWindowTitle('Simple Plot') w.setHtml(html) w.show() sys.exit(app.exec_())
class X0p(XrayServerWidget): name = "X0h Search" description = "X0p" icon = "icons/x0p.png" maintainer = "Luca Rebuffi" maintainer_email = "luca.rebuffi(@at@)elettra.eu" priority = 2 category = "X0h" keywords = ["data", "file", "load", "read"] want_main_area = 1 xway = Setting(2) wave = Setting(0.0) line = Setting("Cu-Ka1") code = Setting("Silicon") hkl11 = Setting(-5) hkl12 = Setting(-5) hkl13 = Setting(-5) hkl21 = Setting(5) hkl22 = Setting(5) hkl23 = Setting(5) qb1 = Setting(0.0) qb2 = Setting(90.0) prcmin = Setting(0.0) df1df2 = Setting(1) base1 = Setting(1) base2 = Setting(0) base3 = Setting(0) modesearch = Setting(0) q1 = Setting(0.0) q2 = Setting(180.0) def __init__(self): super().__init__() left_box_1 = oasysgui.widgetBox(self.controlArea, "X0h-Search Request Form", addSpace=True, orientation="vertical", width=400, height=630) left_box_2 = oasysgui.widgetBox(left_box_1, "X-rays", addSpace=True, orientation="horizontal", width=380, height=110) left_box_2_1 = oasysgui.widgetBox(left_box_2, "", addSpace=True, orientation="vertical", width=150, height=110) gui.radioButtons(left_box_2_1, self, "xway", ["Wavelength (Å)", "Energy (keV)", "Characteristic line"], callback=self.set_xway ) self.box_wave = oasysgui.widgetBox(left_box_2, "", addSpace=True, orientation="vertical", width=190) gui.separator(self.box_wave, height=10) oasysgui.lineEdit(self.box_wave, self, "wave", label="", labelWidth=0, addSpace=False, valueType=float, orientation="horizontal") self.box_line = oasysgui.widgetBox(left_box_2, "", addSpace=True, orientation="horizontal", width=190, height=110) gui.separator(self.box_line, height=120) XRayServerGui.combobox_text(self.box_line, self, "line", label="", labelWidth=0, items=self.get_lines(), sendSelectedValue=True, orientation="horizontal", selectedValue=self.line) button = gui.button( self.box_line, self, "?", callback=self.help_lines) button.setFixedWidth(15) self.set_xway() left_box_3 = oasysgui.widgetBox(left_box_1, "Crystal", addSpace=True, orientation="horizontal", width=380, height=60) self.box_crystal = oasysgui.widgetBox(left_box_3, "", addSpace=True, orientation="horizontal", width=210) XRayServerGui.combobox_text(self.box_crystal, self, "code", label="", labelWidth=0, items=self.get_crystals(), sendSelectedValue=True, orientation="horizontal", selectedValue=self.code) button = gui.button( self.box_crystal, self, "?", callback=self.help_crystals) button.setFixedWidth(15) left_box_4 = oasysgui.widgetBox(left_box_1, "Bragg Planes Range", addSpace=True, orientation="horizontal", width=380, height=60) oasysgui.lineEdit(left_box_4, self, "hkl11", label="From", labelWidth=50, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "hkl12", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "hkl13", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "hkl21", label=" To", labelWidth=50, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "hkl22", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_4, self, "hkl23", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") left_box_7 = oasysgui.widgetBox(left_box_1, "Bragg Angle Range", addSpace=True, orientation="horizontal", width=380, height=60) oasysgui.lineEdit(left_box_7, self, "qb1", label="From", labelWidth=80, addSpace=False, valueType=float, orientation="horizontal") oasysgui.lineEdit(left_box_7, self, "qb2", label=" To", labelWidth=80, addSpace=False, valueType=float, orientation="horizontal") tab_central = oasysgui.tabWidget(left_box_1) tab_1 = oasysgui.createTabPage(tab_central, "Intensity Control") tab_2 = oasysgui.createTabPage(tab_central, "Find only Bragg planes making certain angles to the surface") left_box_5 = oasysgui.widgetBox(tab_1, "", addSpace=True, orientation="vertical", width=370, height=250) gui.separator(left_box_5) oasysgui.lineEdit(left_box_5, self, "prcmin", label="Minimum |xh/x0| (%)", labelWidth=250, addSpace=False, valueType=float, orientation="horizontal") left_box_5_1 = oasysgui.widgetBox(left_box_5, "Database Options for dispersion corrections df1, df2", addSpace=True, orientation="vertical", width=370, height=185) gui.radioButtons(left_box_5_1, self, "df1df2", ["Auto (Henke at low energy, X0h at mid, Brennan-Cowan\nat high)", "Use X0h data (5-25 keV or 0.5-2.5 A), recommended for\nBragg diffraction", "Use Henke data (0.01-30 keV or 0.4-1200 A),\nrecommended for soft x-rays", "Use Brennan-Cowan data (0.03-700 keV or 0.02-400 A)"]) left_box_6 = oasysgui.widgetBox(tab_2, "", addSpace=True, orientation="vertical", width=370, height=255) gui.separator(left_box_6) left_box_6_1 = oasysgui.widgetBox(left_box_6, "", addSpace=False, orientation="horizontal", width=370, height=30) oasysgui.lineEdit(left_box_6_1, self, "base1", label="Surface Plane Indices", labelWidth=200, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_6_1, self, "base2", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") oasysgui.lineEdit(left_box_6_1, self, "base3", label=" ", labelWidth=1, addSpace=False, valueType=int, orientation="horizontal") gui.radioButtons(left_box_6, self, "modesearch", ["Planes make angles from Theta1 to Theta2", "Planes make angles from Theta1 to (Bragg_Angle - Theta2)", "Planes make angles from (Bragg_Angle - Theta1)\nto (Bragg_Angle - Theta2)"]) gui.separator(left_box_6, height=10) left_box_6_2 = oasysgui.widgetBox(left_box_6, "", addSpace=True, orientation="horizontal", width=370, height=30) oasysgui.lineEdit(left_box_6_2, self, "q1", label="Theta1", labelWidth=80, addSpace=False, valueType=float, orientation="horizontal") oasysgui.lineEdit(left_box_6_2, self, "q2", label=" Theta2", labelWidth=80, addSpace=False, valueType=float, orientation="horizontal") button = gui.button(self.controlArea, self, "Find Planes!", callback=self.submit) button.setFixedHeight(30) gui.rubber(self.controlArea) self.tabs_widget = oasysgui.tabWidget(self.mainArea) self.tab_output = oasysgui.createTabPage(self.tabs_widget, "X-ray Server Ouput") self.x0h_output = QWebView(self.tab_output) self.tab_output.layout().addWidget(self.x0h_output) self.x0h_output.setFixedHeight(640) self.x0h_output.setFixedWidth(740) def set_xway(self): self.box_wave.setVisible(self.xway!=2) self.box_line.setVisible(self.xway==2) def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") self.checkFields() parameters = {} parameters.update({"xway" : str(self.xway + 1)}) parameters.update({"wave" : str(self.wave)}) parameters.update({"line" : self.line}) parameters.update({"code" : self.code}) parameters.update({"hkl11" : str(self.hkl11)}) parameters.update({"hkl12" : str(self.hkl12)}) parameters.update({"hkl13" : str(self.hkl13)}) parameters.update({"hkl21" : str(self.hkl21)}) parameters.update({"hkl22" : str(self.hkl22)}) parameters.update({"hkl23" : str(self.hkl23)}) parameters.update({"qb1" : str(self.qb1)}) parameters.update({"qb2" : str(self.qb2)}) parameters.update({"prcmin" : str(self.prcmin)}) parameters.update({"df1df2" : self.decode_df1df2()}) parameters.update({"base1" : str(self.base1)}) parameters.update({"base2" : str(self.base2)}) parameters.update({"base3" : str(self.base3)}) parameters.update({"modesearch" : self.decode_modesearch()}) parameters.update({"q1" : str(self.q1)}) parameters.update({"q2" : str(self.q2)}) try: response = HttpManager.send_xray_server_request_GET(APPLICATION, parameters) response = response.split("<hr>")[0] + "\n </body></html>" temp_1, temp_2 = response.split("style.css") output = temp_1 + XRAY_SERVER_URL + "/style.css" + temp_2 response = response.split("<td><img src=\"images/x.gif\" width=31 height=32 border=0></td>")[0] + "</tr></tr></body></html>" self.x0h_output.setHtml(response) except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: ShowTextDialog.show_text("Error", 'Error Occurred.\nReason: ' + str(e), parent=self) self.setStatusMessage("") self.progressBarFinished() def getLeftPartWidth(self): return 415 def checkFields(self): pass def decode_df1df2(self): if self.df1df2 == 0: return "-1" elif self.df1df2 == 1: return "0" elif self.df1df2 == 2: return "2" elif self.df1df2 == 3: return "4" def decode_modesearch(self): if self.modesearch == 0: return "3" elif self.modesearch == 1: return "2" elif self.modesearch == 2: return "1"
class X0h(XrayServerWidget): name = "X0h" description = "X0h" icon = "icons/x0h.png" maintainer = "Luca Rebuffi" maintainer_email = "luca.rebuffi(@at@)elettra.eu" priority = 1 category = "X0h" keywords = ["data", "file", "load", "read"] want_main_area = 1 outputs = [{"name": "xrayserver_data", "type": DataExchangeObject, "doc": "xrayserver_data", "id": "xrayserver_data"}, ] def __init__(self): super().__init__() left_box_1 = oasysgui.widgetBox(self.controlArea, "X0h Request Form", addSpace=True, orientation="vertical", width=610, height=640) html = self.clear_input_form(HttpManager.send_xray_server_direct_request("/cgi/www_form.exe?template=x0h_form.htm")) self.x0h_input = QWebView(left_box_1) self.x0h_input.setHtml(html) left_box_1.layout().addWidget(self.x0h_input) self.x0h_input.setFixedHeight(540) self.x0h_input.setFixedWidth(590) button = gui.button(self.controlArea, self, "Get X0h!", callback=self.submit) button.setFixedHeight(30) gui.rubber(self.controlArea) self.tabs = [] self.tabs_widget = oasysgui.tabWidget(self.mainArea) self.initializeTabs() self.x0h_output = QWebView(self.tabs[0]) self.tabs[0].layout().addWidget(self.x0h_output) self.x0h_output.setFixedHeight(630) self.x0h_output.setFixedWidth(740) def clear_input_form(self, html): temp_1 = html.split("<body onload=\"setOnloads()\">")[0] temp_2 = html.split("<table cellspacing=0 cellpadding=0 border=0 bgcolor=\"#c1c1c1\"><tr><td>")[1] html = temp_1 + "<body>\n<table cellspacing=0 cellpadding=0 border=0 bgcolor=\"#c1c1c1\"><tr><td>\n" + temp_2 html = html.split("<input type=SUBMIT value=\"Get X0h!\"><input type=RESET> <br>")[0] html += "\n<input type=SUBMIT style=\"display: none;\" id=\"submit-btn\"><input type=RESET style=\"display: none;\" id=\"reset-btn\"> <br>" html += "\n</form>" html += "\n</td></tr></table>" html += "\n</td></tr></table>" html += "\n</body>" html += "\n</html>" temp_1, temp_2 = html.split("x0h.js") html = temp_1 + XRAY_SERVER_URL + "/x0h.js" + temp_2 temp_1, temp_2 = html.split("/cgi/x0h_form.exe") html = temp_1 + XRAY_SERVER_URL + "/cgi/x0h_form.exe" + temp_2 return html def getLeftPartWidth(self): return 620 def initializeTabs(self): current_tab = self.tabs_widget.currentIndex() size = len(self.tabs) for index in range(0, size): self.tabs_widget.removeTab(size-1-index) self.tabs = [gui.createTabPage(self.tabs_widget, "X-ray Server Ouput"), gui.createTabPage(self.tabs_widget, "Critical Angle for TER"), gui.createTabPage(self.tabs_widget, "Darwin Curve (" + u"\u03C3" + " Pol.)"), gui.createTabPage(self.tabs_widget, "Darwin Curve (" + u"\u03C0" + " Pol.)"), ] for tab in self.tabs: tab.setFixedHeight(650) tab.setFixedWidth(750) self.plot_canvas = [None, None, None] self.tabs_widget.setCurrentIndex(current_tab) def js_callback(self, result): pass def _callable_1(self, html): self.original_signal = self.x0h_input.loadFinished self.x0h_input.loadFinished.connect(self.loadFinished) self.x0h_input.setHidden(True) self.x0h_input.page().runJavaScript("document.getElementById('submit-btn').click()", self.js_callback) def loadFinished(self): self.x0h_input.page().toHtml(self._callable_2) def _callable_2(self, html): try: self.x0h_input.loadFinished.disconnect() self.x0h_input.back() self.x0h_input.setHidden(False) response_1 = self.clear_response(html) response_2 = self.clear_response(html) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response_1) data0, data1, data2 = self.extract_plots(response_2) exchange_data = DataExchangeObject("XRAYSERVER", "X0H") exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content("x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content("x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + str(e)) self.tabs_widget.setCurrentIndex(0) self.setStatusMessage("") self.progressBarFinished() def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") if platform.system() == 'Darwin': self.x0h_input.page().toHtml(self._callable_1) elif platform.system() == 'Linux': doc = self.x0h_input.page().mainFrame().documentElement() submit_btn = doc.findFirst("input[id=submit-btn]") try: response = "" #response = HttpManager.send_xray_server_request_POST(APPLICATION, parameters) response = self.clear_response(response) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response) data0, data1, data2 = self.extract_plots(response) exchange_data = DataExchangeObject("XRAYSERVER", "X0H") exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content("x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content("x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) pass except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) raise e except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) raise e except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) raise e except Exception as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + str(e)) raise e self.setStatusMessage("") self.progressBarFinished() def clear_response(self, response): print(response) # remove links output = response.split("<img src=\"images/x.gif\" width=\"31\" height=\"32\" border=\"0\">")[0] + "\n</body></html>" # remove "get the curve" images output = "".join(output.split("<input type=image src=\"images/get_the_curve.gif\" border=0 width=102 height=12 alt=\"Get the reflectivity curve\">")) output = "".join(output.split("<input type=image src=\"images/get_the_curve.gif\" border=0 width=102 height=12 alt=\"Get the Bragg curve (sigma)\">")) output = "".join(output.split("<input type=image src=\"images/get_the_curve.gif\" border=0 width=102 height=12 alt=\"Get the Bragg curve (pi)\">")) # remove question mark images and links output = "".join(output.split("<a href=\"javascript:void(0)\" onClick=\"Wfloat(\'images/x0h_help_0.gif\',\'x0h_0\',740,357);\"><b>?</b></a> ")) output = "".join(output.split("<a href=\"javascript:void(0)\" onClick=\"Wfloat(\'images/x0h_help_h.gif\',\'x0h_h\',705,853);\"><b>?</b></a> ")) temp_1, temp_2 = output.split("style.css") output = temp_1 + XRAY_SERVER_URL + "/style.css" + temp_2 return output def extract_plots(self, response): form_1_begin = False form_2_begin = False form_3_begin = False form_1 = None form_2 = None form_3 = None rows = response.split("\n") for row in rows: if form_1_begin: if "<td>" in row: form_1_begin = False elif form_2_begin: if "<td>" in row: form_2_begin = False elif form_3_begin: if "<td>" in row: form_3_begin = False if form_1_begin: form_1.append(row) elif form_2_begin: form_2.append(row) elif form_3_begin: form_3.append(row) if "/cgi/ter_form.pl" in row: if form_1 is None: form_1 = [] form_1_begin = True if "/cgi/gid_form.pl" in row: if form_2 is None: form_2 = [] form_2_begin = True elif form_3 is None: form_3 = [] form_3_begin = True self.setStatusMessage("Plotting Results") if not form_1 is None: x_1, y_1 = self.get_plots_from_form("/cgi/ter_form.pl", form_1) self.plot_histo(x_1, y_1, 40, 1, 0, "Critical Angle for TER", "Incidence angle [degrees]", "Reflectivity") self.tabs_widget.setCurrentIndex(1) else: x_1 = None y_1 = None if not form_2 is None: x_2, y_2 = self.get_plots_from_form("/cgi/gid_form.pl", form_2) self.plot_histo(x_2, y_2, 60, 2, 1, "Darwin Curve ($\sigma$ Pol.)", "Scan Angle [arcsec]", "Diffracted Intensity") self.tabs_widget.setCurrentIndex(2) else: x_2 = None y_2 = None if not form_3 is None: x_3, y_3 = self.get_plots_from_form("/cgi/gid_form.pl", form_3) self.plot_histo(x_3, y_3, 80, 3, 2, "Darwin Curve ($\pi$ Pol.)", "Scan Angle [arcsec]", "Diffracted Intensity") self.tabs_widget.setCurrentIndex(3) else: x_3 = None y_3 = None return [x_1, y_1], [x_2, y_2], [x_3, y_3]