def __init__(self, parent=None): super().__init__(parent) self.port = None view = QWebEngineView() settings = view.settings() settings.setAttribute(QWebEngineSettings.JavascriptEnabled, True) self._set_widget(view)
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 __init__(self, inspector=False): QWebEngineView.__init__(self) self.__inspector = None self.__contextMenuEvent = self.contextMenuEvent self.set_inspector(inspector)
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)
def __init__(self, html): self.html = None self.app = QApplication(sys.argv) QWebEngineView.__init__(self) self.loadFinished.connect(self._loadFinished) self.setHtml(html) while self.html is None: self.app.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers | QEventLoop.WaitForMoreEvents) self.app.quit()
def showDocumentation(self): if self._documentation is None: doc = QWebView(self) doc.load(QUrl("doc/html/index.html")) self._documentation = QDockWidget("Documentation", self) self._documentation.setWidget(doc) self._documentation.closeEvent = lambda _: self.hide_documentation() self.addDockWidget(Qt.LeftDockWidgetArea, self._documentation)
def test1(): app = QApplication(sys.argv) window = QMainWindow() window.setWindowTitle('PyQt Demo') window.setGeometry(320, 180, 960, 540) view = QWebEngineView() # view.load(QUrl('http://leafletjs.com/')) view.load(QUrl('https://www.raspberrypi.org/')) window.setCentralWidget(view) window.show() sys.exit(app.exec_())
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 Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.qwebengine = QWebEngineView(self.centralwidget) self.qwebengine.setGeometry(QtCore.QRect(10, 30, 451, 321)) self.qwebengine.setAutoFillBackground(False) self.qwebengine.setStyleSheet("background-color: rgb(170, 170, 127);") self.qwebengine.setObjectName("qwebengine") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
def mainPyQt5(): # 必要なモジュールのimport from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEngineView url = "https://github.com/tody411/PyIntroduction" app = QApplication(sys.argv) # QWebEngineViewによるWebページ表示 browser = QWebEngineView() browser.load(QUrl(url)) browser.show() sys.exit(app.exec_())
def obtain_code(self, url=SandBoxURL, state=""): """Obtain an application code :param url: A Base url for requests, optional :param state: Additional if to be returned, optional """ self.app = QApplication([]) payload = { "response_type": "code", "client_id": client_id, "redirect_uri": oauth2_redirect, "scope": scope, "state": state, } res = requests.get(url + "/v3/auth/auth", params=payload, headers=headers) self.webview = QMainWindow() self.engine = QWebEngineView() self.engine.setUrl(QUrl(res.url)) self.engine.urlChanged.connect(self.parse_code) self.webview.setCentralWidget(self.engine) self.webview.show() self.app.exec_()
def initUI(self, windowType): self.setStyleSheet(""" #cmdLine, #bar, #bar > * { border: 0px; background: #070707; font-family: "Pro Font"; font-size: 10px; color: white; min-height: 17px } """) self.setWindowTitle('shower') self.setAttribute(Qt.WA_DeleteOnClose) vbox = QVBoxLayout() self.setLayout(vbox) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) bar = QWidget() bar.setObjectName('bar') hbox = QHBoxLayout() hbox.setContentsMargins(2, 0, 0, 0) hbox.setSpacing(0) bar.setLayout(hbox) vbox.addWidget(bar) self.urlLabel = QLabel() self.urlLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) self.urlLabel.setTextFormat(Qt.RichText) hbox.addWidget(self.urlLabel) hbox.setStretch(0, 1) self.progressLabel = QLabel() self.progressLabel.setTextFormat(Qt.RichText) hbox.addWidget(self.progressLabel) self.cmdLine = QLineEdit() self.cmdLine.setObjectName('cmdLine') vbox.addWidget(self.cmdLine) self.webView = QWebEngineView() self.webView.setPage(BrowserPage(self)) vbox.addWidget(self.webView) self.cmdLine.returnPressed.connect(self.handleCommand) self.webView.page().linkHovered.connect(self.onLinkHovered) self.webView.page().urlChanged.connect(self.urlChanged) self.webView.page().titleChanged.connect(self.onTitleChanged) self.webView.page().loadProgress.connect(self.onLoadProgress) self.webView.page().loadStarted.connect(self.onLoadStarted) self.webView.page().loadFinished.connect(self.onLoadFinished) self.urlChanged.connect(self.onUrlChanged) self.addShortcut("Alt+Left", lambda: self.webView.page().triggerAction(QWebEnginePage.Back)) self.addShortcut("Alt+Right", lambda: self.webView.page().triggerAction(QWebEnginePage.Forward)) self.addShortcut("Ctrl+R", lambda: self.webView.page().triggerAction(QWebEnginePage.Reload)) self.addShortcut("Ctrl+Shift+R", lambda: self.webView.page().triggerAction(QWebEnginePage.ReloadAndBypassCache)) self.stopShortcut = self.addShortcut("Esc", lambda: self.webView.page().triggerAction(QWebEnginePage.Stop)) self.addShortcut("Ctrl+W", lambda: self.close()) self.addShortcut("Ctrl+L", lambda: self.beginEnteringCommand(None)) self.addShortcut("Ctrl+K", lambda: self.beginEnteringCommand('? ')) self.addShortcut("Ctrl+/", lambda: self.beginEnteringCommand('/ ')) self.addShortcut("Ctrl+U", lambda: self.toggleSource())
def __init__(self, tab, editorPositionToSourceLineFunc, sourceLineToEditorPositionFunc): QWebEngineView.__init__(self, parent=tab) webPage = ReTextWebEnginePage(self, tab) self.setPage(webPage) self.syncscroll = SyncScroll(webPage, editorPositionToSourceLineFunc, sourceLineToEditorPositionFunc) ReTextWebPreview.__init__(self, tab.editBox) settings = self.settings() settings.setAttribute(QWebEngineSettings.LocalContentCanAccessFileUrls, False)
class WebViewPlus(QWebEngineView): """ WebView 커스터마이징 - inspector 추가 - jsconsole 로그 추가 - webview에서 document로 이벤트를 발생함. """ def __init__(self): super().__init__() self.setPage(WebPagePlus()) #Keyboard shortcuts self.shortcut = {} #F5 - Page reloading self.shortcut['F5'] = QShortcut(self) self.shortcut['F5'].setKey(Qt.Key_F5) self.shortcut['F5'].activated.connect(self.reload) #Devtool setup def debuggingMode(self, port): #F12 - Development tool self.shortcut['F12'] = QShortcut(self) self.shortcut['F12'].setContext(Qt.ApplicationShortcut) self.shortcut['F12'].setKey(Qt.Key_F12) self.shortcut['F12'].activated.connect(self._toggleDevTool) self.devTool = QDialog(self) self.devTool.setWindowTitle("Development Tool") self.devTool.resize(950, 400) self.devView = QWebEngineView() self.devView.setPage(QWebEnginePage(self.devView)) self.devView.load(QUrl("http://localhost:"+port)) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.devView) self.devTool.setLayout(layout) def _toggleDevTool(self): """ F12키를 다시 누르면 "개발자 도구"가 사라짐 """ self.devTool.setVisible(not self.devTool.isVisible())
class MainWidow(QWidget): def __init__(self): super().__init__() self.view=QWebEngineView() self.myprofile=self.getProfile() self.page=QWebEnginePage(self.myprofile,None) # self.channel=QWebChannel() # self.myobject=myObject() # self.channel.registerObject("xdpy", self.myobject) # self.page.setWebChannel(self.channel) self.page.settings().AllowRunningInsecureContent=True; self.page.settings().JavascriptEnabled=True; self.view.page=self.page self.url=QUrl("") self.view.page.load(self.url) self.view.show() self.view.settings().JavascriptEnabled=True def js_callback(self,result): print("js_callback:{}".format(result)) def injectJS(self,sourceCode,name): script = QWebEngineScript(); script.setSourceCode(sourceCode) script.setName(name) script.setInjectionPoint(QWebEngineScript.DocumentCreation) script.setWorldId(QWebEngineScript.MainWorld) script.setRunsOnSubFrames(True) self.view.page.scripts().insert(script) self.page.scripts().insert(script) def getProfile(self): profile=QWebEngineProfile("myProfile") profile.cachePath="/home/yyk/Desktop/cache" jsFile = constants.QTWEBCHANNELJS_FILE with open(jsFile, encoding="UTF-8") as file: js = file.read() script = QWebEngineScript(); script.setSourceCode(js) script.setName('qwebchannel.js') script.setInjectionPoint(QWebEngineScript.DocumentCreation) script.setWorldId(QWebEngineScript.MainWorld) script.setRunsOnSubFrames(False) profile.scripts().insert(script) return profile
def test(): app = QApplication(sys.argv) window = QMainWindow() window.setWindowTitle('PyQt Demo') window.setGeometry(320, 180, 960, 540) webView = QWebEngineView() # webView.settings().setAttribute(QWebEngineSettings.) # webView.javaScriptConsoleMessage # webView.load(QUrl('https://www.baidu.com')) webView.load(QUrl('http://192.168.1.217:8088')) # webView.load(QUrl('http://192.168.1.217:8088/groundcontrol/test_console.html')) # webView.load(QUrl('https://www.raspberrypi.org/')) # webView.load(QUrl('http://www.oschina.net')) # webView.load(QUrl('https://github.com/')) # webView.load(QUrl('http://127.0.0.1:8088')) window.setCentralWidget(webView) window.show() sys.exit(app.exec_())
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 WebKitFrame(qw.QFrame): def __init__(self, url=None, parent=None): if use_pyqt5: try: from PyQt5.QtWebEngineWidgets import QWebEngineView as WebView except (ImportError): from PyQt5.QtWebKitWidgets import QWebView as WebView else: from PyQt4.QtWebKit import QWebView as WebView qw.QFrame.__init__(self, parent) layout = qw.QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.setLayout(layout) self.web_widget = WebView() layout.addWidget(self.web_widget, 0, 0) if url: self.web_widget.load(qc.QUrl(url))
def __init__(self): self.debug=1 self.app = QApplication(sys.argv) self.desktop= QApplication.desktop() self.web = QWebEngineView() self.icon = QIcon(ICON) #self.web.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.web.titleChanged.connect(self.title_changed) self.web.iconUrlChanged.connect(self.icon_changed) self.web.page().windowCloseRequested.connect(self.close_window) self.web.page().geometryChangeRequested.connect(self.set_geometry)
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()
def debuggingMode(self, port): #F12 - Development tool self.shortcut['F12'] = QShortcut(self) self.shortcut['F12'].setContext(Qt.ApplicationShortcut) self.shortcut['F12'].setKey(Qt.Key_F12) self.shortcut['F12'].activated.connect(self._toggleDevTool) self.devTool = QDialog(self) self.devTool.setWindowTitle("Development Tool") self.devTool.resize(950, 400) self.devView = QWebEngineView() self.devView.setPage(QWebEnginePage(self.devView)) self.devView.load(QUrl("http://localhost:"+port)) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.devView) self.devTool.setLayout(layout)
def __init__(self): super().__init__() self.view=QWebEngineView() self.myprofile=self.getProfile() self.page=QWebEnginePage(self.myprofile,None) # self.channel=QWebChannel() # self.myobject=myObject() # self.channel.registerObject("xdpy", self.myobject) # self.page.setWebChannel(self.channel) self.page.settings().AllowRunningInsecureContent=True; self.page.settings().JavascriptEnabled=True; self.view.page=self.page self.url=QUrl("") self.view.page.load(self.url) self.view.show() self.view.settings().JavascriptEnabled=True
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
if self._last_reload_at is not None and monotonic( ) - self._last_reload_at < 2: self.render_process_failed.emit() prints('The Qt WebEngine Render process crashed too often') else: self._last_reload_at = monotonic() self.render_process_restarted.emit() prints('Restarting Qt WebEngine') if __name__ == '__main__': from calibre.gui2 import Application from calibre.gui2.tweak_book.preview import WebPage from PyQt5.Qt import QMainWindow app = Application([]) view = QWebEngineView() page = WebPage(view) view.setPage(page) w = QMainWindow() w.setCentralWidget(view) class Test(Bridge): s1 = from_js(object) j1 = to_js() t = Test(view.page()) t.s1.connect(print) w.show() view.setHtml(''' <p>hello</p> ''')
def cal1(self): self.num7 = QPushButton("7", self) self.num7.setGeometry(250, 250, 100, 50) self.num8 = QPushButton("8", self) self.num8.setGeometry(350, 250, 100, 50) self.num9 = QPushButton("9", self) self.num9.setGeometry(450, 250, 100, 50) self.num4 = QPushButton("4", self) self.num4.setGeometry(250, 300, 100, 50) self.num5 = QPushButton("5", self) self.num5.setGeometry(350, 300, 100, 50) self.num6 = QPushButton("6", self) self.num6.setGeometry(450, 300, 100, 50) self.num1 = QPushButton("1", self) self.num1.setGeometry(250, 350, 100, 50) self.num2 = QPushButton("2", self) self.num2.setGeometry(350, 350, 100, 50) self.num3 = QPushButton("3", self) self.num3.setGeometry(450, 350, 100, 50) self.num0 = QPushButton("0", self) self.num0.setGeometry(250, 400, 100, 50) self.numm1 = QPushButton("Pow", self) self.numm1.setGeometry(350, 400, 100, 50) self.numm2 = QPushButton(".", self) self.numm2.setGeometry(450, 400, 100, 50) self.numm3 = QPushButton("/", self) self.numm3.setGeometry(550, 250, 100, 50) self.numm4 = QPushButton("x", self) self.numm4.setGeometry(550, 300, 100, 50) self.numm5 = QPushButton("-", self) self.numm5.setGeometry(550, 350, 100, 50) self.numm6 = QPushButton("+", self) self.numm6.setGeometry(550, 400, 100, 50) self.numm7 = QPushButton("Clear", self) self.numm7.setGeometry(250, 450, 200, 50) self.line = QLineEdit(self) self.line.setGeometry(250, 190, 100, 35) self.line1 = QLineEdit(self) self.line1.setGeometry(360, 190, 100, 35) self.line2 = QLineEdit(self) self.line2.setGeometry(500, 190, 150, 35) self.label = QLabel("=", self) self.label.move(480, 190) self.numm8 = QPushButton("Mod", self) self.numm8.setGeometry(450, 450, 200, 50) self.setWindowTitle(self.tit) self.setGeometry(self.top, self.bot, self.wid, self.hei) if self.numm6.isEnabled(): self.numm6.clicked.connect(self.addition) if self.numm5.isEnabled(): self.numm5.clicked.connect(self.sub) if self.numm4.isEnabled(): self.numm4.clicked.connect(self.mul) if self.numm3.isEnabled(): self.numm3.clicked.connect(self.div) if self.numm1.isEnabled(): self.numm1.clicked.connect(self.pow) if self.numm8.isEnabled(): self.numm8.clicked.connect(self.mod) # if self.line.isEnabled(): # if self.num0.isEnabled(): # self.line.text()==0 self.brow = QWebEngineView() noni = QToolBar("navigation") noni.setIconSize(QSize(20, 20)) self.addToolBar(noni) back = QAction(QIcon(os.path.join('back.png')), "back", self) back.setStatusTip("back to Previous Page") back.triggered.connect(self.bac1) noni.addAction(back) forward = QAction(QIcon(os.path.join('forward.png')), "Forward", self) forward.setStatusTip("back to Previous Page") forward.triggered.connect(self.brow.forward) noni.addAction(forward)
</body> </html> ''' # The next two lines are a workaround to fix an issue with QWebEngineView (see https://github.com/ContinuumIO/anaconda-issues/issues/9199#issuecomment-383842265) import ctypes ctypes.CDLL("libGL.so.1", mode=ctypes.RTLD_GLOBAL) import sys from PyQt5.QtCore import * from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) # Setting "/" as the base_url may be a bad idea : JS script can access any (readable) file of the system... # It's probably much better to isolate external files in a dedicated directory (e.g. /tmp/...) as everybody do for webservers (/var/www/html) base_url = QUrl.fromLocalFile("/") web = QWebEngineView() web.setHtml(HTML, base_url) web.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) QWebEngineView.__init__(self) self.ui = winForm1() self.ui.setupUi(self)
class DaLuRenWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.shiPan = None self.setWindowTitle("大六壬") # Create mainold layout layout = QtWidgets.QHBoxLayout() mainWidget = QtWidgets.QWidget() mainWidget.setLayout(layout) self.setCentralWidget(mainWidget) self.textBrowser = QWebEngineView() layout.addWidget(self.textBrowser) # 设置右则面板 rightWidget = QtWidgets.QWidget() rightWidget.setFixedWidth(100) # layout.addWidget(rightWidget) scrollArea = QtWidgets.QScrollArea(self) scrollArea.setFixedWidth(120) scrollArea.setWidgetResizable(True) # scroll_bar = scrollArea.verticalScrollBar() scrollArea.setWidget(rightWidget) layout.addWidget(scrollArea) # 为右则面板使用水平布局 rightVBoxLayout = QtWidgets.QVBoxLayout() rightWidget.setLayout(rightVBoxLayout) # self.yearInput = QtWidgets.QLineEdit() self.yearInput.setPlaceholderText("年 1920-2050") self.yearInput.setValidator( QtGui.QIntValidator(1920, 2050, self.yearInput)) rightVBoxLayout.addWidget(self.yearInput) self.monthInput = QtWidgets.QLineEdit() self.monthInput.setPlaceholderText("月") self.monthInput.setValidator( QtGui.QIntValidator(1, 12, self.monthInput)) rightVBoxLayout.addWidget(self.monthInput) self.dayInput = QtWidgets.QLineEdit() self.dayInput.setPlaceholderText("日") self.dayInput.setValidator(QtGui.QIntValidator(1, 31, self.dayInput)) rightVBoxLayout.addWidget(self.dayInput) self.hourInput = QtWidgets.QLineEdit() self.hourInput.setPlaceholderText("时") self.hourInput.setValidator(QtGui.QIntValidator(0, 23, self.hourInput)) rightVBoxLayout.addWidget(self.hourInput) self.minutesInput = QtWidgets.QLineEdit() self.minutesInput.setPlaceholderText("分") self.minutesInput.setValidator( QtGui.QIntValidator(0, 59, self.minutesInput)) rightVBoxLayout.addWidget(self.minutesInput) self.secondInput = QtWidgets.QLineEdit() self.secondInput.setPlaceholderText("秒") self.secondInput.setValidator( QtGui.QIntValidator(0, 59, self.minutesInput)) rightVBoxLayout.addWidget(self.secondInput) timeNowButton = QtWidgets.QPushButton("当前时间") rightVBoxLayout.addWidget(timeNowButton) self.yueJiang = QtWidgets.QComboBox() self.yueJiang.addItems(DiZHiList) yueJiangHBoxLayout = QtWidgets.QHBoxLayout() yueJiangHBoxLayout.addWidget(QtWidgets.QLabel("月将")) yueJiangbutton = QtWidgets.QPushButton("计算") yueJiangHBoxLayout.addWidget(yueJiangbutton) rightVBoxLayout.addLayout(yueJiangHBoxLayout) rightVBoxLayout.addWidget(self.yueJiang) self.zhanShi = QtWidgets.QComboBox() self.zhanShi.addItems(DiZHiList) rightVBoxLayout.addWidget(QtWidgets.QLabel("占时")) rightVBoxLayout.addWidget(self.zhanShi) self.zhouZhan = QtWidgets.QComboBox() self.zhouZhan.addItems(["是", "否"]) rightVBoxLayout.addWidget(QtWidgets.QLabel("昼占/昼生人")) rightVBoxLayout.addWidget(self.zhouZhan) self.mingJu = QtWidgets.QComboBox() self.mingJu.addItems(["否", "是"]) rightVBoxLayout.addWidget(QtWidgets.QLabel("命局")) rightVBoxLayout.addWidget(self.mingJu) man = QtWidgets.QRadioButton("男") male = QtWidgets.QRadioButton("女") man.setChecked(True) self.sex = QtWidgets.QButtonGroup() self.sex.addButton(man, 0) self.sex.addButton(male, 1) sexLayout = QtWidgets.QHBoxLayout() sexLayout.addWidget(man) sexLayout.addWidget(male) rightVBoxLayout.addLayout(sexLayout) self.shengNianInput = QtWidgets.QLineEdit() self.shengNianInput.setPlaceholderText("生年") self.shengNianInput.setValidator( QtGui.QIntValidator(1920, 2050, self.shengNianInput)) rightVBoxLayout.addWidget(self.shengNianInput) rightVBoxLayout.addWidget(QtWidgets.QLabel("占测之事")) self.占测的事Input = QtWidgets.QLineEdit() rightVBoxLayout.addWidget(self.占测的事Input) button = QtWidgets.QPushButton("起六壬局") rightVBoxLayout.addWidget(button) shenShaButton = QtWidgets.QPushButton("神煞查询") rightVBoxLayout.addWidget(shenShaButton) helpButton = QtWidgets.QPushButton("帮助") rightVBoxLayout.addWidget(helpButton) rightVBoxLayout.addStretch() # 设置默认时间 self.timeNow() 月将 = GetLi(int(self.yearInput.text()), int(self.monthInput.text()), int(self.dayInput.text()), int(self.hourInput.text()), int(self.minutesInput.text()), int(self.secondInput.text()))[4] self.yueJiang.setCurrentIndex(月将.num - 1) button.clicked.connect(self.onclick) helpButton.clicked.connect(self.helpOnclick) yueJiangbutton.clicked.connect(self.yueJiangOnClick) shenShaButton.clicked.connect(self.shenShaOnclick) timeNowButton.clicked.connect(self.timeNowOnClick) # self.show() # Connect event for button @checkValue def onclick(self): year = int("0{}".format(self.yearInput.text())) month = int("0{}".format(self.monthInput.text())) day = int("0{}".format(self.dayInput.text())) hour = int("0{}".format(self.hourInput.text())) minutes = int("0{}".format(self.minutesInput.text())) second = int("0{}".format(self.secondInput.text())) shengNian = int("0{}".format(self.shengNianInput.text())) 月将 = DiZHiList[self.yueJiang.currentIndex()] 占时 = DiZHiList[self.zhanShi.currentIndex()] 昼占 = True __占测的事 = self.占测的事Input.text() if self.zhouZhan.currentIndex() == 1: 昼占 = False 命局 = False if self.mingJu.currentIndex() == 1: 命局 = True 性别 = self.sex.checkedId() if 命局: s = MinGPan(year, month, day, hour, minutes, second, 月将, 占时, 昼占, __占测的事, 性别, shengNian) else: s = ShiPan(year, month, day, hour, minutes, second, 月将, 占时, 昼占, __占测的事, 性别, shengNian) self.textBrowser.setHtml(s.toHml) self.shiPan = s @checkValue def yueJiangOnClick(self): year = int("0{}".format(self.yearInput.text())) month = int("0{}".format(self.monthInput.text())) day = int("0{}".format(self.dayInput.text())) hour = int("0{}".format(self.hourInput.text())) minutes = int("0{}".format(self.minutesInput.text())) second = int("0{}".format(self.secondInput.text())) __月将 = GetLi(year, month, day, hour, minutes, second)[4] self.yueJiang.setCurrentIndex(__月将.num - 1) __占时 = GetShiChen(int(self.hourInput.text())) self.zhanShi.setCurrentIndex(__占时.num - 1) def helpOnclick(self): # return helpDialog = HelpDialog(self) # helpDialog.setWindowTitle("帮助") # helpDialog.exec_() helpDialog.show() def shenShaOnclick(self): # return shenShaDialog = ShenShaDialog(self, self.shiPan) shenShaDialog.show() def timeNowOnClick(self): self.timeNow() def timeNow(self): nowDateTime = datetime.datetime.today() self.yearInput.setText("{}".format(nowDateTime.year)) self.monthInput.setText("{}".format(nowDateTime.month)) self.dayInput.setText("{}".format(nowDateTime.day)) self.hourInput.setText("{}".format(nowDateTime.hour)) self.minutesInput.setText("{}".format(nowDateTime.minute)) self.secondInput.setText("{}".format(nowDateTime.second)) self.shengNianInput.setText("{}".format(nowDateTime.year)) __占时 = GetShiChen(nowDateTime.hour) # self.zhanShi.setCurrentIndex(GetShiChen(int(self.hourInput.text())).num # - 1) self.zhanShi.setCurrentIndex(__占时.num - 1)
class MainFornecedor(Ui_ct_MainFornecedor, Ui_ct_FormFornecedor): def mainfornecedor(self, frame): super(MainFornecedor, self).setMainFornecedor(frame) self.frameMainFornecedor.show() # Icone Botoes self.IconeBotaoForm(self.bt_AddNovoFornecedor, self.resourcepath('Images/addFornecedor.svg')) self.IconeBotaoMenu(self.bt_BuscaFornecedor, self.resourcepath('Images/search.png')) self.IconeBotaoMenu(self.bt_PrintRelatForn, self.resourcepath('Images/gtk-print.png')) # Botao Adicionar Cliente / FormFornecedor self.bt_AddNovoFornecedor.clicked.connect(self.FormFornecedor) self.tb_Fornecedor.setColumnHidden(0, True) self.tb_Fornecedor.setColumnWidth(1, 40) self.tb_Fornecedor.setColumnWidth(2, 270) self.tb_Fornecedor.setColumnWidth(3, 130) self.tb_Fornecedor.setColumnWidth(4, 225) self.tb_Fornecedor.setColumnWidth(5, 225) self.tb_Fornecedor.setColumnWidth(6, 60) # Populando Tabela Fornecedor self.TabelaFornecedor() # buscando por nome self.tx_BuscaFornecedor.textEdited.connect(self.TabelaFornecedor) # Imprimindo Tabela self.bt_PrintRelatForn.clicked.connect(self.imprimir) def TabelaFornecedor(self): lista = CrudFornecedor() lista.nomeFantasia = self.tx_BuscaFornecedor.text() lista.listaFornecedor() # Limpando Tabela while self.tb_Fornecedor.rowCount() > 0: self.tb_Fornecedor.removeRow(0) i = 0 if len(lista.nomeFantasia) >= 1: while i < len(lista.nomeFantasia): self.tb_Fornecedor.insertRow(i) self.TabelaStatus(self.tb_Fornecedor, i, 0, self.StatusEntrega(1)) self.TabelaID(self.tb_Fornecedor, i, 1, lista.id[i]) self.TabelaNomeTelefone(self.tb_Fornecedor, i, 2, lista.nomeFantasia[i], lista.razaoSocial[i]) self.TabelaNomeTelefone( self.tb_Fornecedor, i, 3, self.formatoNumTelefone(lista.telefone[i]), "") self.TabelaNomeTelefone(self.tb_Fornecedor, i, 4, lista.email[i], "") self.TabelaNomeTelefone(self.tb_Fornecedor, i, 5, lista.site[i], "") # Sinal click tabela self.botaoTabela(self.tb_Fornecedor, i, 6, partial(self.SelectFornecedor, lista.id[i]), "#005099") i += 1 pass # Seleciona Cliente por ID def SelectFornecedor(self, id): busca = CrudFornecedor() self.FormFornecedor() busca.id = id busca.SelectFornecedorId() self.tx_Id.setText(str(busca.id)) self.tx_NomeFantasia.setText(busca.nomeFantasia) self.tx_RazaoSocial.setText(busca.razaoSocial) self.tx_cnpj.setText(str(busca.cnpj)) self.tx_InscEstadual.setText(str(busca.inscEstadual)) self.tx_Telefone.setText(str(busca.telefone)) self.tx_Site.setText(busca.site) self.tx_Email.setText(busca.email) self.tx_Obs.setText(busca.obs) self.tx_Cep.setText(busca.cep) self.tx_Endereco.setText(busca.endereco) self.tx_Numero.setText(str(busca.numero)) self.tx_Bairro.setText(busca.bairro) self.tx_Cidade.setText(busca.cidade) self.tx_Estado.setText(busca.estado) # Limpando tabela Histórico de Compras for row in range(self.tb_Historico.rowCount()): self.tb_Historico.removeRow(row) # Histórico de Compras cliente total = '0.00' lista = CrudCompra() lista.idFornecedor = id lista.selectCompraFornecedor() i = 0 while i < len(lista.dataEmissao): # print row self.tb_Historico.insertRow(i) self.conteudoTabela(self.tb_Historico, i, 0, str(lista.dataEmissao[i])) self.conteudoTabela(self.tb_Historico, i, 1, str(lista.dataEntrega[i])) self.conteudoTabela(self.tb_Historico, i, 2, str(lista.valorTotal[i])) total = float(lista.valorTotal[i]) + float(total) i += 1 self.lb_TotalHistorico.setText(format(float(total), ".2f")) pass # Frame Formulário Produtos def FormFornecedor(self): # self.DesativaBotaoProdutos() self.LimpaFrame(self.ct_containerFornecedor) super(MainFornecedor, self).setFormFornecedor(self.ct_containerFornecedor) self.fr_FormFornecedor.show() # Icone Botoes self.IconeBotaoMenu(self.bt_Salvar, self.resourcepath('Images/salvar.png')) self.IconeBotaoMenu(self.bt_Voltar, self.resourcepath('Images/cancelar.png')) self.IconeBotaoMenu(self.bt_BuscaCep, self.resourcepath('Images/find.png')) # Checando se existe ID válido self.IdCheckFornecedor() # Tamanho tabela Histórico self.tb_Historico.setColumnWidth(0, 100) self.tb_Historico.setColumnWidth(1, 100) self.tb_Historico.setColumnWidth(2, 100) # Botao Salvar self.bt_Salvar.clicked.connect(self.VerificaInputFornecedor) # Botão Voltar self.bt_Voltar.clicked.connect(self.janelaFornecedor) # Buscar Cep self.bt_BuscaCep.clicked.connect(self.buscarCepCliente) self.tx_Cep.returnPressed.connect(self.buscarCepCliente) # checando campo Id se é Edicao ou Novo Fornecedor def IdCheckFornecedor(self): if not self.tx_Id.text(): busca = CrudFornecedor() self.tx_Id.setText(str(busca.lastIdFornecedor())) # Verificando Campos antes do INPUT def VerificaInputFornecedor(self): if not self.tx_NomeFantasia.text(): self.tx_NomeFantasia.setFocus() elif not self.tx_Telefone.text(): self.tx_Telefone.setFocus() else: self.CadFornecedor() # Cadastrando fornecedor def CadFornecedor(self): INSERI = CrudFornecedor() INSERI.id = self.tx_Id.text() INSERI.nomeFantasia = self.tx_NomeFantasia.text().upper() INSERI.razaoSocial = self.tx_RazaoSocial.text().upper() INSERI.cnpj = self.tx_cnpj.text() INSERI.inscEstadual = self.tx_InscEstadual.text() INSERI.telefone = re.sub('[^[0-9]', '', self.tx_Telefone.text()) INSERI.email = self.tx_Email.text() INSERI.site = self.tx_Site.text() INSERI.obs = self.tx_Obs.text().upper() INSERI.cep = re.sub('[^[0-9]', '', self.tx_Cep.text()) INSERI.endereco = self.tx_Endereco.text().upper() INSERI.numero = self.tx_Numero.text() INSERI.bairro = self.tx_Bairro.text().upper() INSERI.cidade = self.tx_Cidade.text().upper() INSERI.estado = self.tx_Estado.text() INSERI.inseriFornecedor() self.janelaFornecedor() # Imprimindo def imprimir(self): self.documento = QWebEngineView() headertable = ["Cod", "Nome Fantasia", "Telefone", "Email", "Site"] codcliente = [] nomeFornecedor = [] telefoneFornecedor = [] siteFornecedor = [] emailFornecedor = [] i = 0 for i in range(self.tb_Fornecedor.rowCount()): codcliente.append(self.tb_Fornecedor.cellWidget(i, 1).text()) nomeFornecedor.append(self.tb_Fornecedor.cellWidget(i, 2).text()) telefoneFornecedor.append( self.tb_Fornecedor.cellWidget(i, 3).text()) siteFornecedor.append(self.tb_Fornecedor.cellWidget(i, 4).text()) emailFornecedor.append(self.tb_Fornecedor.cellWidget(i, 5).text()) i += 1 html = self.renderTemplate( "report.html", estilo=self.resourcepath('Template/estilo.css'), titulo="LISTAGEM FORNECEDOR", headertable=headertable, codcliente=codcliente, nomeFornecedor=nomeFornecedor, telefoneFornecedor=telefoneFornecedor, siteFornecedor=siteFornecedor, emailFornecedor=emailFornecedor) self.documento.load( QtCore.QUrl.fromLocalFile(self.resourcepath("report.html"))) self.documento.loadFinished['bool'].connect(self.previaImpressao)
class QmMainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionShow.triggered.connect(self.toggle_mode) self.ui.actionSave.triggered.connect(self.save_note) self.ui.actionLoadShelf.triggered.connect(self.download_shelf) self.ui.actionLoadHot.triggered.connect(self.show_hot_note) self.ui.actionLoadNotes.triggered.connect(self.download_notes) self.ui.statusBar.hide() self.pbar = QProgressBar(self) self.pbar.setFixedWidth(500) self.ui.statusBar.addWidget(self.pbar) icon = QtGui.QIcon() icon.addPixmap( QtGui.QPixmap(os.path.join(root_path, "static/icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) self.browser = QWebEngineView(self) self.browser.setGeometry( 0, self.ui.menubar.height(), self.width(), self.height() - self.ui.menubar.height(), ) self.ui.actionback.triggered.connect(self.browser.back) self.ui.actionforward.triggered.connect(self.browser.forward) self.ui.actionShelf.triggered.connect(self.view_shelf) self.ui.actionLibrary.triggered.connect(self.view_library) # 加载外部的web页面 self.cache_path = os.path.join(root_path, "cache") if not os.path.exists(self.cache_path): os.mkdir(self.cache_path) # 设置缓存目录 default_profile = QWebEngineProfile.defaultProfile() default_profile.setCachePath(self.cache_path) default_profile.setPersistentStoragePath(self.cache_path) # 记录上次阅读位置 self.history_url_file = os.path.join(self.cache_path,"history.txt") if not os.path.exists(self.history_url_file): url = QUrl("https://weread.qq.com/") else: with open(self.history_url_file,'r') as f: url = QUrl(f.read().strip()) self.browser.urlChanged.connect(self.update_lastpage) # 每次改变都更新还是退出的时候更新 self.browser.load(url) self.model = QStringListModel(self) self.item_model = QStandardItemModel(self) self.select_model = QItemSelectionModel(self.item_model) self.ui.tableView.setModel(self.item_model) self.ui.tableView.setSelectionModel(self.select_model) self.ui.tableView.setAlternatingRowColors(True) self.ui.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.is_reading_mode = True self.note_dir = os.path.join(root_path, "notes") if not os.path.exists(self.note_dir): os.mkdir(self.note_dir) try: self.update_cookies() self.booklist = wereader.get_bookshelf(self.cookies) self.books = itertools.cycle(self.booklist) self.curBook = self.booklist[0] except Exception: self.curBook = None self.booklist = None def update_cookies(self): self.cookies = read_cookie_from_path(self.cache_path + "/Cookies") def update_lastpage(self): with open(self.history_url_file,'w') as f: f.write(self.browser.history().currentItem().url().toString()) def resizeEvent(self, a0): self.browser.resize( self.width(), self.height() - self.ui.menubar.height(), ) self.ui.splitter_2.resize( self.width() - 10, self.height() - self.ui.menubar.height(), ) self.ui.tableView.resize( self.ui.splitter.width(), self.ui.splitter.height() // 2 ) def on_listView_clicked(self, index): self.curBook = self.booklist[index.row()] self.on_curBook_changed() def on_tableView_clicked(self, index): self.curBook = self.booklist[index.row()] self.on_curBook_changed() def on_curBook_changed(self): self.ui.noteEdit.clear() note = self.get_note(self.curBook.bookId) self.ui.noteEdit.setText(note) def show_hot_note(self): self.ui.noteEdit.clear() note = self.get_hot_note(self.curBook.bookId) self.ui.noteEdit.setText(note) def get_note(self, id): note_name = os.path.join(self.note_dir, "%s.md" % id) if os.path.exists(note_name): with open(note_name, "r", encoding="utf-8") as f: return f.read() else: return wereader.get_bookmarklist(id, cookies=self.cookies) def get_hot_note(self, id): note_name = os.path.join(self.note_dir, "%s_hot.md" % id) if os.path.exists(note_name): with open(note_name, "r", encoding="utf-8") as f: return f.read() else: return wereader.get_bestbookmarks(id, cookies=self.cookies) def on_nextButton_clicked(self): self.curBook = next(self.books) self.on_curBook_changed() def save_note(self): text = self.ui.noteEdit.toPlainText() note_name = os.path.join(self.note_dir, "%s.md" % self.curBook.bookId) with open(note_name, "w", encoding="utf-8") as f: f.write(text) def toggle_mode(self): if self.is_reading_mode: self.browser.setVisible(False) self.ui.actionShow.setText("切换至阅读模式") self.is_reading_mode = False else: self.browser.setVisible(True) self.ui.actionShow.setText("切换至笔记模式") self.is_reading_mode = True def download_shelf(self): """加载书架时默认已经登录,重新获取cookie""" if not self.booklist: self.update_cookies() self.booklist = wereader.get_bookshelf(self.cookies) self.books = itertools.cycle(self.booklist) self.init_model() def init_model(self): self.model.setStringList([b.title for b in self.booklist]) self.ui.listView.setModel(self.model) self.ui.listView.setEditTriggers(QAbstractItemView.NoEditTriggers) rows = len(self.booklist) cols = 3 self.item_model.setRowCount(rows) self.item_model.setColumnCount(cols) for i in range(rows): try: self.item_model.setItem(i, 0, QStandardItem(self.booklist[i].bookId)) self.item_model.setItem(i, 1, QStandardItem(self.booklist[i].title)) self.item_model.setItem(i, 2, QStandardItem(self.booklist[i].author)) except Exception as e: print(e) self.ui.tableView.setModel(self.item_model) w = self.ui.splitter.width() // 10 self.ui.tableView.setColumnWidth(0, 1 * w) self.ui.tableView.setColumnWidth(1, 6 * w) self.ui.tableView.setColumnWidth(2, 3 * w) self.ui.tableView.setSelectionModel(self.select_model) # def view(self): # img = cv2.imread(next(self.images)) # 读取图像 # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换图像通道 # w, h = self.ui.graphicsView.width(), self.ui.graphicsView.height() # img = cv2.resize(img, (w, h)) # frame = QImage(img, w, h, QImage.Format_RGB888) # pix = QPixmap.fromImage(frame) # self.item = QGraphicsPixmapItem(pix) # 创建像素图元 # # self.item.setScale(self.zoomscale) # self.scene = QGraphicsScene() # 创建场景 # self.scene.addItem(self.item) # self.ui.graphicsView.setScene(self.scene) # 将场景添加至视图 def download_notes(self): self.ui.actionLoadNotes.setDisabled(True) self.ui.statusBar.show() self.pbar.show() self.pbar.setMaximum(len(self.booklist)) for i, book in enumerate(self.booklist): self.pbar.setValue(i) try: note_name = os.path.join(self.note_dir, "%s.md" % book.bookId) if os.path.exists(note_name): continue note = self.get_note(book.bookId) if note.strip(): with open(note_name, 'w', encoding='utf-8') as f: f.write(note) except Exception as e: print(e) self.pbar.hide() self.ui.statusBar.hide() def view_library(self): self.browser.load(QUrl("https://weread.qq.com/web/category")) def view_shelf(self): self.browser.load(QUrl("https://weread.qq.com/web/shelf"))
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.DomainCookies = {} self.setWindowTitle('微信读书助手') # 设置窗口标题 self.resize(900, 600) # 设置窗口大小 self.setWindowFlags(Qt.WindowMinimizeButtonHint) # 禁止最大化按钮 self.setFixedSize(self.width(), self.height()) # 禁止调整窗口大小 url = 'https://weread.qq.com/#login' # 目标地址 self.browser = QWebEngineView() # 实例化浏览器对象 self.profile = QWebEngineProfile.defaultProfile() self.profile.cookieStore().deleteAllCookies() # 初次运行软件时删除所有cookies self.profile.cookieStore().cookieAdded.connect( self.onCookieAdd) # cookies增加时触发self.onCookieAdd()函数 self.browser.loadFinished.connect( self.onLoadFinished) # 网页加载完毕时触发self.onLoadFinished()函数 self.browser.load(QUrl(url)) # 加载网页 self.setCentralWidget(self.browser) # 设置中心窗口 # 网页加载完毕事件 def onLoadFinished(self): global USER_VID global HEADERS # 获取cookies cookies = [ '{}={};'.format(key, value) for key, value in self.DomainCookies.items() ] cookies = ' '.join(cookies) # 添加Cookie到header HEADERS.update(Cookie=cookies) # 判断是否成功登录微信读书 if login_success(HEADERS): print('登录微信读书成功!') # 获取用户user_vid if 'wr_vid' in self.DomainCookies.keys(): USER_VID = self.DomainCookies['wr_vid'] print('用户id:{}'.format(USER_VID)) # 注入javascript脚本,与网页交互 self.browser.page().runJavaScript('alert("登录成功!")') # 关闭整个qt窗口 self.close() else: print('请扫描二维码登录微信读书...') # 添加cookies事件 def onCookieAdd(self, cookie): if 'weread.qq.com' in cookie.domain(): name = cookie.name().data().decode('utf-8') value = cookie.value().data().decode('utf-8') if name not in self.DomainCookies: self.DomainCookies.update({name: value}) # 窗口关闭事件 def closeEvent(self, event): """ 重写closeEvent方法,实现窗体关闭时执行一些代码 :param event: close()触发的事件 :return: None """ self.setWindowTitle('退出中……') # 设置窗口标题 # 关闭软件软件之前删除所有cookies # 此代码不可删除,否则下次打开软件会自动加载浏览器中旧的cookies self.profile.cookieStore().deleteAllCookies()
window = uic.loadUi("mainViewQt.ui") initPosition() window.botaoUp.clicked.connect(on_botaoUp_clicked) window.botaoDown.clicked.connect(on_botaoDown_clicked) window.botaoLeft.clicked.connect(on_botaoLeft_clicked) window.botaoRight.clicked.connect(on_botaoRight_clicked) window.botaoHome.clicked.connect(on_botaoHome_clicked) window.labelFrameB4B3B2.setScaledContents(True) window.labelFrameB8.setScaledContents(True) window.labelFrameB8A.setScaledContents(True) window.labelFrameB11B12.setScaledContents(True) window.labelFrameB5B6B7.setScaledContents(True) window.labelFrameB1B9B10.setScaledContents(True) window.labelFrameGT.setScaledContents(True) window.labelFramePredict.setScaledContents(True) vbox = QVBoxLayout(window.widgetMap) webView = QWebEngineView() vbox.addWidget(webView) window.widgetMap.setLayout(vbox) #webView.load(QUrl("https://www.google.pt/maps/@41.5333322,-8.6325896,14z")) window.widgetMap.show() on_botaoHome_clicked() window.show() sys.exit(app.exec())
class Ui_SLIMB(object): def setupUi(self, SLIMB, homeurl): SLIMB.setObjectName("SLIMB") SLIMB.resize(1075, 838) self.centralwidget = QtWidgets.QWidget(SLIMB) self.centralwidget.setObjectName("centralwidget") self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.horizontalLayoutWidget.setGeometry(QtCore.QRect(20, 10, 1041, 71)) self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") self.horizontalLayout = QtWidgets.QHBoxLayout( self.horizontalLayoutWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName("horizontalLayout") self.butBack = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.butBack.setObjectName("butBack") self.horizontalLayout.addWidget(self.butBack) self.butRefresh = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.butRefresh.setObjectName("butRefresh") self.horizontalLayout.addWidget(self.butRefresh) self.butForward = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.butForward.setObjectName("butForward") self.horizontalLayout.addWidget(self.butForward) self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.gridLayoutWidget.setGeometry(QtCore.QRect(19, 130, 1041, 661)) self.gridLayoutWidget.setObjectName("gridLayoutWidget") self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.webView = QWebEngineView(self.gridLayoutWidget) self.webView.setUrl(QtCore.QUrl(homeurl)) self.webView.setObjectName("webView") self.gridLayout.addWidget(self.webView, 0, 0, 1, 1) SLIMB.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(SLIMB) self.menubar.setGeometry(QtCore.QRect(0, 0, 1075, 22)) self.menubar.setObjectName("menubar") self.menuSetting = QtWidgets.QMenu(self.menubar) self.menuSetting.setObjectName("menuSetting") SLIMB.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(SLIMB) self.statusbar.setObjectName("statusbar") SLIMB.setStatusBar(self.statusbar) self.actionReboot = QtWidgets.QAction(SLIMB) self.actionReboot.setObjectName("actionReboot") self.actionSend_Email = QtWidgets.QAction(SLIMB) self.actionSend_Email.setObjectName("actionSend_Email") self.menuSetting.addAction(self.actionReboot) self.menuSetting.addAction(self.actionSend_Email) self.menubar.addAction(self.menuSetting.menuAction()) self.retranslateUi(SLIMB) self.actionReboot.triggered.connect(self.actionReboot.trigger) self.actionSend_Email.triggered.connect(self.actionSend_Email.trigger) self.butBack.clicked.connect(self.butBack.click) self.butForward.clicked.connect(self.butForward.click) self.butRefresh.clicked.connect(self.butRefresh.click) QtCore.QMetaObject.connectSlotsByName(SLIMB) def retranslateUi(self, SLIMB): _translate = QtCore.QCoreApplication.translate SLIMB.setWindowTitle(_translate("SLIMB", "MainWindow")) self.butBack.setText(_translate("SLIMB", "BACK")) self.butRefresh.setText(_translate("SLIMB", "REFRESH")) self.butForward.setText(_translate("SLIMB", "FORWARD")) self.menuSetting.setTitle(_translate("SLIMB", "Setting")) self.actionReboot.setText(_translate("SLIMB", "Reboot")) self.actionSend_Email.setText(_translate("SLIMB", "Send Email"))
def __init__(self, url, disable_browser): # initialize super().__init__() self._view = None self._is_closing = False # initialize the main window self.setWindowTitle(APP_NAME) if IS_FROZEN: base_dir = os.path.join(sys._MEIPASS, "vasl_templates/webapp") #pylint: disable=no-member,protected-access else: base_dir = os.path.join(os.path.split(__file__)[0], "webapp") self.setWindowIcon( QIcon(os.path.join(base_dir, "static/images/app.ico"))) # create the menu menu_bar = QMenuBar(self) file_menu = menu_bar.addMenu("&File") def add_action(caption, icon, handler): """Add a menu action.""" icon = QIcon( os.path.join(base_dir, "static/images/menu", icon ) if icon else None) action = QAction(icon, caption, self) action.triggered.connect(handler) file_menu.addAction(action) add_action("&Settings", "settings.png", self.on_settings) add_action("&About", "info.png", self.on_about) file_menu.addSeparator() add_action("E&xit", "exit.png", self.on_exit) # set the window geometry if disable_browser: self.setFixedSize(300, 108) else: # restore it from the previous session val = app_settings.value("MainWindow/geometry") if val: self.restoreGeometry(val) else: self.resize(1000, 650) self.setMinimumSize(1000, 620) # initialize the layout layout = QVBoxLayout(self) layout.setMenuBar(menu_bar) # FUDGE! We offer the option to disable the QWebEngineView since getting it to run # under Windows (especially older versions) is unreliable (since it uses OpenGL). # By disabling it, the program will at least start (in particular, the webapp server), # and non-technical users can then open an external browser and connect to the webapp # that way. Sigh... if not disable_browser: # initialize the web view self._view = QWebEngineView() layout.addWidget(self._view) # initialize the web page # nb: we create an off-the-record profile to stop the view from using cached JS files :-/ profile = QWebEngineProfile(None, self._view) version = APP_NAME.lower().replace(" ", "-") + "/" + APP_VERSION[1:] profile.setHttpUserAgent( re.sub(r"QtWebEngine/\S+", version, profile.httpUserAgent())) page = AppWebPage(profile, self._view) self._view.setPage(page) # create a web channel to communicate with the front-end web_channel = QWebChannel(page) # FUDGE! We would like to register a WebChannelHandler instance as the handler, but this crashes PyQt :-/ # Instead, we register ourself as the handler, and delegate processing to a WebChannelHandler. # The downside is that PyQt emits lots of warnings about our member variables not being properties, # but we filter them out in qtMessageHandler() :-/ self._web_channel_handler = WebChannelHandler(self) web_channel.registerObject("handler", self) page.setWebChannel(web_channel) # load the webapp url += "?pyqt=1" self._view.load(QUrl(url)) else: # show a minimal UI label = QLabel() label.setTextFormat(Qt.RichText) label.setText( "Running the <em>{}</em> application. <br>" \ "Click <a href='{}'>here</a> to connect." \ "<p> Close this window when you're done.".format( APP_NAME, url ) ) label.setStyleSheet( "QLabel { background-color: white ; padding: 0.5em ; }") label.setOpenExternalLinks(True) layout.addWidget(label) layout.setContentsMargins(QMargins(0, 0, 0, 0)) # register the instance assert MainWindow.instance is None MainWindow.instance = self
class MainWindow(QWidget): """Main application window.""" instance = None def __init__(self, url, disable_browser): # initialize super().__init__() self._view = None self._is_closing = False # initialize the main window self.setWindowTitle(APP_NAME) if IS_FROZEN: base_dir = os.path.join(sys._MEIPASS, "vasl_templates/webapp") #pylint: disable=no-member,protected-access else: base_dir = os.path.join(os.path.split(__file__)[0], "webapp") self.setWindowIcon( QIcon(os.path.join(base_dir, "static/images/app.ico"))) # create the menu menu_bar = QMenuBar(self) file_menu = menu_bar.addMenu("&File") def add_action(caption, icon, handler): """Add a menu action.""" icon = QIcon( os.path.join(base_dir, "static/images/menu", icon ) if icon else None) action = QAction(icon, caption, self) action.triggered.connect(handler) file_menu.addAction(action) add_action("&Settings", "settings.png", self.on_settings) add_action("&About", "info.png", self.on_about) file_menu.addSeparator() add_action("E&xit", "exit.png", self.on_exit) # set the window geometry if disable_browser: self.setFixedSize(300, 108) else: # restore it from the previous session val = app_settings.value("MainWindow/geometry") if val: self.restoreGeometry(val) else: self.resize(1000, 650) self.setMinimumSize(1000, 620) # initialize the layout layout = QVBoxLayout(self) layout.setMenuBar(menu_bar) # FUDGE! We offer the option to disable the QWebEngineView since getting it to run # under Windows (especially older versions) is unreliable (since it uses OpenGL). # By disabling it, the program will at least start (in particular, the webapp server), # and non-technical users can then open an external browser and connect to the webapp # that way. Sigh... if not disable_browser: # initialize the web view self._view = QWebEngineView() layout.addWidget(self._view) # initialize the web page # nb: we create an off-the-record profile to stop the view from using cached JS files :-/ profile = QWebEngineProfile(None, self._view) version = APP_NAME.lower().replace(" ", "-") + "/" + APP_VERSION[1:] profile.setHttpUserAgent( re.sub(r"QtWebEngine/\S+", version, profile.httpUserAgent())) page = AppWebPage(profile, self._view) self._view.setPage(page) # create a web channel to communicate with the front-end web_channel = QWebChannel(page) # FUDGE! We would like to register a WebChannelHandler instance as the handler, but this crashes PyQt :-/ # Instead, we register ourself as the handler, and delegate processing to a WebChannelHandler. # The downside is that PyQt emits lots of warnings about our member variables not being properties, # but we filter them out in qtMessageHandler() :-/ self._web_channel_handler = WebChannelHandler(self) web_channel.registerObject("handler", self) page.setWebChannel(web_channel) # load the webapp url += "?pyqt=1" self._view.load(QUrl(url)) else: # show a minimal UI label = QLabel() label.setTextFormat(Qt.RichText) label.setText( "Running the <em>{}</em> application. <br>" \ "Click <a href='{}'>here</a> to connect." \ "<p> Close this window when you're done.".format( APP_NAME, url ) ) label.setStyleSheet( "QLabel { background-color: white ; padding: 0.5em ; }") label.setOpenExternalLinks(True) layout.addWidget(label) layout.setContentsMargins(QMargins(0, 0, 0, 0)) # register the instance assert MainWindow.instance is None MainWindow.instance = self def closeEvent(self, evt): """Handle requests to close the window (i.e. exit the application).""" # check if we need to check for a dirty scenario if self._view is None or self._is_closing: return def close_window(): """Close the main window.""" if self._view: app_settings.setValue("MainWindow/geometry", self.saveGeometry()) self.close() # FUDGE! We need to do this to stop PyQt 5.15.2 from complaining that the profile # is being deleted while the page is still alive. self._view.page().deleteLater() # check if the scenario is dirty def callback(is_dirty): """Callback for PyQt to return the result of running the Javascript.""" if not is_dirty: # nope - just close the window self._is_closing = True close_window() return # yup - ask the user to confirm the close rc = MainWindow.ask( "This scenario has been changed\n\nDo you want to close the program, and lose your changes?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if rc == QMessageBox.Yes: # confirmed - close the window self._is_closing = True close_window() self._view.page().runJavaScript("is_scenario_dirty()", callback) evt.ignore( ) # nb: we wait until the Javascript finishes to process the event @staticmethod def showInfoMsg(msg): """Show an informational message.""" QMessageBox.information(MainWindow.instance, APP_NAME, msg) @staticmethod def showErrorMsg(msg): """Show an error message.""" QMessageBox.warning(MainWindow.instance, APP_NAME, msg) @staticmethod def ask(msg, buttons, default): """Ask the user a question.""" return QMessageBox.question(MainWindow.instance, APP_NAME, msg, buttons, default) def on_exit(self): """Menu action handler.""" self.close() def on_settings(self): """Menu action handler.""" from vasl_templates.server_settings import ServerSettingsDialog #pylint: disable=cyclic-import dlg = ServerSettingsDialog(self) dlg.exec_() def on_about(self): """Menu action handler.""" from vasl_templates.about import AboutDialog #pylint: disable=cyclic-import dlg = AboutDialog(self) dlg.exec_() @pyqtSlot() @catch_exceptions(caption="SLOT EXCEPTION") def on_app_loaded(self): """Called when the application has finished loading. NOTE: This handler might be called multiple times. """ def decode_val(val): """Decode a settings value.""" # NOTE: Comma-separated values are deserialized as lists automatically. if val == "true": return True if val == "false": return False if str(val).isdigit(): return int(val) return val # load and install the user settings user_settings = {} for key in app_settings.allKeys(): if key.startswith("UserSettings/"): val = app_settings.value(key) key = key[13:] # remove the leading "UserSettings/" sections = key.split(".") target = user_settings while len(sections) > 1: if sections[0] not in target: target[sections[0]] = {} target = target[sections.pop(0)] target[sections[0]] = decode_val(val) self._view.page().runJavaScript("install_user_settings('{}')".format( json.dumps(user_settings))) @pyqtSlot() @catch_exceptions(caption="SLOT EXCEPTION") def on_new_scenario(self): """Called when the user wants to load a scenario.""" self._web_channel_handler.on_new_scenario() @pyqtSlot(result=QVariant) @catch_exceptions(caption="SLOT EXCEPTION") def load_scenario(self): """Called when the user wants to load a scenario.""" fname, data = self._web_channel_handler.load_scenario() if data is None: return None return QVariant({"filename": fname, "data": data}) @pyqtSlot(str, str, result=str) @catch_exceptions(caption="SLOT EXCEPTION", retval=False) def save_scenario(self, fname, data): """Called when the user wants to save a scenario.""" fname = self._web_channel_handler.save_scenario(fname, data) return fname @pyqtSlot(result=QVariant) @catch_exceptions(caption="SLOT EXCEPTION") def load_vsav(self): """Called when the user wants to update a VASL scenario.""" fname, data = self._web_channel_handler.load_vsav() if data is None: return None return QVariant({ "filename": fname, "data": base64.b64encode(data).decode("utf-8") }) @pyqtSlot(str, str, result=bool) @catch_exceptions(caption="SLOT EXCEPTION", retval=False) def save_updated_vsav(self, fname, data): """Called when a VASL scenario has been updated and is ready to be saved.""" data = base64.b64decode(data) return self._web_channel_handler.save_updated_vsav(fname, data) @pyqtSlot(str) @catch_exceptions(caption="SLOT EXCEPTION", retval=False) def save_log_file_analysis(self, data): """Called when the user wants to save a log file analysis.""" self._web_channel_handler.save_log_file_analysis(data) @pyqtSlot(str) @catch_exceptions(caption="SLOT EXCEPTION") def on_user_settings_change(self, user_settings): #pylint: disable=no-self-use """Called when the user changes the user settings.""" # delete all existing keys for key in app_settings.allKeys(): if key.startswith("UserSettings/"): app_settings.remove(key) # save the new user settings def save_section(vals, key_prefix): """Save a section of the User Settings.""" for key, val in vals.items(): if isinstance(val, dict): # FUDGE! The PyQt doco claims that it supports nested sections, but key names that have # a slash in them get saved as a top-level key, with the slash converted to a back-slash, # even on Linux :-/ We use dotted key names to represent nested levels. save_section(val, key_prefix + key + ".") continue # NOTE: PyQt handles lists automatically, converting them to a comma-separated list, # and de-serializing them as lists (string values with a comma in them get quoted). app_settings.setValue( "UserSettings/{}".format(key_prefix + key), val) save_section(json.loads(user_settings), "") @pyqtSlot(str, bool) @catch_exceptions(caption="SLOT EXCEPTION") def on_update_scenario_status(self, caption, is_dirty): """Update the UI to show the scenario's status.""" self._web_channel_handler.on_update_scenario_status(caption, is_dirty) @pyqtSlot(str) @catch_exceptions(caption="SLOT EXCEPTION") def on_snippet_image(self, img_data): """Called when a snippet image has been generated.""" self._web_channel_handler.on_snippet_image(img_data) @pyqtSlot(str, str, result=bool) @catch_exceptions(caption="SLOT EXCEPTION", retval=False) def save_downloaded_vsav(self, fname, data): """Called when a VASL scenario has been downloaded.""" data = base64.b64decode(data) # NOTE: We handle this the same as saving an updated VSAV. return self._web_channel_handler.save_updated_vsav(fname, data)
def __init__(self, parent=None): QWebEngineView.__init__(self, parent) self._last_reload_at = None self.renderProcessTerminated.connect(self.render_process_terminated) self.render_process_restarted.connect( self.reload, type=Qt.ConnectionType.QueuedConnection)
from PyQt5.QtCore import QUrl from MySharedObject import MySharedObject from PyQt5.QtWebChannel import QWebChannel import sys # 创建一个 application实例 app = QApplication(sys.argv) win = QWidget() win.setWindowTitle('Web页面中的JavaScript与 QWebEngineView交互例子') # 创建一个垂直布局器 layout = QVBoxLayout() win.setLayout(layout) # 创建一个 QWebEngineView 对象 view = QWebEngineView() htmlUrl = 'http://127.0.0.1:8020/web/index.html' view.load(QUrl(htmlUrl)) # 创建一个 QWebChannel对象,用来传递pyqt参数到JavaScript channel = QWebChannel() myObj = MySharedObject() channel.registerObject("bridge", myObj) view.page().setWebChannel(channel) # 把QWebView和button加载到layout布局中 layout.addWidget(view) # 显示窗口和运行app win.show() sys.exit(app.exec_())
def __init__(self): super().__init__() self.shiPan = None self.setWindowTitle("大六壬") # Create mainold layout layout = QtWidgets.QHBoxLayout() mainWidget = QtWidgets.QWidget() mainWidget.setLayout(layout) self.setCentralWidget(mainWidget) self.textBrowser = QWebEngineView() layout.addWidget(self.textBrowser) # 设置右则面板 rightWidget = QtWidgets.QWidget() rightWidget.setFixedWidth(100) # layout.addWidget(rightWidget) scrollArea = QtWidgets.QScrollArea(self) scrollArea.setFixedWidth(120) scrollArea.setWidgetResizable(True) # scroll_bar = scrollArea.verticalScrollBar() scrollArea.setWidget(rightWidget) layout.addWidget(scrollArea) # 为右则面板使用水平布局 rightVBoxLayout = QtWidgets.QVBoxLayout() rightWidget.setLayout(rightVBoxLayout) # self.yearInput = QtWidgets.QLineEdit() self.yearInput.setPlaceholderText("年 1920-2050") self.yearInput.setValidator( QtGui.QIntValidator(1920, 2050, self.yearInput)) rightVBoxLayout.addWidget(self.yearInput) self.monthInput = QtWidgets.QLineEdit() self.monthInput.setPlaceholderText("月") self.monthInput.setValidator( QtGui.QIntValidator(1, 12, self.monthInput)) rightVBoxLayout.addWidget(self.monthInput) self.dayInput = QtWidgets.QLineEdit() self.dayInput.setPlaceholderText("日") self.dayInput.setValidator(QtGui.QIntValidator(1, 31, self.dayInput)) rightVBoxLayout.addWidget(self.dayInput) self.hourInput = QtWidgets.QLineEdit() self.hourInput.setPlaceholderText("时") self.hourInput.setValidator(QtGui.QIntValidator(0, 23, self.hourInput)) rightVBoxLayout.addWidget(self.hourInput) self.minutesInput = QtWidgets.QLineEdit() self.minutesInput.setPlaceholderText("分") self.minutesInput.setValidator( QtGui.QIntValidator(0, 59, self.minutesInput)) rightVBoxLayout.addWidget(self.minutesInput) self.secondInput = QtWidgets.QLineEdit() self.secondInput.setPlaceholderText("秒") self.secondInput.setValidator( QtGui.QIntValidator(0, 59, self.minutesInput)) rightVBoxLayout.addWidget(self.secondInput) timeNowButton = QtWidgets.QPushButton("当前时间") rightVBoxLayout.addWidget(timeNowButton) self.yueJiang = QtWidgets.QComboBox() self.yueJiang.addItems(DiZHiList) yueJiangHBoxLayout = QtWidgets.QHBoxLayout() yueJiangHBoxLayout.addWidget(QtWidgets.QLabel("月将")) yueJiangbutton = QtWidgets.QPushButton("计算") yueJiangHBoxLayout.addWidget(yueJiangbutton) rightVBoxLayout.addLayout(yueJiangHBoxLayout) rightVBoxLayout.addWidget(self.yueJiang) self.zhanShi = QtWidgets.QComboBox() self.zhanShi.addItems(DiZHiList) rightVBoxLayout.addWidget(QtWidgets.QLabel("占时")) rightVBoxLayout.addWidget(self.zhanShi) self.zhouZhan = QtWidgets.QComboBox() self.zhouZhan.addItems(["是", "否"]) rightVBoxLayout.addWidget(QtWidgets.QLabel("昼占/昼生人")) rightVBoxLayout.addWidget(self.zhouZhan) self.mingJu = QtWidgets.QComboBox() self.mingJu.addItems(["否", "是"]) rightVBoxLayout.addWidget(QtWidgets.QLabel("命局")) rightVBoxLayout.addWidget(self.mingJu) man = QtWidgets.QRadioButton("男") male = QtWidgets.QRadioButton("女") man.setChecked(True) self.sex = QtWidgets.QButtonGroup() self.sex.addButton(man, 0) self.sex.addButton(male, 1) sexLayout = QtWidgets.QHBoxLayout() sexLayout.addWidget(man) sexLayout.addWidget(male) rightVBoxLayout.addLayout(sexLayout) self.shengNianInput = QtWidgets.QLineEdit() self.shengNianInput.setPlaceholderText("生年") self.shengNianInput.setValidator( QtGui.QIntValidator(1920, 2050, self.shengNianInput)) rightVBoxLayout.addWidget(self.shengNianInput) rightVBoxLayout.addWidget(QtWidgets.QLabel("占测之事")) self.占测的事Input = QtWidgets.QLineEdit() rightVBoxLayout.addWidget(self.占测的事Input) button = QtWidgets.QPushButton("起六壬局") rightVBoxLayout.addWidget(button) shenShaButton = QtWidgets.QPushButton("神煞查询") rightVBoxLayout.addWidget(shenShaButton) helpButton = QtWidgets.QPushButton("帮助") rightVBoxLayout.addWidget(helpButton) rightVBoxLayout.addStretch() # 设置默认时间 self.timeNow() 月将 = GetLi(int(self.yearInput.text()), int(self.monthInput.text()), int(self.dayInput.text()), int(self.hourInput.text()), int(self.minutesInput.text()), int(self.secondInput.text()))[4] self.yueJiang.setCurrentIndex(月将.num - 1) button.clicked.connect(self.onclick) helpButton.clicked.connect(self.helpOnclick) yueJiangbutton.clicked.connect(self.yueJiangOnClick) shenShaButton.clicked.connect(self.shenShaOnclick) timeNowButton.clicked.connect(self.timeNowOnClick)
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionShow.triggered.connect(self.toggle_mode) self.ui.actionSave.triggered.connect(self.save_note) self.ui.actionLoadShelf.triggered.connect(self.download_shelf) self.ui.actionLoadHot.triggered.connect(self.show_hot_note) self.ui.actionLoadNotes.triggered.connect(self.download_notes) self.ui.statusBar.hide() self.pbar = QProgressBar(self) self.pbar.setFixedWidth(500) self.ui.statusBar.addWidget(self.pbar) icon = QtGui.QIcon() icon.addPixmap( QtGui.QPixmap(os.path.join(root_path, "static/icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) self.browser = QWebEngineView(self) self.browser.setGeometry( 0, self.ui.menubar.height(), self.width(), self.height() - self.ui.menubar.height(), ) self.ui.actionback.triggered.connect(self.browser.back) self.ui.actionforward.triggered.connect(self.browser.forward) self.ui.actionShelf.triggered.connect(self.view_shelf) self.ui.actionLibrary.triggered.connect(self.view_library) # 加载外部的web页面 self.cache_path = os.path.join(root_path, "cache") if not os.path.exists(self.cache_path): os.mkdir(self.cache_path) # 设置缓存目录 default_profile = QWebEngineProfile.defaultProfile() default_profile.setCachePath(self.cache_path) default_profile.setPersistentStoragePath(self.cache_path) # 记录上次阅读位置 self.history_url_file = os.path.join(self.cache_path,"history.txt") if not os.path.exists(self.history_url_file): url = QUrl("https://weread.qq.com/") else: with open(self.history_url_file,'r') as f: url = QUrl(f.read().strip()) self.browser.urlChanged.connect(self.update_lastpage) # 每次改变都更新还是退出的时候更新 self.browser.load(url) self.model = QStringListModel(self) self.item_model = QStandardItemModel(self) self.select_model = QItemSelectionModel(self.item_model) self.ui.tableView.setModel(self.item_model) self.ui.tableView.setSelectionModel(self.select_model) self.ui.tableView.setAlternatingRowColors(True) self.ui.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.is_reading_mode = True self.note_dir = os.path.join(root_path, "notes") if not os.path.exists(self.note_dir): os.mkdir(self.note_dir) try: self.update_cookies() self.booklist = wereader.get_bookshelf(self.cookies) self.books = itertools.cycle(self.booklist) self.curBook = self.booklist[0] except Exception: self.curBook = None self.booklist = None
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(724, 665) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(".\\ico/vw.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setIconSize(QtCore.QSize(32, 32)) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_3.setObjectName("verticalLayout_3") self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setContentsMargins(-1, -1, -1, 0) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.txt_Find = QtWidgets.QLineEdit(self.centralwidget) self.txt_Find.setObjectName("txt_Find") self.horizontalLayout_3.addWidget(self.txt_Find) self.btn_Find = QtWidgets.QPushButton(self.centralwidget) self.btn_Find.setObjectName("btn_Find") self.horizontalLayout_3.addWidget(self.btn_Find) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.splitter_2 = QtWidgets.QSplitter(self.centralwidget) self.splitter_2.setAutoFillBackground(True) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName("splitter_2") self.splitter = QtWidgets.QSplitter(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.splitter.sizePolicy().hasHeightForWidth()) self.splitter.setSizePolicy(sizePolicy) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName("splitter") self.verticalLayoutWidget_2 = QtWidgets.QWidget(self.splitter) self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2") self.verticalLayout_2 = QtWidgets.QVBoxLayout( self.verticalLayoutWidget_2) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.midleft = QtWidgets.QTreeWidget(self.verticalLayoutWidget_2) self.midleft.setObjectName("midleft") self.midleft.headerItem().setText(0, "1") self.midleft.header().setHighlightSections(True) self.verticalLayout_2.addWidget(self.midleft) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.cb_Tabelle = QtWidgets.QCheckBox(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(14) self.cb_Tabelle.setFont(font) self.cb_Tabelle.setLayoutDirection(QtCore.Qt.LeftToRight) self.cb_Tabelle.setCheckable(True) self.cb_Tabelle.setChecked(False) self.cb_Tabelle.setTristate(False) self.cb_Tabelle.setObjectName("cb_Tabelle") self.horizontalLayout.addWidget(self.cb_Tabelle) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.btn_Update_Tree = QtWidgets.QPushButton( self.verticalLayoutWidget_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.btn_Update_Tree.sizePolicy().hasHeightForWidth()) self.btn_Update_Tree.setSizePolicy(sizePolicy) self.btn_Update_Tree.setText("") icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(".\\ico/ARROW6A.ICO"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_Update_Tree.setIcon(icon1) self.btn_Update_Tree.setIconSize(QtCore.QSize(32, 32)) self.btn_Update_Tree.setObjectName("btn_Update_Tree") self.horizontalLayout.addWidget(self.btn_Update_Tree) self.verticalLayout_2.addLayout(self.horizontalLayout) self.verticalLayoutWidget = QtWidgets.QWidget(self.splitter) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.botleft = QtWidgets.QTreeWidget(self.verticalLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(2) sizePolicy.setHeightForWidth( self.botleft.sizePolicy().hasHeightForWidth()) self.botleft.setSizePolicy(sizePolicy) self.botleft.setObjectName("botleft") self.botleft.headerItem().setText(0, "1") self.verticalLayout.addWidget(self.botleft) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.cb_PR = QtWidgets.QCheckBox(self.verticalLayoutWidget) font = QtGui.QFont() font.setPointSize(14) self.cb_PR.setFont(font) self.cb_PR.setObjectName("cb_PR") self.horizontalLayout_2.addWidget(self.cb_PR) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.btn_Dump_pr = QtWidgets.QPushButton(self.verticalLayoutWidget) self.btn_Dump_pr.setText("") icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(".\\ico/ARROW6C.ICO"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_Dump_pr.setIcon(icon2) self.btn_Dump_pr.setIconSize(QtCore.QSize(32, 32)) self.btn_Dump_pr.setObjectName("btn_Dump_pr") self.horizontalLayout_2.addWidget(self.btn_Dump_pr) self.btn_Inject_pr = QtWidgets.QPushButton(self.verticalLayoutWidget) self.btn_Inject_pr.setText("") icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(".\\ico/ARROW6D.ICO"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_Inject_pr.setIcon(icon3) self.btn_Inject_pr.setIconSize(QtCore.QSize(32, 32)) self.btn_Inject_pr.setObjectName("btn_Inject_pr") self.horizontalLayout_2.addWidget(self.btn_Inject_pr) self.btn_Update_PrNr = QtWidgets.QPushButton(self.verticalLayoutWidget) self.btn_Update_PrNr.setText("") self.btn_Update_PrNr.setIcon(icon1) self.btn_Update_PrNr.setIconSize(QtCore.QSize(32, 32)) self.btn_Update_PrNr.setObjectName("btn_Update_PrNr") self.horizontalLayout_2.addWidget(self.btn_Update_PrNr) self.verticalLayout.addLayout(self.horizontalLayout_2) self.textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.textEdit.sizePolicy().hasHeightForWidth()) self.textEdit.setSizePolicy(sizePolicy) self.textEdit.setObjectName("textEdit") self.verticalLayout.addWidget(self.textEdit) self.topright = QWebEngineView(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(2) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.topright.sizePolicy().hasHeightForWidth()) self.topright.setSizePolicy(sizePolicy) self.topright.setObjectName("topright") self.verticalLayout_3.addWidget(self.splitter_2) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 724, 23)) self.menubar.setObjectName("menubar") self.menu = QtWidgets.QMenu(self.menubar) self.menu.setObjectName("menu") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.openMenu = QtWidgets.QAction(MainWindow) self.openMenu.setObjectName("openMenu") self.menu.addAction(self.openMenu) self.menubar.addAction(self.menu.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)
class mainWindowWidget(QMainWindow): currentScanID = 0 image_source = None currentOCRSourceLanguageIndex = 0 lastOpenedDirectory = os.path.expanduser("~\\Pictures") def __init__(self, *args, **kwargs): super(mainWindowWidget, self).__init__(*args, **kwargs) self.setWindowTitle("B-25 UNITED") windowWidth_noImage = 100 + 150 + 100 + 150 + 100 self.setFixedSize(windowWidth_noImage, 70 + 60) self.screenRegionWindow = screenRegionPromptWidget() self.topbarItems = QLabel(self, objectName="topbarItemsContainer") self.topbarItems.setFixedSize(windowWidth_noImage - 4, 50 - 4) self.topbarItems.move(3, 3) self.screenSnipButton = QPushButton("CAPTURE", self.topbarItems, objectName="screenSnipButton") self.screenSnipButton.clicked.connect(self.newSnipPressed) self.screenSnipButton.setFont(QFont("Gotham", 20, 1000, False)) self.screenSnipButton.setFixedSize(200, 50 - 12) self.screenSnipButton.move(7, 7) self.screenSnipButton = QPushButton("Contact US", self.topbarItems, objectName="nopen_webbrowser") self.screenSnipButton.clicked.connect(self.open_webbrowser) self.screenSnipButton.setFont(QFont("Gotham", 10, 1000, False)) self.screenSnipButton.setFixedSize(180, 50 - 12) self.screenSnipButton.move(30 + 190 + 30, 7) self.openImageButton = QPushButton("VIEW", self.topbarItems, objectName="openImageButton") self.openImageButton.clicked.connect(self.openImagePressed) self.openImageButton.setFont(QFont("Gotham", 20, 1000, False)) self.openImageButton.setFixedSize(120, 50 - 10) self.openImageButton.move(60 + 350 + 60, 7) self.basicButtonLabels = QLabel( "CAPTURE: screenshot ke liye ye use karo \nVIEW: direct image read karne ke liye", self, objectName="basicButtonLabels") self.basicButtonLabels.setFont(QFont("Gotham", 11, 100, False)) self.basicButtonLabels.setFixedSize(250 + 10 + 250, 50) self.basicButtonLabels.move(6, 50) self.imagePreview = QLabel("", self, objectName="imagePreview") self.imagePreview.hide() self.outputWindow = outputWindowWidget() self.outputWindow.hide() self.setStyleSheet(mainWindow_CSS) def newSnipPressed(self): self.hide() self.outputWindow.close() self.screenRegionWindow.promptForRegion( callback=self.gotScreenRegionForSnip) def open_webbrowser(self): self.web = QWebView() self.web.load(QUrl("https://www.pocketape.com")) self.web.show() def openImagePressed(self): dialogTitle = "VIEW IMAGE" openInDirectory = self.lastOpenedDirectory acceptedFiles = "Image files (*.png *.jpeg *jpg)" (fname, x) = QFileDialog.getOpenFileName(self, dialogTitle, openInDirectory, acceptedFiles) if x == '': return else: img = None try: self.lastOpenedDirectory = str(pathlib.Path(fname).parent) pic = PIL.Image.open(fname) img = np.array(pic) if img.shape[-1] == 4: img = img[:, :, :3] except BaseException as e: print("Failed to open image: %s" % str(e)) self.newImage(img) def startOCR(self, image, id, language): text = None try: text = getTextFromImg(image, timeout=120, language=language['code']) except BaseException as e: if "Tesseract process timeout" in str(e): if id != self.currentScanID: return return self.outputWindow.ocrStatusChangeSignal.emit( id, OCRSTATUS_TIMEOUT, str(e)) else: if id != self.currentScanID: return return self.outputWindow.ocrStatusChangeSignal.emit( id, OCRSTATUS_ERROR, str(e)) if id != self.currentScanID: return if text is None: text = "" return self.outputWindow.ocrStatusChangeSignal.emit( id, OCRSTATUS_FINISH, str(text)) def gotScreenRegionForSnip(self, region): if region is None: print("Screen Snip CANCELED") self.show() else: img = screenshotRegion(region) self.show() if img.shape[-1] == 4: # drop alpha channel img = img[:, :, :3] img = img[:, :, ::-1] # BGR -> RGB self.newImage(img) def newImage(self, img): self.image_source = img self.newOCR() def newOCR(self): if self.image_source is None: return self.currentScanID += 1 if self.currentScanID == 1: self.basicButtonLabels.hide() self.imagePreview.show() self.topbarItems.setFixedSize(3 + 100 + 3 + 100 + 3 + 200 + 3, 50 - 6) language = None if self.currentOCRSourceLanguageIndex < len(supportedOCRLanguages): language = supportedOCRLanguages[ self.currentOCRSourceLanguageIndex] else: language = supportedOCRScripts[self.currentOCRSourceLanguageIndex - len(supportedOCRLanguages) - 1] # show image h, w, ch = self.image_source.shape qimg = QImage(self.image_source.data.tobytes(), w, h, ch * w, QImage.Format_RGB888) self.imagePreview.setPixmap(QPixmap.fromImage(qimg)) self.imagePreview.setFixedSize(w, h) # resize main window topbarWidth = 30 + 200 + 30 + 300 + 30 + 200 + 30 imageWidth = w imagePosition = 3 topbarPosition = 3 windowWidth = 300 if topbarWidth == imageWidth: imagePosition = topbarPosition = 3 windowWidth = 3 + topbarWidth + 3 elif topbarWidth > imageWidth: topbarPosition = 3 imagePosition = 3 + (topbarWidth - imageWidth) / 2 windowWidth = 3 + topbarWidth + 3 else: #if topbarWidth < imageWidth: imagePosition = 3 topbarPosition = 3 + (imageWidth - topbarWidth) / 2 windowWidth = 3 + imageWidth + 3 self.imagePreview.move(math.floor(imagePosition), 50) self.topbarItems.move(math.floor(topbarPosition), 3) self.setFixedSize(math.ceil(windowWidth), 53 + h) # notify outputWindow to get ready, and begin OCR self.outputWindow.ocrStatusChangeSignal.emit(self.currentScanID, OCRSTATUS_BEGIN, language['name']) threading.Thread( target=self.startOCR, args=[self.image_source, self.currentScanID, language]).start() def closeEvent(self, event): self.outputWindow.kill() self.screenRegionWindow.active = False self.screenRegionWindow.close()
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()
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton from PyQt5.QtWebEngineWidgets import QWebEngineView import sys # 创建一个 application实例 app = QApplication(sys.argv) win = QWidget() win.setWindowTitle('Web页面中的JavaScript与 QWebEngineView交互例子') # 创建一个垂直布局器 layout = QVBoxLayout() win.setLayout(layout) # 创建一个 QWebEngineView 对象 view = QWebEngineView() view.setHtml(''' <html> <head> <title>A Demo Page</title> <script language="javascript"> // Completes the full-name control and // shows the submit button function completeAndReturnName() { alert('Call javascriptFunction' ); var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var full = fname + ' ' + lname; document.getElementById('fullname').value = full;
class Ui_Dialog(object): def setupUi(self, Dialog, exchange: str, ticker: str): #récupération du chemin self.mypath = os.path.dirname(__file__) self.exchange = exchange self.ticker = ticker graphics.chart(self.exchange, self.ticker, '1h', self.mypath) Dialog.setObjectName("Dialog") Dialog.resize(1355, 706) Dialog.setStyleSheet("background-color: rgb(189, 255, 231);\n" "") self.graphTo1h = QtWidgets.QPushButton(Dialog) self.graphTo1h.setGeometry(QtCore.QRect(1140, 60, 141, 23)) self.graphTo1h.setWhatsThis("") self.graphTo1h.setStyleSheet("background-color: rgb(255, 255, 255);") self.graphTo1h.setObjectName("graphTo1h") self.graphTo1h.clicked.connect(self.GraphTo1h) self.graphTo24h = QtWidgets.QPushButton(Dialog) self.graphTo24h.setGeometry(QtCore.QRect(1140, 110, 141, 23)) self.graphTo24h.setWhatsThis("") self.graphTo24h.setStyleSheet("background-color: rgb(255, 255, 255);") self.graphTo24h.setObjectName("graphTo24h") self.graphTo24h.clicked.connect(self.GraphTo24h) self.graphTo7d = QtWidgets.QPushButton(Dialog) self.graphTo7d.setGeometry(QtCore.QRect(1140, 160, 141, 23)) self.graphTo7d.setWhatsThis("") self.graphTo7d.setStyleSheet("background-color: rgb(255, 255, 255);") self.graphTo7d.setObjectName("graphTo7d") self.graphTo7d.clicked.connect(self.GraphTo7d) self.BUY_SELL = QtWidgets.QPushButton(Dialog) self.BUY_SELL.setGeometry(QtCore.QRect(1160, 440, 171, 31)) self.BUY_SELL.setStyleSheet("background-color: rgb(255, 255, 255);") self.BUY_SELL.setObjectName("BUY_SELL") self.BUY_SELL.clicked.connect(self.openBuySell) self.Htmlreader_graph = QWebEngineView(Dialog) self.Htmlreader_graph.setGeometry(QtCore.QRect(10, 10, 1051, 661)) self.Htmlreader_graph.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor)) self.Htmlreader_graph.setWhatsThis("") self.Htmlreader_graph.setAutoFillBackground(False) #récupération du chemin self.Htmlreader_graph.setUrl(QtCore.QUrl("file:/plotlyGraph.html")) self.Htmlreader_graph.setObjectName("Htmlreader_graph") self.Timeframe = QtWidgets.QLabel(Dialog) self.Timeframe.setGeometry(QtCore.QRect(1150, 20, 111, 31)) font = QtGui.QFont() font.setFamily("MS Sans Serif") font.setPointSize(15) font.setBold(True) font.setItalic(True) font.setWeight(75) self.Timeframe.setFont(font) self.Timeframe.setObjectName("Timeframe") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) #fonction pour changer le timeframe du graph: #1h def GraphTo1h(Ui_Dialog): graphics.chart(Ui_Dialog.exchange, Ui_Dialog.ticker, '1h', Ui_Dialog.mypath) Ui_Dialog.Htmlreader_graph.reload() #24h def GraphTo24h(Ui_Dialog): graphics.chart(Ui_Dialog.exchange, Ui_Dialog.ticker, '1d', Ui_Dialog.mypath) Ui_Dialog.Htmlreader_graph.reload() #7d def GraphTo7d(Ui_Dialog): graphics.chart(Ui_Dialog.exchange, Ui_Dialog.ticker, '7d', Ui_Dialog.mypath) Ui_Dialog.Htmlreader_graph.reload() #•ouvre la fenetre BUY/SELL def openBuySell(self): self.window = QtWidgets.QMainWindow() self.ui = BuysellWindow.Ui_Dialog() self.ui.setupUi(self.window, self.exchange, self.ticker) self.window.show() def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.graphTo1h.setText(_translate("Dialog", "1 hour")) self.graphTo24h.setText(_translate("Dialog", "24 hours")) self.graphTo7d.setText(_translate("Dialog", "7 days")) self.BUY_SELL.setText(_translate("Dialog", "Buy/Sell")) self.Timeframe.setText(_translate("Dialog", "Timeframe:"))
def __init__(self, parent=None): QWebEngineView.__init__(self, parent) self.settings = QWebEngineSettings.globalSettings() self.settings.setAttribute(QWebEngineSettings.LocalContentCanAccessFileUrls, True)
def open_webbrowser(self): self.web = QWebView() self.web.load(QUrl("https://www.pocketape.com")) self.web.show()
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/"))
class E5GoogleMailAuthBrowser(QDialog): """ Class implementing a simple web browser to perform the OAuth2 authentication process. @signal approvalCodeReceived(str) emitted to indicate the receipt of the approval code """ approvalCodeReceived = pyqtSignal(str) def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(E5GoogleMailAuthBrowser, self).__init__(parent) self.__layout = QVBoxLayout(self) from PyQt5.QtWebEngineWidgets import QWebEngineView self.__browser = QWebEngineView(self) self.__browser.titleChanged.connect(self.__titleChanged) self.__browser.loadFinished.connect(self.__pageLoadFinished) self.__layout.addWidget(self.__browser) self.__buttonBox = QDialogButtonBox(QDialogButtonBox.Close) self.__buttonBox.rejected.connect(self.reject) self.__layout.addWidget(self.__buttonBox) self.resize(600, 700) @pyqtSlot(str) def __titleChanged(self, title): """ Private slot handling changes of the web page title. @param title web page title @type str """ self.setWindowTitle(title) @pyqtSlot() def __pageLoadFinished(self): """ Private slot handling the loadFinished signal. """ url = self.__browser.url() if url.toString().startswith( "https://accounts.google.com/o/oauth2/approval/v2"): urlQuery = QUrlQuery(url) approvalCode = urlQuery.queryItemValue("approvalCode", QUrl.FullyDecoded) if approvalCode: self.approvalCodeReceived.emit(approvalCode) self.close() def load(self, url): """ Public method to start the authorization flow by loading the given URL. @param url URL to be laoded @type str or QUrl """ self.__browser.setUrl(QUrl(url))
def contentWidget(self): # select region v box 1 select_region_h_box1 = QHBoxLayout() # selection one notice select_region_h_box1.addSpacing(10) # selection label 1 self.select_region_label = QLabel("Select Region", self) select_region_h_box1.addWidget(self.select_region_label) # drop down button self.select_region_combo = QComboBox(self) self.select_region_combo.addItems(self.italy_regions) select_region_h_box1.addWidget(self.select_region_combo) # push button self.select_region_botton = QPushButton("Check Region", self) self.select_region_botton.pressed.connect(self.italyRegionClicked) select_region_h_box1.addWidget(self.select_region_botton) # select region v box 2 select_region_h_box2 = QHBoxLayout() select_region_h_box2.addSpacing(10) # selection label 1 self.select_region_label = QLabel("Italy against", self) select_region_h_box2.addWidget(self.select_region_label) # drop down button (combo ) self.select_euro_combo = QComboBox(self) self.select_euro_combo.addItems(self.european_countries) select_region_h_box2.addWidget(self.select_euro_combo) # push button self.compare_button = QPushButton("Compare", self) self.compare_button.pressed.connect(self.europeanCountriesClicked) select_region_h_box2.addWidget(self.compare_button) # selection main V box select_region_main_v_box = QVBoxLayout() # An overall language pull down menu is being requested at the very top of the GUI # with the option of English and Italian labelling language_h_box = QHBoxLayout() self.language_lbl = QLabel("Select Language", self) self.language_combobox = QComboBox() # language option options = ([ ('English', 'en'), ('Italian', 'it'), ('Spanish', 'es'), ('Chinese', 'zh-CN'), ]) # add language and change language for i, (text, lang) in enumerate(options): self.language_combobox.addItem(text) self.language_combobox.setItemData(i, lang) language_h_box.addWidget(self.language_lbl) # on index changed self.language_combobox.currentIndexChanged.connect( self.languageChanged) language_h_box.addWidget(self.language_combobox) language_h_box.addStretch() # add language_h_box layout select_region_main_v_box.addLayout(language_h_box) # Italy Region Covid Report self.italy_lbl = QLabel("Italy Region Covid Report", self) self.italy_lbl.setStyleSheet("border: 0.5px solid gray") select_region_main_v_box.addWidget(self.italy_lbl) select_region_main_v_box.addLayout(select_region_h_box1) select_region_main_v_box.setSpacing(15) self.euro_text = QLabel( "Italy Covid report against European countries", self) self.euro_text.setStyleSheet("border: 0.5px solid gray") select_region_main_v_box.addWidget(self.euro_text) select_region_main_v_box.addLayout(select_region_h_box2) select_region_main_v_box.addStretch() # for region map and demographic region_map_box = QVBoxLayout() self.coordinate_title = "This is a title" self.coordinate = coordinate['Campania'] m = folium.Map(tiles="Stamen Terrain", zoom_start=6, location=self.coordinate) # create HTML for pop up def foliumHtml(lo): # get stats if lo != "Italy": stats = self.core.getRegionStats(str(lo)) return f""" <h1 style='color:#7b113a;'> {lo} </h1> <hr/> <p style='color:#7b113a;font-size:20px;'>Region Population: {stats['region_population']}</p> <p style='color:#7b113a;font-size:20px;'>Total Covid Case: {stats['case_number']}</p> <p style='color:#7b113a;font-size:20px;'>Daily Cases: {stats['expectedChanges']}</p> <p style='color:#7b113a;font-size:20px;'>Percentage: {stats['percentage']}%</p> """ else: return f""" <h1> {lo}</h1> <p>European country with a long Mediterranean coastline, has left a powerful mark on Western culture and cuisine.</p> """ # add marker one by one on the map for lo in coordinate: # add pop ups html = foliumHtml(lo) iframe = folium.IFrame(html=html, width=300, height=250) popUp = folium.Popup(iframe, max_width=2650) # Marker starts here folium.Marker(location=coordinate[lo], popup=popUp, icon=folium.DivIcon(html=f""" <div><svg> <circle cx="50" cy="50" r="40" fill="#7b113a" opacity=".4"/> <rect x="35", y="35" width="30" height="30", fill="#fff600", opacity=".3" </svg></div>""")).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()) region_map_box.addWidget(webView) # main box top - bottom h_box = QHBoxLayout() h_box.addLayout(select_region_main_v_box) h_box.addLayout(region_map_box) self.setLayout(h_box)
class win(QMainWindow): def link(self, linkStr): QDesktopServices.openUrl(QUrl(linkStr)) def __init__(self, parent=None): super().__init__(parent) self.tit = "VS- The MASTER MIND" self.top = 100 self.bot = 80 self.wid = 1000 self.hei = 650 self.hello() def hello(self): self.push1 = QPushButton("-> Download <-", self) self.push1.setGeometry(515, 300, 110, 30) self.push1.clicked.connect(self.down) self.push2 = QPushButton("-> MASK <-", self) self.push2.setGeometry(515, 350, 100, 30) # self.push2.clicked.connect(self.thug) self.push2.clicked.connect(self.filter) self.dod = Thuggmask(self) self.push3 = QPushButton("-> Chat Bot <-", self) self.push3.setGeometry(515, 400, 110, 30) self.push4 = QPushButton("-> Calculator <-", self) self.push4.setGeometry(515, 450, 110, 30) self.push4.clicked.connect(self.calc) self.dia2 = calcu(self) # self.push4.clicked.connect(self.but) self.push4 = QPushButton("-> SnapShot <-", self) self.push4.move(520, 500) self.push4.clicked.connect(self.capture) self.push5 = QPushButton("-> Camera <-", self) self.push5.move(520, 550) self.push5.clicked.connect(self.cam) self.push6 = QPushButton("-> Face and Eye detector <-", self) self.push6.setGeometry(470, 600, 200, 30) self.push6.clicked.connect(self.detect) self.push7 = QPushButton("Login", self) self.push7.move(900, 60) self.push7.clicked.connect(self.but) self.dialog = second(self) self.push8 = QPushButton("Sign Up", self) self.push8.move(800, 60) self.push8.clicked.connect(self.jojo) self.d1 = third(self) self.label4 = QLabel("ok", self) self.label4.setGeometry(10, 15, 100, 100) self.label4.linkActivated.connect(self.li) self.label4.setText('<a href="http://google.com/">Google</a>') self.label5 = QLabel("ok", self) self.label5.setGeometry(75, 15, 100, 100) self.label5.linkActivated.connect(self.li2) self.label5.setText('<a href="http://facebook.com/">Facebook</a>') self.label6 = QLabel("ok", self) self.label6.setGeometry(150, 15, 100, 100) self.label6.linkActivated.connect(self.li3) self.label6.setText('<a href="http://gmail.com/">Gmail</a>') self.label51 = QLabel("ok", self) self.label51.setGeometry(200, 15, 100, 100) self.label51.linkActivated.connect(self.li4) self.label51.setText('<a href="https://www.wikipedia.org/">Wiki</a>') self.labeel = QLabel("Contact Us : +91 8800338836", self) self.labeel.setGeometry(15, 620, 200, 20) self.label51 = QLabel("ok", self) self.label51.setGeometry(750, 580, 200, 100) self.label51.linkActivated.connect(self.li5) self.label51.setText( '<a href="https://www.gmail.com/">[email protected]</a>') self.la = QLabel("EMail-", self) self.la.move(693, 615) self.lk = QLabel(self) self.lk.setPixmap(QPixmap("vai.png")) self.lk.setGeometry(250, 50, 600, 200) self.lk1 = QLabel(self) self.lk1.setPixmap(QPixmap("robo.png")) self.lk1.setGeometry(50, 200, 250, 400) self.lk2 = QLabel(self) self.lk2.setPixmap(QPixmap("robo.png")) self.lk2.setGeometry(680, 200, 600, 400) # toolbar self.nav = QToolBar("Navigation") self.nav.setIconSize(QSize(50, 50)) self.addToolBar(self.nav) self.url = QLineEdit(self) self.nav.addSeparator() self.nav.addWidget(self.url) label = QLabel("<h1>THE MASTER MIND</h1>", self) label.setGeometry(380, 180, 350, 150) self.setWindowIcon(QtGui.QIcon('save.png')) menu = self.menuBar() # self.lab=QLabel(self) # self.lab.setPixmap(QPixmap('images.jpeg')) # self.lab.setGeometry(300,80,600,100) file = menu.addMenu("File") # file1=file.addMenu("Open files") edit = menu.addMenu("Edit") View = menu.addMenu("View") nav = menu.addMenu("Navigate") tools = menu.addMenu("Tools") helpo = menu.addMenu("Help") add = QAction('Open Files', self) add.triggered.connect(self.oko) file.addAction(add) close = QAction("Close Window", self) close.triggered.connect(self.sure) file.addAction(close) self.setWindowTitle(self.tit) self.setGeometry(self.top, self.bot, self.wid, self.hei) self.show() def oko(self): type = QFileDialog.getOpenFileName(self, "Open", "/home") if type[0]: g = open(type[0], 'r') with g: data = g.read() # self.text.setText(data) def sure(self): msg = QMessageBox.question(self, "close", "DO u want to close", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if msg == QMessageBox.Yes: self.close() def cam(self): img = cv2.VideoCapture(0) four = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi', four, 20.0, (640, 480)) while True: ret, cap = img.read() grey = cv2.cvtColor(cap, cv2.COLOR_BGR2GRAY) cv2.imshow("dfd", cap) cv2.imshow("asa", grey) if cv2.waitKey(1) == 27: break out.release() img.release() # img=cv2.VideoCapture(0) # while True: # ret,cap=img.read() # cv2.imshow("camera",cap) # cv2.waitKey(1) # img.release() def capture(self): # count=0 img1 = cv2.VideoCapture(0) ret, cap = img1.read() cv2.imshow("Capture", cap) # date=QDateTime.currentDateTime() cv2.imwrite("Images/" + "images.jpeg", cap) cv2.waitKey(0) def but(self): self.hide() self.dialog.show() def jojo(self): self.hide() self.d1.show() def down(self): url = "" s = int(input("ENter how many files u want to downloaded ? ")) for i in range(s): fname = "media/" + str(i) + url.split("/")[-1] Thread(target=lambda: request.urlretrieve(url, "abc.mp4")).start() def calc(self): self.hide() self.dia2.show() def detect(self): eyes = cv2.CascadeClassifier("haarcascade_eye.xml") face = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") img = cv2.VideoCapture(0) while True: ret, cap = img.read() grey = cv2.cvtColor(cap, cv2.COLOR_RGB2GRAY) faces = face.detectMultiScale(grey, 2, 5) for (x, y, w, h) in faces: cv2.rectangle(cap, (x, y), (x + w, y + h), (0, 0, 255), 4) greyFace = grey[y:y + h, x:x + w] eye = eyes.detectMultiScale(greyFace, 2, 5) for (x1, y1, w1, h1) in eye: cv2.rectangle(cap, (x + x1, y + y1), (x + x1 + w1, y + y1 + h1), (0, 0, 255), 4) cv2.imshow("Image", cap) if cv2.waitKey(1) == 27: break # cap.release() # cv2.destroyAllWindows() def li(self): self.browser = QWebEngineView() self.browser.setUrl(QUrl("https://www.google.com/")) self.setCentralWidget(self.browser) nav = QToolBar("Navigation") nav.setIconSize(QSize(20, 20)) self.addToolBar(nav) def li2(self): self.browser = QWebEngineView() self.browser.setUrl(QUrl("https://www.facebook.com/")) self.setCentralWidget(self.browser) nav = QToolBar("Navigation") nav.setIconSize(QSize(20, 20)) self.addToolBar(nav) def li3(self): self.browser = QWebEngineView() self.browser.setUrl(QUrl("https://www.gmail.com/")) self.setCentralWidget(self.browser) nav = QToolBar("Navigation") nav.setIconSize(QSize(20, 20)) self.addToolBar(nav) def li4(self): self.browser = QWebEngineView() self.browser.setUrl(QUrl("https://www.wikipedia.org/")) self.setCentralWidget(self.browser) nav = QToolBar("Navigation") nav.setIconSize(QSize(20, 20)) self.addToolBar(nav) def li5(self): self.browser = QWebEngineView() self.browser.setUrl(QUrl("https://www.gmail.com/")) self.setCentralWidget(self.browser) nav = QToolBar("Navigation") nav.setIconSize(QSize(20, 20)) self.addToolBar(nav) def filter(self): self.hide() self.dod.show()
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 Lookup(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self.is_visible = False self.selected_text = '' self.current_query = '' self.current_source = '' self.l = l = QVBoxLayout(self) self.h = h = QHBoxLayout() l.addLayout(h) self.debounce_timer = t = QTimer(self) t.setInterval(150), t.timeout.connect(self.update_query) self.source_box = sb = QComboBox(self) self.label = la = QLabel(_('Lookup &in:')) h.addWidget(la), h.addWidget(sb), la.setBuddy(sb) self.view = QWebEngineView(self) self._page = Page(create_profile(), self.view) secure_webengine(self._page, for_viewer=True) self.view.setPage(self._page) l.addWidget(self.view) self.populate_sources() self.source_box.currentIndexChanged.connect(self.source_changed) self.view.setHtml('<p>' + _('Double click on a word in the book\'s text' ' to look it up.')) self.add_button = b = QPushButton(QIcon(I('plus.png')), _('Add more sources')) b.clicked.connect(self.add_sources) l.addWidget(b) def add_sources(self): if SourcesEditor(self).exec_() == QDialog.Accepted: self.populate_sources() self.source_box.setCurrentIndex(0) self.update_query() def source_changed(self): s = self.source if s is not None: vprefs['lookup_location'] = s['name'] self.update_query() def populate_sources(self): sb = self.source_box sb.clear() sb.blockSignals(True) for item in vprefs['lookup_locations']: sb.addItem(item['name'], item) idx = sb.findText(vprefs['lookup_location'], Qt.MatchExactly) if idx > -1: sb.setCurrentIndex(idx) sb.blockSignals(False) def visibility_changed(self, is_visible): self.is_visible = is_visible self.update_query() @property def source(self): idx = self.source_box.currentIndex() if idx > -1: return self.source_box.itemData(idx) @property def url_template(self): idx = self.source_box.currentIndex() if idx > -1: return self.source_box.itemData(idx)['url'] def update_query(self): self.debounce_timer.stop() query = self.selected_text or self.current_query if self.current_query == query and self.current_source == self.url_template: return if not self.is_visible or not query: return self.current_source = self.url_template url = self.current_source.format(word=query) self.view.load(QUrl(url)) self.current_query = query def selected_text_changed(self, text): self.selected_text = text or '' self.debounce_timer.start()
class Buscador(QWidget): def __init__(self): super().__init__() #DIMENSIONES Y TÍTULO DE LA VENTANA self.resize(740, 520) self.setWindowTitle('My web browser') #ENTRADA PARA BUSQUEDA. page = "https://www.google.com" self.url = QLineEdit(page) self.url.setPlaceholderText(page) #BOTÓN "Ir". self.go = QPushButton("Ir") self.go.clicked.connect(self.btnIrClicked) #AÑADIMOS ELEMENTOS CREADOS self.nav_bar = QHBoxLayout() self.nav_bar.addWidget(self.url) self.nav_bar.addWidget(self.go) #BARRA DE PROGRESO self.progress = QProgressBar() self.progress.setValue(0) html = """ <!DOCTYPE HTML> <html> <head> <title>PyChrome</title> </head> <body> <style> *{ font-family: Arial; } </style> <h1>Bienvenido a QtSearch.</h1> <img src=""/> <p>QtSearch es un navegador creado para "El Programador Chapuzas".</p> </body> </html> """ #ESPACIO PARA VISIONAR LAS PÁGINAS self.web_view = QWebEngineView() self.web_view.loadProgress.connect(self.webLoading) self.web_view.setHtml(html) #INCLUIMOS "WIDGETS" CREADOS. root = QVBoxLayout() root.addLayout(self.nav_bar) root.addWidget(self.web_view) root.addWidget(self.progress) self.setLayout(root) #FUNCIÓN PARA REALIZAR BÚSQUEDA def btnIrClicked(self, event): url = QUrl(self.url.text()) self.web_view.page().load(url) #FUNCIÓN PARA ACTUALIZAR BARRA DE PROGRESO def webLoading(self, event): self.progress.setValue(event)
class Web(QMdiSubWindow, form_Web.Ui_frmWeb): resized = pyqtSignal() def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.mdiParent = "" self.setWindowIcon(QIcon(QPixmap(1, 1))) self.contentType = "Web Page" self.resized.connect(self.resizeMe) self.webView = QWebEngineView(self) self.webView.setObjectName("webView") self.webView.loadFinished.connect(self.LoadFinished) self.webView.loadProgress.connect(self.showLoadProgress) self.title = "" def resizeEvent(self, event): #routine to handle events on objects, like clicks, lost focus, gained forcus, etc. self.resized.emit() return super(self.__class__, self).resizeEvent(event) def resizeMe(self): windowWidth = self.frameGeometry().width() windowHeight = self.frameGeometry().height() self.scrollArea.setGeometry(5, 27, windowWidth - 10, windowHeight - 35) self.webView.setGeometry(5, 27, windowWidth - 10, windowHeight - 35) if self.contentType == "Map": self.webView.adjustSize() self.LoadLocationsMap(self.filter) def html(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) html = """ <!DOCTYPE html> <html> <head> </head> <body> """ myPixmap = self.webView.grab() myPixmap = myPixmap.scaledToWidth(600, Qt.SmoothTransformation) myByteArray = QByteArray() myBuffer = QBuffer(myByteArray) myBuffer.open(QIODevice.WriteOnly) myPixmap.save(myBuffer, "PNG") encodedImage = base64.b64encode(myByteArray) html = html + (""" <img src="data:image/png;base64, """) html = html + str(encodedImage)[1:] html = html + (""" <font size> </body> </html> """) QApplication.restoreOverrideCursor() return (html) def scaleMe(self): fontSize = self.mdiParent.fontSize settings = QWebEngineSettings.globalSettings() settings.setFontSize(QWebEngineSettings.DefaultFontSize, floor(fontSize * 1.6)) scaleFactor = self.mdiParent.scaleFactor windowWidth = 900 * scaleFactor windowHeight = 600 * scaleFactor self.resize(windowWidth, windowHeight) def loadAboutLapwing(self): self.title = "About Lapwing" self.contentType = "About" html = """ <!DOCTYPE html> <html> <head> <title>About Lapwing</title> <meta charset="utf-8"> <style> * { font-family: "Times New Roman", Times, serif; } </style> </head> <body bgcolor="#98FB98"> <h1> Lapwing </h1> """ html = html + "<h3>Version: " + self.mdiParent.versionNumber + "</h3>" html = html + "<h3>Date: " + self.mdiParent.versionDate + "</h3>" html = html + """ <font size='4'> <b> Lapwing is a free, open-source application to analyze personal eBird sightings. <br><br> Created by Richard Trinkner. </b> <h3> Licenses </h3> <p> <ul> <li> Lapwing is licensed under the GNU General Public License, version 3. </li> <li> PyQt, by Riverbank Computing, is licensed under the GNU General Public License. </li> <li> Qt, by the Qt Company, is licensed under the (L)GPL Lesser General Public License. </li> <li> PyInstaller, by the PyInstaller Development Team, Giovanni Bajo and McMillan Enterprise, is licensed under the GPL General Public License. </li> </ul> </font size> </body> </html> """ self.webView.setHtml(html) self.setWindowTitle("About Lapwing") return (True) def LoadWebPage(self, url): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.webView.load(QUrl(url)) self.resizeMe() self.scaleMe() def LoadFinished(self): QApplication.restoreOverrideCursor() def LoadLocationsMap(self, filter): self.title = "Location Map" coordinatesDict = defaultdict() mapWidth = self.frameGeometry().width() - 10 mapHeight = self.frameGeometry().height() - 35 self.scrollArea.setGeometry(5, 27, mapWidth + 2, mapHeight + 2) self.webView.setGeometry(5, 27, mapWidth + 2, mapHeight + 2) self.contentType = "Map" self.filter = filter locations = self.mdiParent.db.GetLocations(filter) if len(locations) == 0: return (False) for l in locations: coordinates = self.mdiParent.db.GetLocationCoordinates(l) coordinatesDict[l] = coordinates html = """ <!DOCTYPE html> <html> <head> <title>Locations Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> * { font-size: 75%; font-family: "Times New Roman", Times, serif; } #map { height: 100%; } html, body { """ html = html + "height: " + str(mapHeight) + "px;" html = html + "width: " + str(mapWidth) + "px;" html = html + """ margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 5 }); var bounds = new google.maps.LatLngBounds(); """ for c in coordinatesDict.keys(): html = html + """ var marker = new google.maps.Marker({ """ html = html + "position: {lat: " + coordinatesDict[c][ 0] + ", lng: " + coordinatesDict[c][1] + "}," html = html + """ map: map, title: """ html = html + '"' + c + '"' html = html + """ }); bounds.extend(marker.getPosition()); """ html = html + """ map.setCenter(bounds.getCenter()); map.fitBounds(bounds); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDjVuwWvZmRlD5n-Jj2Jh_76njXxldDgug&callback=initMap" async defer></script> </body> </html> """ self.webView.setHtml(html) # set window title to descriptive map name locationName = filter.getLocationName( ) # str name of region or location or "" locationType = filter.getLocationType() startDate = filter.getStartDate() # str format yyyy-mm-dd or "" endDate = filter.getEndDate() # str format yyyy-mm-dd or "" startSeasonalMonth = filter.getStartSeasonalMonth() # str format mm startSeasonalDay = filter.getStartSeasonalDay() # str format dd endSeasonalMonth = filter.getEndSeasonalMonth() # str format dd endSeasonalDay = filter.getEndSeasonalDay() # str format dd speciesName = filter.getSpeciesName() # str speciesName family = filter.getFamily() # str family name # set main location label, using "All Locations" if none others are selected windowTitle = speciesName if locationName != "": if locationType == "Country": locationName = self.mdiParent.db.GetCountryName(locationName) if locationType == "State": locationName = self.mdiParent.db.GetStateName(locationName) windowTitle = windowTitle + "; " + locationName if startDate != "": dateTitle = startDate + " to " + endDate if startDate == endDate: dateTitle = startDate windowTitle = windowTitle + "; " + dateTitle # set main seasonal range label, if specified if not ((startSeasonalMonth == "") or (endSeasonalMonth == "")): monthRange = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] rangeTitle = monthRange[ int(startSeasonalMonth) - 1] + "-" + startSeasonalDay + " to " + monthRange[ int(endSeasonalMonth) - 1] + "-" + endSeasonalDay windowTitle = windowTitle + "; " + rangeTitle if family != "": family = family[0:family.index("(") - 1] windowTitle = windowTitle + "; " + family if windowTitle == "": windowTitle = "All species, locations, dates and families" #remove leading "; " if needed if windowTitle[0:2] == "; ": windowTitle = windowTitle[2:] # add location count to window title windowTitle = "Map: " + windowTitle + " (" + str( len(coordinatesDict.keys())) + ")" self.setWindowTitle(windowTitle) icon = QIcon() icon.addPixmap(QPixmap(":/icon_map.png"), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) return (True) def showLoadProgress(self, percent): if percent < 100: self.setWindowTitle(self.title + ": " + str(percent) + "%") else: self.setWindowTitle(self.title)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from PyQt5.QtWidgets import QApplication from PyQt5.QtWebEngineWidgets import QWebEngineView if __name__ == '__main__': app = QApplication([]) view = QWebEngineView() view.show() view.setHtml("""\ <html> <body> <iframe width="560" height="315" src="https://www.youtube.com/embed/Cb-srOfRqNc" frameborder="0" allowfullscreen></iframe> </body> </html> """) 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"
parser = argparse.ArgumentParser() parser.add_argument('url', help='The URL to open') parser.add_argument('--plugins', '-p', help='Enable plugins', default=False, action='store_true') if WEBENGINE: parser.add_argument('--webengine', help='Use QtWebEngine', default=False, action='store_true') return parser.parse_args() if __name__ == '__main__': args = parse_args() app = QApplication(sys.argv) if WEBENGINE and args.webengine: wv = QWebEngineView() else: wv = QWebView() wv.loadStarted.connect(lambda: print("Loading started")) wv.loadProgress.connect(lambda p: print("Loading progress: {}%".format(p))) wv.loadFinished.connect(lambda: print("Loading finished")) if args.plugins and not WEBENGINE: wv.settings().setAttribute(QWebSettings.PluginsEnabled, True) wv.load(QUrl.fromUserInput(args.url)) wv.show() app.exec_()
def visibility_changed(self, visible): if visible and self.view is None: self.view = QWebEngineView(self.view_to_debug) self.view_to_debug.page().setDevToolsPage(self.view.page()) self.layout.addWidget(self.view)
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)
import sys from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView app = QApplication(sys.argv) browser = QWebEngineView() browser.load(QUrl("http://www.baidu.com/")) browser.show() app.exec_()