コード例 #1
0
    def showDocumentation(self):
        if self._documentation is None:
            doc = QWebView(self)
            doc.load(QUrl("doc/html/index.html"))
            self._documentation = QDockWidget("Documentation", self)
            self._documentation.setWidget(doc)
            self._documentation.closeEvent = lambda _: self.hide_documentation()

        self.addDockWidget(Qt.LeftDockWidgetArea, self._documentation)
コード例 #2
0
ファイル: test_pyqt5.py プロジェクト: kamijawa/pi_server
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_())
コード例 #3
0
ファイル: web_browser.py プロジェクト: tody411/PyIntroduction
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_())
コード例 #4
0
ファイル: web.py プロジェクト: zipu/QWebview-plus
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())
コード例 #5
0
ファイル: test_pyqt5.py プロジェクト: kamijawa/pi_server
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_())
コード例 #6
0
ファイル: util.py プロジェクト: hvasbath/pyrocko
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))
コード例 #7
0
import sys

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl

app = QApplication(sys.argv)

browser = QWebEngineView()
browser.load(QUrl('google.com'))
browser.show()

app.exec_()
コード例 #8
0
ファイル: qt502_webviewJs02.py プロジェクト: kiorry/PYQT
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_())
コード例 #9
0
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"))
コード例 #10
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.resize(1000, 600)

        self.back_btn = QPushButton(self)
        self.forward_btn = QPushButton(self)
        self.refresh_btn = QPushButton(self)
        self.zoom_in_btn = QPushButton(self)
        self.zoom_out_btn = QPushButton(self)
        self.url_le = QLineEdit(self)

        self.browser = QWebEngineView()

        self.h_layout = QHBoxLayout()
        self.v_layout = QVBoxLayout()

        self.layout_init()
        self.btn_init()
        self.le_init()
        self.browser_init()

    def layout_init(self):
        self.h_layout.setSpacing(0)
        self.h_layout.addWidget(self.back_btn)
        self.h_layout.addWidget(self.forward_btn)
        self.h_layout.addWidget(self.refresh_btn)
        self.h_layout.addStretch(2)
        self.h_layout.addWidget(self.url_le)
        self.h_layout.addStretch(2)
        self.h_layout.addWidget(self.zoom_in_btn)
        self.h_layout.addWidget(self.zoom_out_btn)

        self.v_layout.addLayout(self.h_layout)
        self.v_layout.addWidget(self.browser)

        self.setLayout(self.v_layout)

    def browser_init(self):
        self.browser.load(QUrl('https://baidu.com'))
        self.browser.urlChanged.connect(
            lambda: self.url_le.setText(self.browser.url().toDisplayString()))

    def btn_init(self):
        self.back_btn.setIcon(QIcon('imgs/back.png'))
        self.forward_btn.setIcon(QIcon('imgs/forward.png'))
        self.refresh_btn.setIcon(QIcon('imgs/refresh.png'))
        self.zoom_in_btn.setIcon(QIcon('imgs/zoom_in.png'))
        self.zoom_out_btn.setIcon(QIcon('imgs/zoom_out.png'))

        self.back_btn.clicked.connect(self.browser.back)
        self.forward_btn.clicked.connect(self.browser.forward)
        self.refresh_btn.clicked.connect(self.browser.reload)
        self.zoom_in_btn.clicked.connect(self.zoom_in_func)
        self.zoom_out_btn.clicked.connect(self.zoom_out_func)

    def le_init(self):
        self.url_le.setFixedWidth(400)
        self.url_le.setPlaceholderText('Search or enter website name')

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == Qt.Key_Return or QKeyEvent.key() == Qt.Key_Enter:
            if self.url_le.hasFocus():
                if self.url_le.text().startswith(
                        'https://') or self.url_le.text().startswith(
                            'http://'):
                    self.browser.load(QUrl(self.url_le.text()))
                else:
                    self.browser.load(QUrl('https://' + self.url_le.text()))

    def zoom_in_func(self):
        self.browser.setZoomFactor(self.browser.zoomFactor() + 0.1)

    def zoom_out_func(self):
        self.browser.setZoomFactor(self.browser.zoomFactor() - 0.1)
コード例 #11
0
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()
コード例 #12
0
ファイル: lookup.py プロジェクト: zieglerm/calibre
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()
コード例 #13
0
ファイル: browser.py プロジェクト: taasan/frescobaldi
class Browser(QWidget):
    """LilyPond documentation browser widget."""
    def __init__(self, dockwidget):
        super(Browser, self).__init__(dockwidget)

        layout = QVBoxLayout(spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.toolbar = tb = QToolBar()
        self.webview = QWebEngineView(self,
                                      contextMenuPolicy=Qt.CustomContextMenu)
        self.webview.setPage(WebEnginePage(self.webview))
        self.chooser = QComboBox(sizeAdjustPolicy=QComboBox.AdjustToContents)
        self.search = SearchEntry(maximumWidth=200)

        layout.addWidget(self.toolbar)
        layout.addWidget(self.webview)

        ac = dockwidget.actionCollection
        ac.help_back.triggered.connect(self.webview.back)
        ac.help_forward.triggered.connect(self.webview.forward)
        ac.help_home.triggered.connect(self.showHomePage)
        ac.help_print.triggered.connect(self.slotPrint)

        self.webview.urlChanged.connect(self.slotUrlChanged)
        self.webview.customContextMenuRequested.connect(
            self.slotShowContextMenu)

        tb.addAction(ac.help_back)
        tb.addAction(ac.help_forward)
        tb.addSeparator()
        tb.addAction(ac.help_home)
        tb.addAction(ac.help_print)
        tb.addSeparator()
        tb.addWidget(self.chooser)
        tb.addWidget(self.search)

        self.chooser.activated[int].connect(self.showHomePage)
        self.search.textChanged.connect(self.slotSearchChanged)
        self.search.returnPressed.connect(self.slotSearchReturnPressed)
        dockwidget.mainwindow().iconSizeChanged.connect(
            self.updateToolBarSettings)
        dockwidget.mainwindow().toolButtonStyleChanged.connect(
            self.updateToolBarSettings)

        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.loadDocumentation()
        self.showInitialPage()
        app.settingsChanged.connect(self.loadDocumentation)
        app.translateUI(self)

    def readSettings(self):
        s = QSettings()
        s.beginGroup("documentation")
        ws = self.webview.page().settings()
        family = s.value("fontfamily", self.font().family(), str)
        size = s.value("fontsize", 16, int)
        ws.setFontFamily(QWebEngineSettings.StandardFont, family)
        ws.setFontSize(QWebEngineSettings.DefaultFontSize, size)
        fixed = textformats.formatData('editor').font
        ws.setFontFamily(QWebEngineSettings.FixedFont, fixed.family())
        ws.setFontSize(QWebEngineSettings.DefaultFixedFontSize,
                       fixed.pointSizeF() * 96 / 72)
        self.webview.page().profile().setHttpAcceptLanguage(','.join(
            lilydoc.network.langs()))

    def keyPressEvent(self, ev):
        if ev.text() == "/":
            self.search.setFocus()
        else:
            super(Browser, self).keyPressEvent(ev)

    def translateUI(self):
        try:
            self.search.setPlaceholderText(_("Search..."))
        except AttributeError:
            pass  # not in Qt 4.6

    def showInitialPage(self):
        """Shows the preferred start page.

        If a local documentation instance already has a suitable version,
        just loads it. Otherwise connects to the allLoaded signal, that is
        emitted when all the documentation instances have loaded their version
        information and then shows the start page (if another page wasn't yet
        loaded).

        """
        if self.webview.url().isEmpty():
            docs = lilydoc.manager.docs()
            version = lilypondinfo.preferred().version()
            index = -1
            if version:
                for num, doc in enumerate(docs):
                    if doc.version() is not None and doc.version() >= version:
                        index = num  # a suitable documentation is found
                        break
            if index == -1:
                # nothing found (or LilyPond version not available),
                # wait for loading or show the most recent version
                if not lilydoc.manager.loaded():
                    lilydoc.manager.allLoaded.connect(self.showInitialPage)
                    return
                index = len(docs) - 1
            self.chooser.setCurrentIndex(index)
            self.showHomePage()

    def loadDocumentation(self):
        """Puts the available documentation instances in the combobox."""
        i = self.chooser.currentIndex()
        self.chooser.clear()
        for doc in lilydoc.manager.docs():
            v = doc.versionString()
            if doc.isLocal():
                t = _("(local)")
            else:
                t = _("({hostname})").format(hostname=doc.url().host())
            self.chooser.addItem("{0} {1}".format(v or _("<unknown>"), t))
        self.chooser.setCurrentIndex(i)
        if not lilydoc.manager.loaded():
            lilydoc.manager.allLoaded.connect(self.loadDocumentation, -1)
            return

    def updateToolBarSettings(self):
        mainwin = self.parentWidget().mainwindow()
        self.toolbar.setIconSize(mainwin.iconSize())
        self.toolbar.setToolButtonStyle(mainwin.toolButtonStyle())

    def showManual(self):
        """Invoked when the user presses F1."""
        self.slotHomeFrescobaldi()  # TEMP

    def slotUrlChanged(self):
        ac = self.parentWidget().actionCollection
        ac.help_back.setEnabled(self.webview.history().canGoBack())
        ac.help_forward.setEnabled(self.webview.history().canGoForward())

    def openUrl(self, url):
        if url.path().endswith(('.ily', '.lyi', '.ly')):
            self.sourceViewer().showReply(lilydoc.network.get(url))
        else:
            self.webview.load(url)

    def slotUnsupported(self, reply):
        helpers.openUrl(reply.url())

    def slotSearchChanged(self):
        text = self.search.text()
        if not text.startswith(':'):
            self.webview.page().findText(text)

    def slotSearchReturnPressed(self):
        text = self.search.text()
        if not text.startswith(':'):
            self.slotSearchChanged()
        else:
            pass  # TODO: implement full doc search

    def sourceViewer(self):
        try:
            return self._sourceviewer
        except AttributeError:
            from . import sourceviewer
            self._sourceviewer = sourceviewer.SourceViewer(self)
            return self._sourceviewer

    def showHomePage(self):
        """Shows the homepage of the LilyPond documentation."""
        i = self.chooser.currentIndex()
        if i < 0:
            i = 0
        doc = lilydoc.manager.docs()[i]

        url = doc.home()
        if doc.isLocal():
            path = url.toLocalFile()
            langs = lilydoc.network.langs()
            if langs:
                for lang in langs:
                    if os.path.exists(path + '.' + lang + '.html'):
                        path += '.' + lang
                        break
            url = QUrl.fromLocalFile(path + '.html')
        self.webview.load(url)

    def slotPrint(self):
        printer = self._printer = QPrinter()
        dlg = QPrintDialog(printer, self)
        dlg.setWindowTitle(app.caption(_("Print")))
        if dlg.exec_():
            self.webview.page().print(printer, self.slotPrintingDone)

    def slotPrintingDone(self, success):
        del self._printer

    def slotShowContextMenu(self, pos):
        d = self.webview.page().contextMenuData()
        menu = QMenu()
        if d.linkUrl().isValid():
            a = self.webview.pageAction(QWebEnginePage.CopyLinkToClipboard)
            a.setIcon(icons.get("edit-copy"))
            a.setText(_("Copy &Link"))
            menu.addAction(a)
            menu.addSeparator()
            a = menu.addAction(icons.get("window-new"),
                               _("Open Link in &New Window"))
            a.triggered.connect(
                (lambda url: lambda: self.slotNewWindow(url))(d.linkUrl()))
        else:
            if d.selectedText():
                a = self.webview.pageAction(QWebEnginePage.Copy)
                a.setIcon(icons.get("edit-copy"))
                a.setText(_("&Copy"))
                menu.addAction(a)
                menu.addSeparator()
            a = menu.addAction(icons.get("window-new"),
                               _("Open Document in &New Window"))
            a.triggered.connect((lambda url: lambda: self.slotNewWindow(url))(
                self.webview.url()))
        if menu.actions():
            menu.exec_(self.webview.mapToGlobal(pos))

    def slotNewWindow(self, url):
        helpers.openUrl(url)
コード例 #14
0
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()
コード例 #15
0
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl
import sys
if sys.platform.startswith('linux'):
    import ctypes
    ctypes.CDLL("libGL.so.1", mode=ctypes.RTLD_GLOBAL)
app = QApplication([])
view = QWebEngineView()
view.load(QUrl("http://www.baidu.com"))
view.show()
app.exec_()
コード例 #16
0
class MainAPagar(Ui_ct_APagar, Ui_ct_FormPagar):
    def mainAPagar(self, frame):
        super(MainAPagar, self).setAPagar(frame)
        self.fr_Apagar.show()
        """ 
        Chamanda de funções localizadas no arquivo 
        financeiro.py na pasta Funcoes 
        """

        # Icone dos botoes
        self.setIconFinanceiro()

        # Setando Datas
        self.setDataFinanceiro()

        # Tamanho da Tabela
        self.tamanhoTabelaFinanceiro(self.fr_Apagar)
        """ Fim Chamanda financeiro.py  """

        # Chamando funcao popular checkBox
        self.listaStatus()

        # Chamando funcao Popular tabela a receber
        self.tabelaAPagar()

        # Funcao chamada botoes
        self.bt_Busca.clicked.connect(self.tabelaAPagar)

        # Imprimir
        self.bt_Print.clicked.connect(self.imprimirAPagar)

        # Abrindo form cadastrar
        self.bt_AddConta.clicked.connect(self.formAPagar)

    # Populando tabela a Pagar
    def tabelaAPagar(self):
        busca = CrudContaAPagar()
        dataInicio = QDate.toString(self.dt_Inicio.date(), "yyyy-MM-dd")
        dataFim = QDate.toString(self.dt_Fim.date(), "yyyy-MM-dd")
        busca.dataVencimento = dataInicio
        busca.dataFim = dataFim
        busca.statusPagamento = self.cb_Situacao.currentData()
        busca.listaContaAPagar()

        while self.tb_APagar.rowCount() > 0:
            self.tb_APagar.removeRow(0)

        self.totalRecebido = 0.00
        self.totalPendente = 0.00

        for i in range(len(busca.nomeFantasia)):
            self.tb_APagar.insertRow(i)

            self.conteudoTabela(self.tb_APagar, i, 0, str(busca.id[i]))

            self.TabelaStatus(
                self.tb_APagar, i, 1,
                self.StatusEntrega(1, busca.idStatusPagamento[i]))

            self.TabelaNomeTelefone(self.tb_APagar, i, 2,
                                    busca.nomeFantasia[i], busca.telefone[i])

            self.TabelaNomeTelefone(self.tb_APagar, i, 3, busca.descricao[i],
                                    "")

            self.TabelaEntrega(self.tb_APagar, i, 4, busca.dataVencimento[i],
                               self.StatusEntrega(busca.idStatusPagamento[i]),
                               busca.statusPagamento[i].upper())

            self.conteudoTabela(self.tb_APagar, i, 5,
                                "R$ " + str(busca.valor[i]))

            self.conteudoTabela(
                self.tb_APagar, i, 6,
                "R$ " + str(busca.valor[i] - busca.valorPago[i]))

            self.botaoReceberParcela(
                self.tb_APagar, i, 7,
                partial(self.BuscaContaAPagar, busca.id[i]), "Pagar", '2')
            # Total Pendente
            self.totalPendente = self.totalPendente + \
                float((busca.valor[i] - busca.valorPago[i]))
            # Total Recebido
            self.totalRecebido = self.totalRecebido + \
                float(busca.valorPago[i])

    # Cadastro e Edição conta a pagar
    def formAPagar(self):
        self.LimpaFrame(self.fr_Apagar)
        super(MainAPagar, self).setFormAPagar(self.fr_Apagar)
        self.fr_FormPagar.show()

        # Checado ID
        self.idCheckAPagar()
        """ Chamanda de funções localizadas no arquivo financeiro.py na pasta Funcoes """
        # Autocomplete
        self.setAutocompleteFinanceiro()

        # Data Vencimento e Pagamento com data Atual
        self.setDataVencPgto()

        # Setando Icones Salvar, Voltar e Imprimir
        self.setIconFormFinanceiro()

        # Pupulando combobox Repetir
        self.cboxRepedir(self.cb_repetir)

        # Botao Add Categoria
        self.bt_AddCategoriaProduto.clicked.connect(
            self.AddCategoriaFinanceiro)

        # Botao Cancela add Categoria
        self.bt_CancelAddCatergoria.clicked.connect(
            partial(self.CalcelAddFinanceiro, self.bt_CancelAddCatergoria,
                    self.bt_AddCategoriaProduto, self.tx_addCategoria,
                    self.cb_categoria))

        # Validador Campos Float
        self.ValidaInputFloat(self.tx_valor)
        self.ValidaInputFloat(self.tx_valorPago)

        # valida Campo Int
        self.ValidaInputInt(self.tx_Id)
        """ Fim Chamanda financeiro.py  """
        """ Chamanda de funções localizadas no arquivo FormaPagamento.py na pasta Funcoes """
        # Populando combobox Forma de Pagamento
        self.CboxFPagamento(self.cb_formaPagamento)
        """ Fim Chamanda FormaPagamento.py  """
        """ Chamanda de funções localizadas no arquivo categoriaAPagar.py na pasta Funcoes """
        # Populando combobox Forma de Pagamento
        self.cboxCatAPagar(self.cb_categoria)
        """ Fim Chamanda categoriaAPagar.py """
        """ Chamanda de funções localizadas no arquivo fornecedor.py na pasta Funcoes """
        # Campo Busca por nome e Autocompletar Fornecedor
        self.tx_NomeFantasia.textEdited.connect(self.autocompleFornecedor)
        self.tx_NomeFantasia.returnPressed.connect(
            partial(self.BuscaFornecedorNome, self.tx_descricao))

        # Return Press Busca Id Fornecedor
        self.tx_Id.returnPressed.connect(
            partial(self.BuscaFornecedorId, self.tx_descricao))
        """ Fim Chamadas """

        # Adicionando Nova Categoria
        self.tx_addCategoria.returnPressed.connect(self.CadCategoriraPagar)

        # Foco campos ID Cliente
        self.tx_Id.setFocus()

        # Botao Pagar
        self.bt_receber.clicked.connect(self.PagarParcela)

        # Imprimir Recibo
        self.bt_PrintRecibo.clicked.connect(self.imprimirReciboPag)

        # Botao Salvar
        self.bt_Salvar.clicked.connect(self.validaCadPagar)

        # Botao Voltar
        self.bt_Voltar.clicked.connect(self.JanelaAPagar)

    # checando campo Id se é Edicao ou Nova Venda
    def idCheckAPagar(self):
        if not self.tx_Cod.text():
            busca = CrudContaAPagar()
            self.tx_Cod.setText(str(busca.lastIdContaAPagar()))
        pass

    # Buscando Conta a Pagar através de ID recebido da Tabela
    def BuscaContaAPagar(self, id):
        self.formAPagar()
        busca = CrudContaAPagar()
        busca.id = id
        busca.selectContaID()
        self.tx_Cod.setText(str(busca.id))
        self.tx_Id.setText(str(busca.idFornecedor))
        self.BuscaFornecedorId(self.tx_descricao)
        self.tx_descricao.setText(busca.descricao)
        self.cb_categoria.setCurrentIndex(
            self.cb_categoria.findData(busca.categoria))
        self.dt_Vencimento.setDate(busca.dataVencimento)
        self.tx_valor.setText(str(busca.valor))
        self.tx_Obs.setPlainText(busca.obs)
        if busca.dataPagamento:
            self.dt_dataPagamento.setDate(busca.dataPagamento)
        self.cb_formaPagamento.setCurrentIndex(
            self.cb_formaPagamento.findData(busca.idFormaPagamento))
        self.tx_valorPago.setText(str(busca.valor - busca.valorPago))
        self.lb_ValorPendente.setText(str(busca.valor - busca.valorPago))

        if busca.idStatusPagamento == 1:
            self.desabilitaLineEdit(self.fr_FormPagar)
            self.bt_PrintRecibo.setVisible(True)
        elif busca.idStatusPagamento == 2:
            self.bt_receber.setEnabled(True)

        self.cb_repetir.setHidden(True)
        self.lb_Repetir.setHidden(True)
        self.lb_obsRepetir.setHidden(True)
        pass

    # realizando pagamento DB
    def PagarParcela(self, id):

        if not self.tx_valorPago.text():
            self.tx_valorPago.setFocus()
        elif not self.cb_formaPagamento.currentData():
            self.cb_formaPagamento.setFocus()
        else:
            INSERI = CrudContaAPagar()
            INSERI.id = self.tx_Cod.text()
            INSERI.formaPagamento = self.cb_formaPagamento.currentData()
            INSERI.valorPago = self.tx_valorPago.text().replace(",", ".")
            INSERI.dataPagamento = QDate.toString(QDate.currentDate(),
                                                  "yyyy-MM-dd")
            INSERI.pagarConta()
            self.BuscaContaAPagar(self.tx_Cod.text())

        pass

    # Validando campos a pagar
    def validaCadPagar(self):
        if not self.tx_Id.text():
            self.tx_Id.setFocus()
        elif not self.tx_descricao.text():
            self.tx_descricao.setFocus()
        elif not self.tx_valor.text():
            self.tx_valor.setFocus()
        else:
            self.cadContaPagar()

    def cadContaPagar(self):
        repetir = int(self.cb_repetir.currentData())
        for i in range(repetir):
            id = int(self.tx_Cod.text()) + i
            INSERI = CrudContaAPagar()
            INSERI.id = id
            INSERI.idFornecedor = self.tx_Id.text()
            INSERI.descricao = self.tx_descricao.text()
            INSERI.categoria = self.cb_categoria.currentData()
            INSERI.dataVencimento = QDate.toString(
                QDate.addMonths(self.dt_Vencimento.date(), i), "yyyy-MM-dd")
            INSERI.valor = self.tx_valor.text()
            INSERI.formaPagamento = self.cb_formaPagamento.currentData()
            INSERI.obs = self.tx_Obs.toPlainText()
            INSERI.inseriContaAPagar()

        self.BuscaContaAPagar(self.tx_Cod.text())

    # Cadastro Categoria a Pagar
    def CadCategoriraPagar(self):
        INSERI = CrudCatAPagar()
        id = INSERI.lastIdCatAPagar()
        categoria = self.tx_addCategoria.text().upper()
        INSERI.id = id
        INSERI.categoriaPagar = categoria
        INSERI.inseriCatAPagar()
        self.cb_categoria.addItem(categoria, str(id))
        self.cb_categoria.setCurrentIndex(self.cb_categoria.findData(str(id)))
        self.CalcelAddFinanceiro(self.bt_CancelAddCatergoria,
                                 self.bt_AddCategoriaProduto,
                                 self.tx_addCategoria, self.cb_categoria)

    # Imprimindo
    def imprimirAPagar(self):
        self.documento = QWebEngineView()

        headertable = [
            "Fornecedor", "Descrição ", "Vencimento", "Valor", "V. Pendente"
        ]

        data_inicio = QDate.toString(self.dt_Inicio.date(), "dd-MM-yyyy")
        data_fim = QDate.toString(self.dt_Fim.date(), "dd-MM-yyyy")

        if self.cb_Situacao.currentData() == '1':
            situacao = "Pago"

        elif self.cb_Situacao.currentData() == '2':
            situacao = "Pendente"

        cliente = []
        descricao = []
        vencimento = []
        valor = []
        pendente = []
        for i in range(self.tb_APagar.rowCount()):
            cliente.append(self.tb_APagar.cellWidget(i, 2).text())
            descricao.append(self.tb_APagar.cellWidget(i, 3).text())
            vencimento.append(self.tb_APagar.cellWidget(i, 4).text())
            valor.append(self.tb_APagar.item(i, 5).text())
            pendente.append(self.tb_APagar.item(i, 6).text())

        self.renderTemplate(
            "apagar.html",
            estilo=self.resourcepath('Template/estilo.css'),
            titulo="Relatório de conta a pagar {} de {} à {}".format(
                situacao, data_inicio, data_fim),
            headertable=headertable,
            nome=cliente,
            desc=descricao,
            venc=vencimento,
            valor=valor,
            pendente=pendente,
            totalPen=format(self.totalPendente, '.2f'),
            totalRec=format(self.totalRecebido, '.2f'))

        self.documento.load(
            QUrl.fromLocalFile(self.resourcepath("report.html")))
        self.documento.loadFinished['bool'].connect(self.previaImpressao)

# Imprimindo

    def imprimirReciboPag(self):

        self.documento = QWebEngineView()

        self.renderTemplate("recibopagamento.html",
                            estilo=self.resourcepath('Template/estilo.css'),
                            cod=self.tx_Cod.text(),
                            descricao=self.tx_descricao.text(),
                            valor=self.tx_valor.text().replace('.', ','),
                            valor_ext=retorno(self.tx_valor.text()),
                            data=date.today().strftime("%d-%m-%Y"))

        self.documento.load(
            QUrl.fromLocalFile(self.resourcepath("report.html")))
        self.documento.loadFinished['bool'].connect(self.previaImpressao)
コード例 #17
0
class Browser(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

        # 脚本
        self.profile = QWebEngineProfile.defaultProfile()
        self.script = QWebEngineScript()
        self.prepare_script()

    def init_ui(self):
        self.webView = QWebEngineView()

        self.logEdit = QTextEdit()
        self.logEdit.setFixedHeight(100)

        self.addrEdit = QLineEdit()
        self.addrEdit.returnPressed.connect(self.load_url)
        self.webView.urlChanged.connect(
            lambda i: self.addrEdit.setText(i.toDisplayString()))

        self.jsEdit = QLineEdit()
        self.jsEdit.setText('inject.js')

        loadUrlBtn = QPushButton('加载')
        loadUrlBtn.clicked.connect(self.load_url)

        chooseJsBtn = QPushButton('选择脚本文件')
        chooseJsBtn.clicked.connect(self.choose_js_file)

        # 导航/工具
        top = QWidget()
        top.setFixedHeight(80)
        topBox = QVBoxLayout(top)
        topBox.setSpacing(0)
        topBox.setContentsMargins(5, 0, 0, 5)

        progBar = QProgressBar()
        progBox = QHBoxLayout()
        progBox.addWidget(progBar)
        topBox.addLayout(progBox)

        naviBox = QHBoxLayout()
        naviBox.addWidget(QLabel('网址'))
        naviBox.addWidget(self.addrEdit)
        naviBox.addWidget(loadUrlBtn)
        topBox.addLayout(naviBox)

        naviBox = QHBoxLayout()
        naviBox.addWidget(QLabel('注入脚本文件'))
        naviBox.addWidget(self.jsEdit)
        naviBox.addWidget(chooseJsBtn)
        topBox.addLayout(naviBox)

        self.webView.loadProgress.connect(progBar.setValue)

        # 主界面
        layout = QVBoxLayout(self)
        layout.addWidget(self.webView)
        layout.addWidget(top)
        layout.addWidget(self.logEdit)

        self.show()
        self.resize(1024, 900)
        self.center()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    @pyqtSlot()
    def load_url(self):
        url = self.addrEdit.text().strip()
        if not url.lower().startswith('http://') \
                and not url.lower().startswith('https://'):
            url = 'http://{}'.format(url)
        self.load(url)

    @pyqtSlot()
    def choose_js_file(self):
        f, _ = QFileDialog.getOpenFileName(filter="Javascript files(*.js)")
        if os.path.isfile(f):
            self.jsEdit.setText(f)
            self.prepare_script()

    def prepare_script(self):
        path = self.jsEdit.text().strip()
        if not os.path.isfile(path):
            self.log('invalid js path')
            return

        self.profile.scripts().remove(self.script)
        with open(path, 'r') as f:
            self.script.setSourceCode(f.read())
        self.profile.scripts().insert(self.script)
        self.log('injected js ready')

    def log(self, msg, *args, **kwargs):
        m = msg.format(*args, **kwargs)
        self.logEdit.append('{} {}'.format(datetime.now().strftime('%H:%M:%S'),
                                           m))

    def load(self, url):
        self.log(f'loading {url}')
        self.addrEdit.setText(url)
        self.webView.load(QUrl(url))
コード例 #18
0
class ReporteWindowWidget(object):
    def __init__(self, Form, url):
        self.setupUi(Form, url)

    def setupUi(self, Form, url):
        """
         Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5.
         Args:
          Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget) 
        """
        Form.setObjectName("Form")
        Form.resize(800, 598)
        self.verticalLayoutWidget = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(220, 0, 581, 541))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.lblLogo = QtWidgets.QLabel(self.verticalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lblLogo.sizePolicy().hasHeightForWidth())
        self.lblLogo.setSizePolicy(sizePolicy)
        self.lblLogo.setMaximumSize(QtCore.QSize(1697/3.5, 312/3.5))
        self.lblLogo.setLineWidth(1)
        self.lblLogo.setText("")
        self.lblLogo.setPixmap(QtGui.QPixmap(APPCTXT().get_resource("logo3.png")))
        self.lblLogo.setScaledContents(True)
        self.lblLogo.setAlignment(QtCore.Qt.AlignCenter)
        self.lblLogo.setObjectName("lblLogo")
        self.horizontalLayout.addWidget(self.lblLogo)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label_4.setToolTip("")
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.verticalLayout_2.addWidget(self.label_4)



        self.webEngineWidget = QWebEngineView(self.verticalLayoutWidget)
        self.webEngineWidget.setObjectName("webEngineWidget")
        self.webEngineWidget.setMinimumSize(QtCore.QSize(0, 381))
        #url = QUrl.fromLocalFile(QDir.currentPath()+"/Reporte/reporte.html")
        urlReporte = QUrl.fromLocalFile(url)
        self.webEngineWidget.load(urlReporte)
        self.verticalLayout_2.addWidget(self.webEngineWidget)


        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        
        self.pbStart = QtWidgets.QPushButton(self.verticalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pbStart.sizePolicy().hasHeightForWidth())
        self.pbStart.setSizePolicy(sizePolicy)
        self.pbStart.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.pbStart.setObjectName("pbStart")
        self.horizontalLayout_2.addWidget(self.pbStart)

        self.pdSaveCsv = QtWidgets.QPushButton(self.verticalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pdSaveCsv.sizePolicy().hasHeightForWidth())
        self.pdSaveCsv.setSizePolicy(sizePolicy)
        self.pdSaveCsv.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.pdSaveCsv.setObjectName("pdSaveCsv")
        self.horizontalLayout_2.addWidget(self.pdSaveCsv)

        self.pbRestart = QtWidgets.QPushButton(self.verticalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pbRestart.sizePolicy().hasHeightForWidth())
        self.pbRestart.setSizePolicy(sizePolicy)
        self.pbRestart.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.pbRestart.setObjectName("pbRestart")
        self.horizontalLayout_2.addWidget(self.pbRestart)

        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.verticalLayout_2.setStretch(0, 1)
        self.verticalLayout_2.setStretch(1, 5)
        self.verticalLayout.addLayout(self.verticalLayout_2)
        self.verticalLayout.setStretch(0, 1)
        self.verticalLayout.setStretch(0, 0)
        self.lWVistas = QtWidgets.QListWidget(Form)
        self.lWVistas.setGeometry(QtCore.QRect(0, 90, 221, 451))
        self.lWVistas.setObjectName("lWVistas")

        self.progressBar = QtWidgets.QProgressBar(Form)
        self.progressBar.setGeometry(QtCore.QRect(127, 560, 601, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        """
         Método empleado paraasignar el contenido de la Interfáz gráfica, es generado por pyuic5.
         Args:
          Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget) 
        """
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Reporte"))
        # self.lblLogo.setText(_translate("Form", "Logo"))
        # self.label.setText(_translate("Form", "SYNAPPS"))
        self.label_4.setText(_translate("Form", "Vista previa del reporte"))
        self.pbStart.setText(_translate("Form", "Abrir en Navegador"))
        self.pdSaveCsv.setText(_translate("Form", "Guardar csv"))
        self.pbRestart.setText(_translate("Form", "Nuevo Reporte"))
コード例 #19
0
class ColdwolfWindow(QWidget):
    def __init__(self, parent=None):
        super(ColdwolfWindow, self).__init__()

        self.initUI(parent=parent)

    def initUI(self, parent=None):

        initurl = 'https://www.google.com'

        self.browser = QWebEngineView()
        self.browser.load(QUrl(initurl))
        self.browser.resize(1000, 600)
        self.browser.move(100, 100)
        self.browser.setWindowTitle(program_name())

        self.browser.settings().setAttribute(
            QWebEngineSettings.WebRTCPublicInterfacesOnly, True)

        # button
        self.back_button = QPushButton('<<')
        self.back_button.clicked.connect(self.browser.back)

        self.forward_button = QPushButton('>>')
        self.forward_button.clicked.connect(self.browser.forward)

        self.reload_button = QPushButton('Reload')
        self.reload_button.clicked.connect(self.browser.reload)

        self.url_edit = QLineEdit()
        self.url_edit.returnPressed.connect(self.loadPage)

        self.browser.urlChanged.connect(self.updateUrl)

        self.home_button = QPushButton('Home')
        self.home_button.clicked.connect(self.homePage)

        # layout
        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(self.back_button, 1, 0)
        grid.addWidget(self.forward_button, 1, 1)
        grid.addWidget(self.reload_button, 1, 2)
        grid.addWidget(self.url_edit, 1, 3, 1, 10)
        grid.addWidget(self.home_button, 1, 14)
        grid.addWidget(self.browser, 2, 0, 5, 15)

        self.setLayout(grid)
        if parent is None:
            self.resize(1200, 700)
            self.center()
            self.setWindowTitle(program_name())
            self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def loadPage(self):
        move_url = QUrl(self.url_edit.text())
        self.browser.load(move_url)
        self.updateUrl

    def updateUrl(self):
        self.url_edit.clear()
        self.url_edit.insert(self.browser.url().toString())

    def homePage(self):
        move_url = QUrl('https://twitter.com/home')
        self.browser.load(move_url)
        self.updateUrl
コード例 #20
0
class Example(QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()


    def initUI(self):

        self.toolBar = QToolBar(self)
        self.addToolBar(self.toolBar)

        self.backBtn = QPushButton(self)
        self.backBtn.setEnabled(False)

        self.backBtn.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/left-32.png'))
        self.backBtn.clicked.connect(self.back)
        self.toolBar.addWidget(self.backBtn)

        self.forBtn = QPushButton(self)
        self.forBtn.setEnabled(False)
        self.forBtn.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/right-32.png'))

        self.forBtn.clicked.connect(self.forward)
        self.toolBar.addWidget(self.forBtn)

        self.address = QLineEdit(self)
        self.address.returnPressed.connect(self.load)
        self.toolBar.addWidget(self.address)

        self.webEngineView = QWebEngineView(self)
        self.setCentralWidget(self.webEngineView)

        self.webEngineView.page().urlChanged.connect(self.onLoadFinished)

        self.webEngineView.page().titleChanged.connect(self.setWindowTitle)
        self.webEngineView.page().urlChanged.connect(self.urlChanged)

        self.setGeometry(300, 300, 500, 400)
        self.setWindowTitle('QWebEnginePage')
        self.show()

    def onLoadFinished(self):

        if self.webEngineView.history().canGoBack():
            self.backBtn.setEnabled(True)
        else:
            self.backBtn.setEnabled(False)

        if self.webEngineView.history().canGoForward():
            self.forBtn.setEnabled(True)
        else:
            self.forBtn.setEnabled(False)


    def load(self):

        url = QUrl.fromUserInput(self.address.text())

        if url.isValid():
            self.webEngineView.load(url)

    def back(self):
        self.webEngineView.page().triggerAction(QWebEnginePage.Back)

    def forward(self):
        self.webEngineView.page().triggerAction(QWebEnginePage.Forward)

    def urlChanged(self, url):
        self.address.setText(url.toString())
コード例 #21
0
import sys

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5 import QtCore

app = QApplication(sys.argv)
qev = QWebEngineView()
qev.show()

print(QtCore.qVersion())


def runTest():
    try:
        from PyQt5.QtTest import QTest
        from PyQt5.QtCore import Qt
        QTest.keyClick(qev, Qt.Key_Tab)
        print('finished')
    except Exception as e:
        print('exception:', e)
    finally:
        exit()


qev.page().loadFinished.connect(runTest)
qev.load(QUrl('http://google.com'))
app.exec_()
コード例 #22
0
 def init_widget(self):
     self.setWindowTitle(self.title)
     web = QWebEngineView()
     url = QUrl.fromLocalFile(r'%s/description.html' % os.getcwd())
     web.load(url)
     self.form_layout.addWidget(web)
コード例 #23
0
class MainWindow(QMainWindow, ui):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        # Additional Initialization
        Initial_path = QDir.currentPath()
        self.setWindowIcon(QIcon(":/IAID.ico"))
        self.PNloc.setText(Initial_path + '/PN.CSV')
        self.Querybox.setVisible(False)
        self.DB.setVisible(False)
        self.PDFloc.setText(Initial_path + '/PDF_Download')
        self.APT.setDate(
            QtCore.QDate(int(time.strftime("%Y")), int(time.strftime("%m")),
                         int(time.strftime("%d"))))
        self.IDT.setDate(
            QtCore.QDate(int(time.strftime("%Y")), int(time.strftime("%m")),
                         int(time.strftime("%d"))))
        self.TTL.setChecked(True)
        self.ISD.setChecked(True)
        self.CPC.setChecked(True)
        self.ABST.setChecked(True)
        self.AN.setChecked(True)
        self.PDF.setChecked(True)
        self.PNbt.setChecked(True)
        self.ut.setChecked(True)
        self.MODEL = QtGui.QStandardItemModel()
        self.MODEL.setColumnCount(17)
        self.MODEL.setHorizontalHeaderLabels([''] * 17)
        self.TABLE.setModel(self.MODEL)
        self.TABLE.setShowGrid(True)
        self.TABLE.setAlternatingRowColors(True)
        #setColumnWidth(0, 85)
        #self.TABLE.resizeColumnsToContents()
        #.setRowHeight(row, 18)
        self.webView = QWebEngineView(self.GL)
        self.webView.setGeometry(QtCore.QRect(0, 0, 1011, 491))
        self.webView.settings().setAttribute(QWebEngineSettings.PluginsEnabled,
                                             True)
        self.webView.load(
            QUrl(
                "http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&r=1&p=1&f=G&l=50&d=PTXT&S1=9532164.PN.&OS=pn/9532164&RS=PN/9532164"
            ))
        self.webView.show()

        # Events
        self.statusBar.showMessage('Welcome!')
        self.PNbws.clicked.connect(self.FileDialog2Line_PNCSV)
        self.PDFbws.clicked.connect(self.FileDialog2Line_PDF)
        self.DB.currentIndexChanged.connect(self.DB2filter)

        # Execution
        self.IMPORT.clicked.connect(self.importPN)
        self.EXPORT.clicked.connect(self.handleSave)
        self.FILTER.clicked.connect(self.TABLE_FILTER)
        self.PDFD.clicked.connect(self.PDFDOWNLOAD)
        self.INFO.clicked.connect(self.Crawler)
        self.STOPLOOP.clicked.connect(self.stopbool)
        self.web_PDF.clicked.connect(self.showPDF)
        self.web_PAT.clicked.connect(self.showPAT)
        self.stop = False

    def showPAT(self):
        PN = self.PNweb.text()
        _, PatFT_link, _, _, _ = ptc.PN_str_and_url(PN)
        self.webView.load(QUrl(PatFT_link))
        self.webView.show()

    def showPDF(self):
        PN = self.PNweb.text()
        _, _, _, PDF_link_full, _ = ptc.PN_str_and_url(PN)
        #self.webView.load(QUrl(PDF_link_full))
        #self.webView.show()
        QDesktopServices.openUrl(QUrl(PDF_link_full))

    def stopbool(self):
        self.stop = True

    def PDFDOWNLOAD(self):
        self.stop = False
        self.PDFD.setEnabled(False)
        # demand: 0=do not download, 1=download full text, 2=download drawing section, 3=download both
        if self.cs2b(self.PDFfull) == 0 and self.cs2b(self.PDFdraw) == 0:
            self.statusBar.showMessage('Please select something to download!')
            self.PDFD.setEnabled(True)
            return
        elif self.cs2b(self.PDFfull) == 1 and self.cs2b(self.PDFdraw) == 0:
            pdf_demand = 1
        elif self.cs2b(self.PDFfull) == 0 and self.cs2b(self.PDFdraw) == 1:
            pdf_demand = 2
        elif self.cs2b(self.PDFfull) == 1 and self.cs2b(self.PDFdraw) == 1:
            pdf_demand = 3

        # return if PN hasn't been imported
        if self.MODEL.headerData(0, Qt.Horizontal) != 'Patent No.':
            self.statusBar.showMessage('Please import Patent Numers first!')
            self.PDFD.setEnabled(True)
            return

        error_download = 0
        cwd = os.getcwd()
        PDF_loc = self.PDFloc.text()
        if not os.path.exists(PDF_loc):
            os.makedirs(PDF_loc)
        os.chdir(PDF_loc)

        totalrow = self.MODEL.rowCount()
        for i in range(totalrow):
            if self.stop:
                break
            QApplication.processEvents()
            PN = str(self.MODEL.data(self.MODEL.index(i, 0)))
            PN, PatFT_link, PN_PDF, PDF_link_full, PDF_link_page = ptc.PN_str_and_url(
                PN)
            status, mes = ptc.PDF_download(PN, PatFT_link, PN_PDF,
                                           PDF_link_full, PDF_link_page,
                                           pdf_demand)
            self.statusBar.showMessage('US' + PN + ' ( ' + str(i + 1) + ' / ' +
                                       str(totalrow) + ' ): ' + mes)
            if not status:
                error_download += 1
        if self.stop:
            self.stop = False
            self.statusBar.showMessage('The program is stop on your demand.')
        elif error_download == 0:
            self.statusBar.showMessage('PDF downloaded sucessfully!')
        else:
            self.statusBar.showMessage('PDF downloaded, but ' +
                                       str(error_download) + 'errors exist')
        os.chdir(cwd)
        self.PDFD.setEnabled(True)

    def Crawler(self):
        self.INFO.setEnabled(False)
        self.stop = False
        # return if PN hasn't been imported
        if self.MODEL.headerData(0, Qt.Horizontal) != 'Patent No.':
            self.statusBar.showMessage('Please import Patent Numers first!')
            self.INFO.setEnabled(True)
            return

        self.statusBar.showMessage('Fetching info for you...')
        row = self.MODEL.rowCount()
        Item_b = [self.cs2b(self.TTL),   self.cs2b(self.ISD),  self.cs2b(self.APD),  self.cs2b(self.IN),   self.cs2b(self.AANM),\
                  self.cs2b(self.AN),    self.cs2b(self.CPC),  self.cs2b(self.CPCs), self.cs2b(self.IPC),  self.cs2b(self.IPCs),\
                  self.cs2b(self.REFby), self.cs2b(self.ABST), self.cs2b(self.FMID), self.cs2b(self.ApNo), self.cs2b(self.PAT), self.cs2b(self.PDF)]
        Item = []
        for i in range(16):
            if Item_b[i] == 1:
                Item.append(i)
        del Item_b
        Head = ["Title","Issue Date", "Application Date", "Inventors", "Applicant", "Assignee", "CPC", "CPC-subclass",\
            "IPC", "IPC-subclass","Referenced by","Abstract", "Family ID",  "Appl. No.", "PatFT Link", "PDF Link"]
        Head = ["Patent No."] + [Head[i] for i in Item]
        Head = Head + (17 - len(Head)) * [' ']
        self.MODEL.setHorizontalHeaderLabels(Head)

        for i in range(row):
            if self.stop:
                break
            QApplication.processEvents()
            PN = str(self.MODEL.data(self.MODEL.index(i, 0)))
            if PN == 'Filtered':
                continue
            PN, PatFT_link, PN_PDF, PDF_link_full, PDF_link_page = ptc.PN_str_and_url(
                PN)
            soup = URL2Soup(PatFT_link)
            ttl = ptc.TTL(soup)
            if len(ttl) < 2:
                time.sleep(1)
                QApplication.processEvents()
                soup = URL2Soup1(PatFT_link)
                ttl = ptc.TTL(soup)
                if len(ttl) < 2:
                    time.sleep(1)
                    QApplication.processEvents()
                    soup = URL2Soup1(PatFT_link)
                    ttl = ptc.TTL(soup)
                    if len(ttl) < 2:
                        time.sleep(1)
                        QApplication.processEvents()
                        soup = URL2Soup1(PatFT_link)
                        ttl = ptc.TTL(soup)
                        if len(ttl) < 2:
                            time.sleep(1)
                            QApplication.processEvents()
                            soup = URL2Soup2(PatFT_link)
                            ttl = ptc.TTL(soup)
                            if len(ttl) < 2:
                                time.sleep(1)
                                QApplication.processEvents()
                                soup = URL2Soup2(PatFT_link)
                                ttl = ptc.TTL(soup)
                                if len(ttl) < 2:
                                    time.sleep(1)
                                    QApplication.processEvents()
                                    soup = URL2Soup2(PatFT_link)
                                    ttl = ptc.TTL(soup)
            j = 1
            #Title
            if 0 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ttl))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Issue Date
            if 1 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.ISD(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Application Date
            if 2 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.APD(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Inventor
            if 3 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ptc.IN(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            #Applicant
            if 4 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.AANM(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Assignee
            if 5 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ptc.AN(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # CPC
            if 6 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.CPC(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # CPC subclass
            if 7 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.CPCs(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # IPC
            if 8 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.IPC(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # IPC subclass
            if 9 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.IPCs(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Number of referenced by
            if 10 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ptc.REF(PN)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Abstract
            if 11 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.ABST(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Family ID
            if 12 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.FMID(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Application Number
            if 13 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.ApNo(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # PatFT link
            if 14 in Item:
                try:
                    self.MODEL.setItem(
                        i, j,
                        QtGui.QStandardItem('=HYPERLINK("' + PatFT_link +
                                            '")'))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # PDF link
            if 15 in Item:
                try:
                    self.MODEL.setItem(
                        i, j,
                        QtGui.QStandardItem('=HYPERLINK("' + PDF_link_full +
                                            '")'))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()

        if self.stop:
            self.stop = False
            self.statusBar.showMessage(
                'The program is stopped on your demand.')
        else:
            self.statusBar.showMessage('Done.')
        self.INFO.setEnabled(True)

    # Filter PNs and delete them
    def TABLE_FILTER(self):
        self.FILTER.setEnabled(False)
        self.stop = False
        PNtype_limit = np.array([
            self.cs2b(self.ut),
            self.cs2b(self.ds),
            self.cs2b(self.pp),
            self.cs2b(self.ot)
        ])
        if self.MODEL.headerData(0, Qt.Horizontal) != 'Patent No.':
            self.statusBar.showMessage('Please import Patent Numers first!')
            self.FILTER.setEnabled(True)
            return
        if self.cs2b(self.APDdis) == 0 and self.cs2b(
                self.ISDdis) == 0 and (self.cs2b(self.all) == 1
                                       or sum(PNtype_limit) == 4):
            self.statusBar.showMessage('Nothing will be filtered.')
            self.FILTER.setEnabled(True)
            return
        row = self.MODEL.rowCount()

        #Time range
        Afy, Afm, Afd = self.APF.date().year(), self.APF.date().month(
        ), self.APF.date().day()
        Aty, Atm, Atd = self.APT.date().year(), self.APT.date().month(
        ), self.APT.date().day()
        Ify, Ifm, Ifd = self.IDF.date().year(), self.IDF.date().month(
        ), self.IDF.date().day()
        Ity, Itm, Itd = self.IDT.date().year(), self.IDT.date().month(
        ), self.IDT.date().day()
        APD_limit = np.array([Afy, Afm, Afd, Aty, Atm, Atd])
        ISD_limit = np.array([Ify, Ifm, Ifd, Ity, Itm, Itd])

        delete_list = []
        for i in range(row):
            if self.stop:
                break
            self.statusBar.showMessage('Filtering: ' + str(len(delete_list)) +
                                       ' patents are filtered. ( ' +
                                       str(i + 1) + ' / ' + str(row) + ' )')
            PN = str(self.MODEL.data(self.MODEL.index(i, 0)))
            PN, PatFT_link, _, _, _ = ptc.PN_str_and_url(PN)
            APD_str, ISD_str = '', ''
            # derive soup only if necessary (since it's time consuming)
            if self.cs2b(self.APDdis) != 0 or self.cs2b(self.ISDdis) != 0:
                soup = URL2Soup(PatFT_link)
                QApplication.processEvents()
                APD_str = ptc.APD(soup)
                ISD_str = ptc.ISD(soup)
            now = datetime.datetime.now()
            # Do not filter patent type if 'all' is checked
            if self.cs2b(self.all) != 1:
                if not ptc.PNtype_filter(PN, PNtype_limit):
                    delete_list += [i]
                    self.MODEL.setItem(i, 0, QtGui.QStandardItem('Filtered'))
                    continue
            # Do not filter appl. date if (1) user do not want to, (2) appl. date isn't listed, (3) (start time <1790/1/1) AND (end time> now)
            if self.cs2b(self.APDdis) == 1 and len(APD_str) > 1 and not (
                    datetime.datetime(Afy, Afm, Afd) <= datetime.datetime(
                        1790, 1, 1)
                    and datetime.datetime(Aty, Atm, Atd) >= now):
                if not ptc.Date_filter(APD_str, APD_limit):
                    delete_list += [i]
                    self.MODEL.setItem(i, 0, QtGui.QStandardItem('Filtered'))
                    continue
            # Do not filter issue date if (1) user do not want to, (2) issue date isn't listed, (3) (start time <1790/1/1) AND (end time> now)
            if len(ISD_str) > 1 and self.cs2b(self.ISDdis) == 1 and not (
                    datetime.datetime(Ify, Ifm, Ifd) <= datetime.datetime(
                        1790, 1, 1)
                    and datetime.datetime(Ity, Itm, Itd) >= now):
                if not ptc.Date_filter(ISD_str, ISD_limit):
                    delete_list += [i]
                    self.MODEL.setItem(i, 0, QtGui.QStandardItem('Filtered'))
                    continue
            QApplication.processEvents()
        if self.stop:
            self.stop = False
            self.statusBar.showMessage(
                'The program is stopped on your demand.')
        # delete unwanted PN
        elif len(delete_list) > 0:
            delete_list_arr = np.array(delete_list)
            for row_index in delete_list:
                self.MODEL.removeRow(
                    row_index -
                    len(delete_list_arr[delete_list_arr < row_index]))
                self.statusBar.showMessage('Deleting the filtered data.....')
        self.statusBar.showMessage('Done Filtering: ' + str(len(delete_list)) +
                                   ' out of ' + str(row) +
                                   ' patents are filtered.')
        self.FILTER.setEnabled(True)

    # import PN with a existing CSV file
    def import_PNlist_CSV(self, list_loc):
        with open(list_loc) as csvr:
            reader = csv.reader(csvr)
            count = 0
            for row in reader:
                count += 1
                self.statusBar.showMessage(
                    'There are %d patent numbers in the list. Preparing the list...'
                    % count)
                QApplication.processEvents()
            csvr.seek(0)
            self.MODEL.clear()
            self.MODEL.setHorizontalHeaderLabels(['Patent No.'] + [''] * 16)
            i = 0
            error_count = 0
            for row in reader:
                if self.stop:
                    break
                PN = str(row[0]).replace(' ', '').replace(',', '')
                self.MODEL.setItem(i, 0, QtGui.QStandardItem(PN))
                """
                if requests.get("http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/"+row[0]).status_code!=200:
                    self.MODEL.setItem(i,1, QtGui.QStandardItem('NO') )
                else:
                    self.MODEL.setItem(i,1, QtGui.QStandardItem('YES') )
                """
                try:
                    int(PN)
                except:
                    try:
                        int(PN[1:])
                        if (PN[0].lower not in [
                                'h', 't', 'd', 'x'
                        ]) and (requests.get(
                                "http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/1"
                                + PN).status_code != 200):
                            self.MODEL.setItem(
                                i, 1,
                                QtGui.QStandardItem(
                                    'Not a proper patent number! Please check again.'
                                ))
                            error_count += 1
                    except:
                        try:
                            int(PN[2:])
                            if (PN[0:2].lower not in [
                                    're', 'rx', 'pp', 'ai'
                            ]) and (requests.get(
                                    "http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/1"
                                    + PN).status_code != 200):
                                self.MODEL.setItem(
                                    i, 1,
                                    QtGui.QStandardItem(
                                        'Not a proper patent number! Please check again.'
                                    ))
                                error_count += 1
                        except:
                            self.MODEL.setItem(
                                i, 1,
                                QtGui.QStandardItem(
                                    'Not a proper patent number! Please check again.'
                                ))
                            error_count += 1
                QApplication.processEvents()
                i += 1
            if self.stop:
                self.stop = False
                self.statusBar.showMessage(
                    'The program is stopped on your demand.')
            elif error_count == 0:
                self.statusBar.showMessage(
                    'Patent list is ready! There are %d patents.' % count)
            else:
                self.statusBar.showMessage(
                    'Patent list is ready but ' + str(error_count) +
                    'out of %d patent numbers are not in proper formats.' %
                    count)
                self.MODEL.setHorizontalHeaderLabels(['Patent No.', 'Errors'])

    def importPN(self):
        self.IMPORT.setEnabled(False)
        self.FILTER.setEnabled(False)
        self.INFO.setEnabled(False)
        self.PDFD.setEnabled(False)
        self.stop = False
        if self.PNbt.isChecked():
            self.MODEL.clear()
            list_loc = self.PNloc.text()
            if not os.path.exists(list_loc):
                self.statusBar.showMessage(
                    "The path of input PN list doesn't exist. Please check again."
                )
            elif list_loc[-3:].lower() != 'csv':
                self.statusBar.showMessage(
                    'This not a CSV file! Please check again.')
            else:
                self.import_PNlist_CSV(list_loc)
        elif self.Querybt.isChecked():
            self.MODEL.clear()
            self.statusBar.showMessage('Preparing patent list...')
            if self.DB.currentIndex() == 0:
                db = 'PTXT'
            else:
                db = 'PALL'
            query = self.Querybox.toPlainText()
            total_PTnumber, PN_1st_page, message = getInfofromQuery_1st_page(
                query, db)
            self.statusBar.showMessage(
                'There are %d patents can be searched with this query.' %
                total_PTnumber)
            if total_PTnumber == 0:
                self.statusBar.showMessage(message)
            elif total_PTnumber <= 50:
                self.MODEL.setHorizontalHeaderLabels(['Patent No.'])
                for i in range(total_PTnumber):
                    self.MODEL.setItem(i, 0,
                                       QtGui.QStandardItem(PN_1st_page[i]))
                    QApplication.processEvents()
                self.statusBar.showMessage(
                    'Patent list is ready! There are %d patents.' %
                    total_PTnumber)
            else:
                pages = int(total_PTnumber /
                            50) + 1 if total_PTnumber % 50 != 0 else int(
                                total_PTnumber / 50)
                search_pages = [(
                    'http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&r=0&p='
                    + str(i + 1) + '&f=S&l=50&Query=' + query + '&d=' + db)
                                for i in range(pages)]
                self.MODEL.setHorizontalHeaderLabels(['Patent No.'])
                i = 0
                for link in search_pages:
                    if self.stop:
                        break
                    soup = URL2Soup(link)
                    PN_list = getPNfromSoup_one_page(soup)
                    j = 1
                    for PN in PN_list:
                        index = i * 50 + j
                        self.MODEL.setItem(index - 1, 0,
                                           QtGui.QStandardItem(PN))
                        self.statusBar.showMessage((
                            'There are ' + str(total_PTnumber) +
                            ' patents can be searched with this query. Acquiring patent numbers: '
                            + str(index) + ' / ' + str(total_PTnumber)))
                        QApplication.processEvents()
                        j += 1
                    i += 1
                if self.stop:
                    self.stop = False
                    self.statusBar.showMessage(
                        'The program is stopped on your demand.')
                else:
                    self.statusBar.showMessage(
                        'Patent list is ready! There are %d patents.' %
                        total_PTnumber)
        self.IMPORT.setEnabled(True)
        self.FILTER.setEnabled(True)
        self.INFO.setEnabled(True)
        self.PDFD.setEnabled(True)

    def handleSave(self):
        path = self.FileDialog2Line_OutCSV()
        try:
            os.path.exists(path)
        except:
            return
        if os.path.exists(path):
            with open(path + '\\Result.CSV', 'w', newline='') as stream:
                writer = csv.writer(stream)
                header = []
                for i in range(17):
                    header.append(self.MODEL.headerData(i, Qt.Horizontal))
                writer.writerow(header)
                for row in range(self.MODEL.rowCount()):
                    if self.stop:
                        break
                    rowdata = []
                    for column in range(self.MODEL.columnCount()):
                        item = self.MODEL.item(row, column)
                        if item is not None:
                            rowdata.append(item.text())
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)
                if self.stop:
                    self.stop = False
                    self.statusBar.showMessage(
                        'The program is stopped by demand.')
                else:
                    self.statusBar.showMessage('Result.CSV is saved.')

    def FileDialog2Line_PNCSV(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Select a CSV file containing Patent Numbers",
            "",
            "CSV Files (*.csv);;All Files (*)",
            options=options)
        del options
        if fileName:
            self.PNloc.setText(fileName)
        del fileName

    def FileDialog2Line_OutCSV(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getExistingDirectory(self,
                                                    "Saving Result.CSV at:",
                                                    options=options)
        del options
        if fileName:
            return fileName

    def FileDialog2Line_PDF(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getExistingDirectory(self,
                                                    "Saving PDF files at:",
                                                    "",
                                                    options=options)
        del options
        if fileName:
            self.PDFloc.setText(fileName)
        del fileName

    def DB2filter(self):
        if self.DB.currentIndex() == 0:
            self.APF.setDate(QtCore.QDate(1976, 1, 1))
            self.IDF.setDate(QtCore.QDate(1976, 1, 1))
        else:
            self.APF.setDate(QtCore.QDate(1790, 1, 1))
            self.IDF.setDate(QtCore.QDate(1790, 1, 1))

    def cs2b(self, box):
        if box.checkState() == 2:
            return 1
        else:
            return 0
コード例 #24
0
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)
コード例 #25
0
    def js_callback(self, result):
        QMessageBox.information(None, "提示", "来自js回复:{}".format(result))
        print(result)

    # 注意pyqtSlot用于把该函数暴露给js可以调用 result=str返回的值string
    @pyqtSlot(str, result=str)
    def jsCallpy(self, text):
        QMessageBox.information(None, "提示", "来自js消息:{}".format(text))
        return 'js,py收到消息'


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 新增一个浏览器引擎
    web_view = QWebEngineView()
    # 增加一个通信中需要用到的频道
    myChannel = QWebChannel()
    # 用于通信的对象
    bridgeClass = BridgeClass()
    # 注册,testObject是自己起的名字
    myChannel.registerObject('Bridge', bridgeClass)
    # 在浏览器中设置该频道
    web_view.page().setWebChannel(myChannel)

    # 获取当前文件夹位置
    path_url = os.path.abspath('.')
    url_string = 'file://' + path_url + '/web.html'
    web_view.load(QUrl(url_string))
    web_view.show()
    sys.exit(app.exec_())
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_()
コード例 #27
0
ファイル: downloader.py プロジェクト: logonmy/youtube-stealer
 def gotowebpage(self, url):
     browser_search = QWebEngineView()
     search_url = QUrl(url.replace('watch?v=', 'embed/'))
     browser_search.load(search_url)
コード例 #28
0
ファイル: qt502_webviewJs02.py プロジェクト: ttof80/PyQt5
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_())
コード例 #29
0
ファイル: JsSignals.py プロジェクト: won2930015/pyqt5example
        layout = QVBoxLayout(self)
        self.webview = WebEngineView(self)
        layout.addWidget(self.webview)
        layout.addWidget(
            QPushButton('发送自定义信号', self,
                        clicked=self.webview.sendCustomSignal))

        self.webview.windowTitleChanged.connect(self.setWindowTitle)
        self.webview.load(
            QUrl.fromLocalFile(os.path.abspath('Data/JsSignals.html')))


if __name__ == "__main__":
    from PyQt5.QtWidgets import QApplication
    import sys
    # 开启F12 控制台功能,需要单独通过浏览器打开这个页面
    # 这里可以做个保护, 发布软件,启动时把这个环境变量删掉。防止他人通过环境变量开启
    os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = '9966'
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    w.move(100, 100)

    # 打开调试页面
    dw = QWebEngineView()
    dw.setWindowTitle('开发人员工具')
    dw.load(QUrl('http://127.0.0.1:9966'))
    dw.move(600, 100)
    dw.show()
    sys.exit(app.exec_())
コード例 #30
0
ファイル: mainfornecedor.py プロジェクト: Wiras77/sitema-pdv
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)
コード例 #31
0
folium.Marker(
    location=[g.lat, g.lng],
    popup='You\'re here',
    icon=folium.Icon(color='green', icon='ok-sign'),
).add_to(m)
outfp = "map.html"
m.save(outfp)
#webview.create_window('Hello world', 'map.html')

app = QApplication(sys.argv)
#label = QLabel("Hello World!")
browser = QWebEngineView()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "map.html"))
local_url = QUrl.fromLocalFile(file_path)
browser.load(local_url)

browser.show()
app.exec_()



#webbrowser.open_new_tab('map.html')
#webview.create_window('Todos magnificos', outfp)
'''import wx
import wx.html

class MyHtmlFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title)
        html = wx.html.HtmlWindow(self)
コード例 #32
0
class Overlay(QtCore.QObject):

    def __init__(self, up, configFileName, name, url):
        super().__init__()
        self.configFileName = configFileName
        self.parent = up
        self.app = up.app
        self.url = url
        self.size = None
        self.name = name
        self.overlay = None
        self.settings = None
        self.position = None
        self.enabled = True
        self.showtitle = True
        self.mutedeaf = True
        self.showtitle = True

    def load(self):
        config = ConfigParser(interpolation=None)
        config.read(self.configFileName)
        self.posXL = config.getint(self.name, 'xl', fallback=0)
        self.posXR = config.getint(self.name, 'xr', fallback=200)
        self.posYT = config.getint(self.name, 'yt', fallback=50)
        self.posYB = config.getint(self.name, 'yb', fallback=450)
        self.right = config.getboolean(self.name, 'rightalign', fallback=False)
        self.mutedeaf = config.getboolean(
            self.name, 'mutedeaf', fallback=True)
        self.chatresize = config.getboolean(
            self.name, 'chatresize', fallback=True)
        self.screenName = config.get(self.name, 'screen', fallback='None')
        #self.url = config.get(self.name, 'url', fallback=None)
        self.enabled = config.getboolean(self.name, 'enabled', fallback=True)
        self.showtitle = config.getboolean(self.name, 'title', fallback=True)
        self.hideinactive = config.getboolean(
            self.name, 'hideinactive', fallback=True)
        self.chooseScreen()
        # TODO Check, is there a better logic location for this?
        if self.enabled:
            self.showOverlay()

    def moveOverlay(self):
        if self.overlay:
            self.overlay.resize(self.posXR-self.posXL, self.posYB-self.posYT)
            self.overlay.move(self.posXL + self.screenOffset.left(),
                              self.posYT + self.screenOffset.top())

    def on_url(self, url):
        if self.overlay:
            self.overlay.load(QtCore.QUrl(url))
        self.url = url
        self.save()
        self.settings.close()
        self.settings = None

    def on_save_position(self, url):
        self.save()
        self.position.close()
        self.position = None

    @pyqtSlot()
    def save(self):
        config = ConfigParser(interpolation=None)
        config.read(self.configFileName)
        if not config.has_section(self.name):
            config.add_section(self.name)
        config.set(self.name, 'xl', '%d' % (self.posXL))
        config.set(self.name, 'xr', '%d' % (self.posXR))
        config.set(self.name, 'yt', '%d' % (self.posYT))
        config.set(self.name, 'yb', '%d' % (self.posYB))
        config.set(self.name, 'rightalign', '%d' % (int(self.right)))
        config.set(self.name, 'mutedeaf', '%d' % (int(self.mutedeaf)))
        config.set(self.name, 'chatresize', '%d' % (int(self.chatresize)))
        config.set(self.name, 'screen', self.screenName)
        config.set(self.name, 'enabled', '%d' % (int(self.enabled)))
        config.set(self.name, 'title', '%d' % (int(self.showtitle)))
        config.set(self.name, 'hideinactive', '%d' % (int(self.hideinactive)))
        if self.url:
            config.set(self.name, 'url', self.url)
            if ',' in self.url:
                self.parent.reinit()
        with open(self.configFileName, 'w') as file:
            config.write(file)

    @pyqtSlot()
    def on_click(self):
        self.runJS(
            "document.getElementsByClassName('source-url')[0].value;", self.on_url)

    @pyqtSlot()
    def skip_stream_button(self):
        skipIntro = "buttons = document.getElementsByTagName('button');for(i=0;i<buttons.length;i++){if(buttons[i].innerHTML=='Install for OBS'){buttons[i].click()}}"
        hideLogo = "document.getElementsByClassName('install-logo')[0].style.setProperty('display','none');"
        resizeContents = "document.getElementsByClassName('content')[0].style.setProperty('top','30px');"
        resizeHeader = "document.getElementsByClassName('header')[0].style.setProperty('height','35px');"
        hidePreview = "document.getElementsByClassName('config-link')[0].style.setProperty('height','300px');document.getElementsByClassName('config-link')[0].style.setProperty('overflow','hidden');"
        hideClose = "document.getElementsByClassName('close')[0].style.setProperty('display','none');"
        chooseVoice = "for( let button of document.getElementsByTagName('button')){ if(button.getAttribute('value') == 'voice'){ button.click(); } }"
        chooseChat = "for( let button of document.getElementsByTagName('button')){ if(button.getAttribute('value') == 'chat'){ button.click(); } }"
        infoListener = "if(typeof console.oldlog === 'undefined'){console.oldlog=console.log;}window.consoleCatchers=[];console.log = function(text,input){if(typeof input !== 'undefined'){window.consoleCatchers.forEach(function(item,index){item(input)})}else{console.oldlog(text);}};"
        catchGuild = "window.consoleCatchers.push(function(input){if(input.cmd == 'GET_GUILD'){window.guilds=input.data.id}})"
        catchChannel = "window.consoleCatchers.push(function(input){if(input.cmd == 'GET_CHANNELS'){window.channels = input.data.channels;}})"

        self.runJS(skipIntro)
        self.runJS(hideLogo)
        self.runJS(resizeContents)
        self.runJS(hidePreview)
        self.runJS(resizeHeader)
        self.runJS(hideClose)
        self.runJS(infoListener)
        self.runJS(catchGuild)
        self.runJS(catchChannel)
        if self.url:
            if 'overlay/voice' in self.url:
                self.runJS(chooseVoice)
            else:
                self.runJS(chooseChat)

    def enableConsoleCatcher(self):
        if self.overlay:
            tweak = "if(typeof console.oldlog === 'undefined'){console.oldlog=console.log;}window.consoleCatchers=[];console.log = function(text,input){if(typeof input !== 'undefined'){window.consoleCatchers.forEach(function(item,index){item(input)})}else{console.oldlog(text);}};"
            self.overlay.page().runJavaScript(tweak)

    def enableShowVoiceTitle(self):
        if self.overlay:
            tweak = "window.consoleCatchers.push(function(input){if(input.cmd == 'GET_CHANNEL'){chan=input.data.name;(function() { css = document.getElementById('title-css'); if (css == null) { css = document.createElement('style'); css.type='text/css'; css.id='title-css'; document.head.appendChild(css); } css.innerText='.voice-container:before{content:\"'+chan+'\";background:rgba(30, 33, 36, 0.95);padding:4px 6px;border-radius: 3px;}';})()}})"
            self.overlay.page().runJavaScript(tweak)

    def enableHideInactive(self):
        if self.overlay and self.url:
            if 'overlay/voice' in self.url:
                tweak = "document.getElementById('app-mount').style='display:none';window.consoleCatchers.push(function(input){if(input.cmd=='AUTHENTICATE'){console.error(input.data.user);window.iAm=input.data.user.username;}if(input.evt=='VOICE_STATE_CREATE' || input.evt=='VOICE_STATE_UPDATE'){if(input.data.nick.toUpperCase()==window.iAm.toUpperCase()){document.getElementById('app-mount').style='display:block';console.error('Showing '+chan)}}if(input.evt=='VOICE_STATE_DELETE'){if(input.data.nick.toUpperCase()==window.iAm.toUpperCase()){document.getElementById('app-mount').style='display:none';console.error('Hiding '+chan)}}});"
                self.overlay.page().runJavaScript(tweak)

    def enableMuteDeaf(self):
        if self.overlay:
            tweak = "window.consoleCatchers.push(function(input){if(input.evt == 'VOICE_STATE_UPDATE'){name=input.data.nick;uState = input.data.voice_state;muteicon = '';if(uState.self_mute || uState.mute){muteicon='<img src=\\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABhMAAAYJQE8CCw1AAAAB3RJTUUH5AUGCx0VMm5EjgAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAABzSURBVDjLxZIxCsAwCEW/oT1P7z93zZJjeIYMv0sCIaBoodTJDz6/JgJfBslOsns1xYONvK66JCeqAC4ALTz+dJvOo0lu/zS87p2C98IdHlq9Buo5D62h17amScMk78hBWXB/DUdP2fyBaINjJiJy4o94AM8J8ksz/MQjAAAAAElFTkSuQmCC\\' style=\\'height:0.9em;\\'>';}deaficon = '';if(uState.self_deaf || uState.deaf){deaficon='<img src=\\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABhMAAAYJQE8CCw1AAAAB3RJTUUH5AUGCx077rhJQQAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAACNSURBVDjLtZPNCcAgDIUboSs4iXTGLuI2XjpBz87g4fWiENr8iNBAQPR9ef7EbfsjAEQAN4A2UtCcGtyMzFxjwVlyBHAwTRFh52gqHDVnF+6L1XJ/w31cp7YvOX/0xlOJ254qYJ1ZLTAmPWeuDVxARDurfBFR8jovMLEKWxG6c1qB55pEuQOpE8vKz30AhEdNuXK0IugAAAAASUVORK5CYII=\\' style=\\'height:0.9em;\\'>';}spans = document.getElementsByTagName('span');for(i=0;i<spans.length;i++){if(spans[i].innerHTML.startsWith(name)){text = name + muteicon + deaficon;spans[i].innerHTML = text;}}}});"
            self.overlay.page().runJavaScript(tweak)

    def runJS(self, string, retFunc=None):
        if retFunc:
            self.settingWebView.page().runJavaScript(string, retFunc)
        else:
            self.settingWebView.page().runJavaScript(string)

    def applyTweaks(self):
        self.enableConsoleCatcher()
        if self.right:
            self.addCSS(
                'cssrightalign', 'li.voice-state{ direction:rtl; }.avatar{ float:right !important; }.user{ display:flex; }.voice-container{margin-top:30px;}.voice-container:before{position:fixed;right:0px;top:0px;}')
        else:
            self.delCSS('cssrightalign')
        if self.showtitle:
            self.enableShowVoiceTitle()
        if self.mutedeaf:
            self.enableMuteDeaf()
        if self.hideinactive:
            self.enableHideInactive()
        if self.chatresize:
            self.addCSS(
                'cssflexybox', 'div.chat-container { width: 100%; height: 100%; top: 0; left: 0; position: fixed; display: flex; flex-direction: column; } div.chat-container > .messages { box-sizing: border-box; width: 100%; flex: 1; }')
        else:
            self.delCSS('cssflexybox')

    def addCSS(self, name, css):
        if self.overlay:
            js = '(function() { css = document.getElementById(\'%s\'); if (css == null) { css = document.createElement(\'style\'); css.type=\'text/css\'; css.id=\'%s\'; document.head.appendChild(css); } css.innerText=\'%s\';})()' % (name, name, css)
            self.overlay.page().runJavaScript(js)

    def delCSS(self, name):
        if self.overlay:
            js = "(function() { css = document.getElementById('%s'); if(css!=null){ css.parentNode.removeChild(css);} })()" % (
                name)
            self.overlay.page().runJavaScript(js)

    @pyqtSlot()
    def toggleEnabled(self, button=None):
        self.enabled = self.enabledButton.isChecked()
        if self.enabled:
            self.showOverlay()
        else:
            self.hideOverlay()

    @pyqtSlot()
    def toggleTitle(self, button=None):
        self.showtitle = self.showTitle.isChecked()
        if self.showtitle:
            self.enableShowVoiceTitle()

    @pyqtSlot()
    def toggleMuteDeaf(self, button=None):
        self.mutedeaf = self.muteDeaf.isChecked()
        if self.muteDeaf.isChecked():
            self.enableMuteDeaf()

    @pyqtSlot()
    def toggleHideInactive(self, button=None):
        self.hideinactive = self.hideInactive.isChecked()
        if self.hideinactive:
            self.enableHideInactive()

    @pyqtSlot()
    def toggleChatResize(self, button=None):
        self.chatresize = self.chatResize.isChecked()
        self.applyTweaks()

    @pyqtSlot()
    def toggleRightAlign(self, button=None):
        self.right = self.rightAlign.isChecked()
        self.applyTweaks()

    @pyqtSlot()
    def changeValueFL(self):
        self.posXL = self.settingsDistanceFromLeft.value()
        self.moveOverlay()

    @pyqtSlot()
    def changeValueFR(self):
        self.posXR = self.settingsDistanceFromRight.value()
        self.moveOverlay()

    @pyqtSlot()
    def changeValueFT(self):
        self.posYT = self.settingsDistanceFromTop.value()
        self.moveOverlay()

    @pyqtSlot()
    def changeValueFB(self):
        self.posYB = self.settingsDistanceFromBottom.value()
        self.moveOverlay()

    def fillPositionWindowOptions(self):
        self.settingsDistanceFromLeft.valueChanged[int].connect(
            self.changeValueFL)
        self.settingsDistanceFromLeft.setMaximum(self.size.width())
        self.settingsDistanceFromLeft.setValue(self.posXL)
        self.settingsDistanceFromRight.valueChanged[int].connect(
            self.changeValueFR)
        self.settingsDistanceFromRight.setMaximum(self.size.width())
        self.settingsDistanceFromRight.setValue(self.posXR)
        self.settingsDistanceFromTop.valueChanged[int].connect(
            self.changeValueFT)
        self.settingsDistanceFromTop.setMaximum(self.size.height())
        self.settingsDistanceFromTop.setInvertedAppearance(True)
        self.settingsDistanceFromTop.setValue(self.posYT)
        self.settingsDistanceFromBottom.valueChanged[int].connect(
            self.changeValueFB)
        self.settingsDistanceFromBottom.setMaximum(self.size.height())
        self.settingsDistanceFromBottom.setInvertedAppearance(True)
        self.settingsDistanceFromBottom.setValue(self.posYB)

    def populateScreenList(self):
        self.ignoreScreenComboBox = True
        screenList = self.app.screens()
        self.settingsScreen.clear()
        for i, s in enumerate(screenList):
            self.settingsScreen.addItem(s.name())
            if s.name() == self.screenName:
                self.settingsScreen.setCurrentIndex(i)

        self.ignoreScreenComboBox = False
        self.chooseScreen()

    def changeScreen(self, index):
        if not self.ignoreScreenComboBox:
            self.screenName = self.settingsScreen.currentText()
            self.chooseScreen()

    def chooseScreen(self):
        screen = None
        screenList = self.app.screens()
        logger.debug("Discovered screens: %r", [s.name() for s in screenList])

        for s in screenList:
            if s.name() == self.screenName:
                screen = s
                logger.debug("Chose screen %s", screen.name())
                break
        # The chosen screen is not in this list. Drop to primary
        else:
            screen = self.app.primaryScreen()
            logger.warning(
                "Chose screen %r as fallback because %r could not be matched", screen.name(), self.screenName)

        # Fill Info!
        self.size = screen.size()
        self.screenName = s.name()
        self.screenOffset = screen.availableGeometry()
        if self.position:
            self.settingsAspectRatio.updateScreen(
                self.size.width(), self.size.height())
            self.fillPositionWindowOptions()
            self.screenShot(screen)
        self.moveOverlay()

    def showPosition(self):
        if self.position is not None:
            self.position.show()
        else:
            # Positional Settings Window
            self.position = QtWidgets.QWidget()
            self.position.setWindowTitle('Overlay %s Position' % (self.name))
            self.positionbox = QtWidgets.QVBoxLayout()

            # Use a grid to lay out screen & sliders
            self.settingsGridWidget = QtWidgets.QWidget()
            self.settingsGrid = QtWidgets.QGridLayout()

            # Use the custom Aspect widget to keep the whole thing looking
            # as close to the user experience as possible
            self.settingsAspectRatio = AspectRatioWidget(
                self.settingsGridWidget)

            # Grid contents
            self.settingsPreview = ResizingImage()
            self.settingsPreview.setMinimumSize(1, 1)
            sizePolicy = QtWidgets.QSizePolicy(
                QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
            self.settingsPreview.setSizePolicy(sizePolicy)
            self.settingsDistanceFromLeft = QtWidgets.QSlider(
                QtCore.Qt.Horizontal)
            self.settingsDistanceFromRight = QtWidgets.QSlider(
                QtCore.Qt.Horizontal)
            self.settingsDistanceFromTop = QtWidgets.QSlider(
                QtCore.Qt.Vertical)
            self.settingsDistanceFromBottom = QtWidgets.QSlider(
                QtCore.Qt.Vertical)

            # Screen chooser
            self.settingsScreen = QtWidgets.QComboBox()

    #        self.position.setMinimumSize(600,600)
            # Save button
            self.settingSave = QtWidgets.QPushButton("Save")

            # Fill Screens, Choose the screen if config is set
            self.populateScreenList()

            self.settingSave.clicked.connect(self.on_save_position)
            self.settingsScreen.currentIndexChanged.connect(self.changeScreen)

            self.settingsGrid.addWidget(self.settingsPreview, 0, 0)
            self.settingsGrid.addWidget(self.settingsDistanceFromLeft, 1, 0)
            self.settingsGrid.addWidget(self.settingsDistanceFromRight, 2, 0)
            self.settingsGrid.addWidget(self.settingsDistanceFromTop, 0, 1)
            self.settingsGrid.addWidget(self.settingsDistanceFromBottom, 0, 2)
            self.settingsGridWidget.setLayout(self.settingsGrid)
            self.positionbox.addWidget(self.settingsScreen)
            self.positionbox.addWidget(self.settingsAspectRatio)
            self.position.setLayout(self.positionbox)
            self.positionbox.addWidget(self.settingSave)
            self.fillPositionWindowOptions()
            self.position.show()

    def showSettings(self):
        if self.settings is not None:
            self.settings.show()
        else:
            self.settings = QtWidgets.QWidget()
            self.settings.setWindowTitle('Overlay %s Layout' % (self.name))
            self.settingsbox = QtWidgets.QVBoxLayout()
            self.settingWebView = QWebEngineView()
            self.rightAlign = QtWidgets.QCheckBox("Right Align")
            self.muteDeaf = QtWidgets.QCheckBox("Show mute and deafen")
            self.chatResize = QtWidgets.QCheckBox("Large chat box")
            self.showTitle = QtWidgets.QCheckBox("Show room title")
            self.hideInactive = QtWidgets.QCheckBox(
                "Hide voice channel when inactive")
            self.enabledButton = QtWidgets.QCheckBox("Enabled")
            self.settingTakeUrl = QtWidgets.QPushButton("Use this Room")
            self.settingTakeAllUrl = QtWidgets.QPushButton("Use all Rooms")

            self.settings.setMinimumSize(400, 400)
            self.settingTakeUrl.clicked.connect(self.on_click)
            self.settingTakeAllUrl.clicked.connect(self.getAllRooms)
            self.settingWebView.loadFinished.connect(self.skip_stream_button)
            self.rightAlign.stateChanged.connect(self.toggleRightAlign)
            self.rightAlign.setChecked(self.right)
            self.muteDeaf.stateChanged.connect(self.toggleMuteDeaf)
            self.muteDeaf.setChecked(self.mutedeaf)
            self.showTitle.stateChanged.connect(self.toggleTitle)
            self.showTitle.setChecked(self.showtitle)
            self.hideInactive.stateChanged.connect(self.toggleHideInactive)
            self.hideInactive.setChecked(self.hideinactive)
            self.enabledButton.stateChanged.connect(self.toggleEnabled)
            self.enabledButton.setChecked(self.enabled)
            self.chatResize.stateChanged.connect(self.toggleChatResize)
            self.chatResize.setChecked(self.chatresize)

            self.settingWebView.load(QtCore.QUrl(
                "https://streamkit.discord.com/overlay"))

            self.settingsbox.addWidget(self.settingWebView)
            self.settingsbox.addWidget(self.rightAlign)
            self.settingsbox.addWidget(self.muteDeaf)
            self.settingsbox.addWidget(self.chatResize)
            self.settingsbox.addWidget(self.showTitle)
            self.settingsbox.addWidget(self.hideInactive)
            self.settingsbox.addWidget(self.enabledButton)
            self.settingsbox.addWidget(self.settingTakeUrl)
            self.settingsbox.addWidget(self.settingTakeAllUrl)
            self.settings.setLayout(self.settingsbox)
            self.settings.show()

    def screenShot(self, screen):
        screenshot = screen.grabWindow(0)
        self.settingsPreview.setImage(screenshot)
        self.settingsPreview.setContentsMargins(0, 0, 0, 0)

    def showOverlay(self):
        if self.overlay:
            return
        self.overlay = QWebEngineView()
        self.overlay.page().setBackgroundColor(QtCore.Qt.transparent)
        self.overlay.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
        self.overlay.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True)
        self.overlay.setWindowFlags(
            QtCore.Qt.X11BypassWindowManagerHint |
            QtCore.Qt.FramelessWindowHint |
            QtCore.Qt.WindowStaysOnTopHint |
            QtCore.Qt.WindowTransparentForInput |
            QtCore.Qt.WindowDoesNotAcceptFocus |
            QtCore.Qt.NoDropShadowWindowHint |
            QtCore.Qt.WindowSystemMenuHint |
            QtCore.Qt.WindowMinimizeButtonHint
        )
        self.overlay.loadFinished.connect(self.applyTweaks)
        self.overlay.load(QtCore.QUrl(self.url))

        self.overlay.setStyleSheet("background:transparent;")
        self.overlay.show()
        self.moveOverlay()

    def hideOverlay(self):
        if self.overlay:
            self.overlay.close()
            self.overlay = None

    def delete(self):
        self.hideOverlay()
        if self.settings:
            self.settings.close()
        if self.position:
            self.position.close()
        self.overlay = None

    def getAllRooms(self):
        getChannel = "[window.channels, window.guilds]"
        self.runJS(getChannel, self.gotAllRooms)

    def gotAllRooms(self, message):
        sep = ''
        url = ''
        for chan in message[0]:
            if chan['type'] == 2:
                url += sep+"https://streamkit.discord.com/overlay/voice/%s/%s?icon=true&online=true&logo=white&text_color=%%23ffffff&text_size=14&text_outline_color=%%23000000&text_outline_size=0&text_shadow_color=%%23000000&text_shadow_size=0&bg_color=%%231e2124&bg_opacity=0.95&bg_shadow_color=%%23000000&bg_shadow_size=0&limit_speaking=false&small_avatars=false&hide_names=false&fade_chat=0" % (message[1], chan[
                    'id'])
                sep = ','

        if self.overlay:
            self.overlay.load(QtCore.QUrl(url))
        self.url = url
        self.save()
        self.settings.close()
        self.settings = None
コード例 #33
0
ファイル: DrrrChatRoom.py プロジェクト: xin053/DrrrClient
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()
コード例 #34
0
ファイル: main.py プロジェクト: Zadrayca/Kourse
class Browzer(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.initUi()
        self.init_signals()

    def initUi(self):
        loadUi('mainwindow.ui', self)

        self.webView = QWebView(self)
        self.mainLayout.addWidget(self.webView)
        self.init_history_buttons()

    def init_signals(self):
        self.actionAboutQt.triggered.connect(self.about_qt)

        self.backBtn.clicked.connect(self.webView.back)
        self.forwardBtn.clicked.connect(self.webView.forward)
        self.query.returnPressed.connect(self.on_enter_query)
        self.searchBtn.clicked.connect(self.on_enter_query)

        self.webView.urlChanged.connect(self.init_history_buttons)
        self.webView.urlChanged.connect(self.set_query)
        self.webView.titleChanged.connect(self.on_title_changed)
        self.webView.page().linkHovered.connect(self.on_link_hovered)
        self.bookWidget.setVisible(False)
        self.actionBook.triggered.connect(self.bookWidget.setVisible)
        self.bookmarksBtn.clicked.connect(self.add_favor)
        self.textBrowser.anchorClicked.connect(self.webView.load)

    def init_history_buttons(self):
        history = self.webView.page().history()

        self.backBtn.setEnabled(history.canGoBack())
        self.forwardBtn.setEnabled(history.canGoForward())

    def about_qt(self):
        QMessageBox.aboutQt(self, 'O Qt')

    def on_enter_query(self):
        url = QUrl.fromUserInput(self.query.text())
        self.webView.load(url)

    def on_title_changed(self, title):
        name = self.windowTitle().split(' | ').pop()
        self.setWindowTitle(title + ' | ' + name)

    def set_query(self, url):
        if isinstance(url, QUrl):
            self.query.setText(url.toString())

    def on_link_hovered(self, url, *args, **kwargs):
        self.statusBar().showMessage(url)  # по идее url.toString()

    def add_favor(self, title):
        #<a href="url">text</a>
        #self.textBrowser.insertHtml(self.query.text())

        url = self.query.text()

        # self.textBrowser.append('<a herf="%s">%s</a>') % url

        x = ('<a href="%s">%s</a>') % (url, url)
        print(x)
        self.textBrowser.append(x)
コード例 #35
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# See http://doc.qt.io/qt-5/qwebengineview.html#details

# This class replace the deprecated QWebView (based on QtWebKit).
# See:
# - https://stackoverflow.com/questions/29055475/qwebview-or-qwebengineview
# - https://wiki.qt.io/QtWebEngine/Porting_from_QtWebKit

import sys
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)

web = QWebEngineView()
web.load(QUrl("http://www.jdhp.org"))
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)
コード例 #36
0
ファイル: test2.py プロジェクト: ricleal/PythonCode
#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""

QWebView with URL
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget
#from PyQt5.QtWebKitWidgets import QWebView
from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView
from PyQt5.QtCore import QUrl

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = QWebView()
    w.resize(800, 600)
    w.move(300, 300)
    w.setWindowTitle('Simple Plot')
    w.load(QUrl("http://google.com/"));
    w.show()

    sys.exit(app.exec_())
コード例 #37
0
class MainProdutos(Ui_ct_MainProdutos, Ui_ct_FormProdutos):
    def mainprodutos(self, frame):
        super(MainProdutos, self).setMainProdutos(frame)
        self.frameMainProdutos.show()

        # Icone Botoes
        self.IconeBotaoForm(self.bt_AddNovoProduto,
                            self.resourcepath('Images/addNovo.svg'))
        self.IconeBotaoMenu(self.bt_BuscaProduto,
                            self.resourcepath('Images/search.png'))
        self.IconeBotaoMenu(self.bt_PrintRelatProdutos,
                            self.resourcepath('Images/gtk-print.png'))

        # Desabiltando Signals tabela
        self.tb_produtos.blockSignals(True)

        # Tamanho campos tabela
        self.tb_produtos.setColumnHidden(0, True)
        self.tb_produtos.setColumnWidth(1, 10)
        self.tb_produtos.setColumnWidth(2, 40)
        self.tb_produtos.setColumnWidth(3, 450)
        self.tb_produtos.setColumnWidth(4, 80)
        self.tb_produtos.setColumnWidth(5, 147)
        self.tb_produtos.setColumnWidth(6, 147)
        self.tb_produtos.setColumnWidth(7, 40)

        # Populando tabela produtos
        self.DataTabProdutos()

        # Busca produto
        self.tx_BuscaProduto.textEdited.connect(self.DataTabProdutos)

        # Botao Adicionar Produto
        self.bt_AddNovoProduto.clicked.connect(self.FormProdutos)

        # Botao Imprimir Produtos
        self.bt_PrintRelatProdutos.clicked.connect(self.imprimirProdutos)

        # Dados Tabela Produto
    def DataTabProdutos(self):
        lista = CrudProduto()
        lista.produto = self.tx_BuscaProduto.text()
        lista.listaProduto()

        while self.tb_produtos.rowCount() > 0:
            self.tb_produtos.removeRow(0)

        i = 0
        if len(lista.produto) >= 1:
            while i < len(lista.produto):
                self.tb_produtos.insertRow(i)
                self.conteudoTabela(self.tb_produtos, i, 0, str(lista.id[i]))
                self.TabelaStatus(self.tb_produtos, i, 1,
                                  self.StatusEntrega(1))
                self.TabelaID(self.tb_produtos, i, 2, lista.id[i])
                self.TabelaNomeTelefone(self.tb_produtos, i, 3,
                                        lista.produto[i], lista.marca[i])
                self.TabelaQtdeStatus(
                    self.tb_produtos, i, 4, str(lista.qtdeProduto[i]),
                    self.StatusStoque(lista.qtdeProduto[i],
                                      lista.estoqueMinimo[i]))
                self.ValorProduto(self.tb_produtos, i, 5,
                                  lista.valorUnitario[i])
                self.ValorProduto(self.tb_produtos, i, 6,
                                  lista.valorAtacado[i])
                # Sinal click tabela
                self.botaoTabela(self.tb_produtos, i, 7,
                                 partial(self.SelectProduto, lista.id[i]),
                                 "#005099")
                i += 1
        pass

    # Frame Formulário Produtos
    def FormProdutos(self):
        self.DesativaBotaoProdutos()
        self.LimpaFrame(self.ct_containerProdutos)
        super(MainProdutos, self).setFormProdutos(self.ct_containerProdutos)
        # Ocultando alguns Campos
        self.tx_AddCategoria.setHidden(True)
        self.tx_AddMarca.setHidden(True)
        self.bt_CalcelAddMarca.setHidden(True)
        self.bt_CancelAddCatergoria.setHidden(True)
        self.bt_DelImagem.setHidden(True)
        # Mostandro Frame
        self.fr_FormProdutos.show()

        # Icone Botoes
        self.IconeBotaoMenu(self.bt_SalvarProdutos,
                            self.resourcepath('Images/salvar.png'))
        self.IconeBotaoMenu(self.bt_CancelarProdutos,
                            self.resourcepath('Images/cancelar.png'))
        self.IconeBotaoMenu(self.bt_BuscaProduto,
                            self.resourcepath('Images/search.png'))
        self.IconeBotaoMenu(self.bt_AddImagem,
                            self.resourcepath('Images/edit-add.png'))
        self.IconeBotaoMenu(self.bt_DelImagem,
                            self.resourcepath('Images/edit-delete.png'))
        self.IconeBotaoMenu(self.bt_AddCategoriaProduto,
                            self.resourcepath('Images/edit-add.png'))
        self.IconeBotaoMenu(self.bt_AddMarcaProduto,
                            self.resourcepath('Images/edit-add.png'))

        self.IconeBotaoMenu(self.bt_CalcelAddMarca,
                            self.resourcepath('Images/edit-delete.png'))
        self.IconeBotaoMenu(self.bt_CancelAddCatergoria,
                            self.resourcepath('Images/edit-delete.png'))
        self.lb_qtdeMin.setPixmap(
            QPixmap(self.resourcepath('Images/warnig.svg')))
        self.label_2.setPixmap(
            QPixmap(self.resourcepath('Images/CodBarra.png')))

        # Checando se existe ID válido
        self.IdCheckProduto()

        # Validar campos Inteiros
        validar = QIntValidator(1, 999, self)
        self.tx_EstoqueMaximoProduto.setValidator(validar)
        self.tx_EstoqueMinimoProduto.setValidator(validar)
        self.tx_MinimoAtacado.setValidator(validar)
        validarValor = QDoubleValidator(0.50, 999.99, 2, self)
        validarValor.setNotation(QDoubleValidator.StandardNotation)
        validarValor.setDecimals(2)
        # validarValor.setRange(000.50, 999.99, 2)
        self.tx_ValorCompraProduto.setValidator(validarValor)
        self.tx_ValorAtacadoProduto.setValidator(validarValor)
        self.tx_ValorUnitarioProduto.setValidator(validarValor)
        # Fim Valida Campos

        # Calculando Margem de lucro
        self.tx_ValorUnitarioProduto.textChanged.connect(
            partial(self.CalculoPorcentagem, self.tx_ValorUnitarioProduto,
                    self.tx_PorcentagemVarejo))
        self.tx_ValorAtacadoProduto.textChanged.connect(
            partial(self.CalculoPorcentagem, self.tx_ValorAtacadoProduto,
                    self.tx_PorcentagemAtacado))
        # Fim Calculo porcentagem

        # Botao Upload e Cancelar Imagem
        self.bt_AddImagem.clicked.connect(self.UploadImagem)
        self.bt_DelImagem.clicked.connect(self.DelImagem)

        # Botao Add Categoria e populando combobox e check
        self.modelCombo = self.cb_CategoriaProduto.model()
        self.ListaCategoria()
        self.bt_AddCategoriaProduto.clicked.connect(self.AddCategoria)
        self.tx_AddCategoria.returnPressed.connect(self.AddCategoriaDb)
        self.cb_CategoriaProduto.currentIndexChanged.connect(self.listaMarca)
        self.bt_CancelAddCatergoria.clicked.connect(
            partial(self.CalcelAdd, self.bt_CancelAddCatergoria,
                    self.bt_AddCategoriaProduto, self.tx_AddCategoria,
                    self.cb_CategoriaProduto))
        # Fim Add Categoria

        # Botao Add Marca
        self.bt_AddMarcaProduto.clicked.connect(self.AddMarca)
        self.tx_AddMarca.returnPressed.connect(self.AddMarcaDb)
        self.bt_CalcelAddMarca.clicked.connect(
            partial(self.CalcelAdd, self.bt_CalcelAddMarca,
                    self.bt_AddMarcaProduto, self.tx_AddMarca,
                    self.cb_MarcaProduto))
        # Fim Add Marca

        # Botão Voltar
        self.bt_CancelarProdutos.clicked.connect(self.janelaProdutos)

        # Botao Salvar
        self.bt_SalvarProdutos.clicked.connect(self.VerificaInputProduto)

    # Desativando Botões
    def DesativaBotaoProdutos(self):
        self.bt_AddNovoProduto.setEnabled(False)
        self.tx_BuscaProduto.setEnabled(False)
        self.bt_BuscaProduto.setEnabled(False)

    # Ativando Botes

    def AtivaBotaoProdutos(self):
        self.bt_AddNovoProduto.setEnabled(True)
        self.tx_BuscaProduto.setEnabled(True)
        self.bt_BuscaProduto.setEnabled(True)

    # upload Imagem
    def UploadImagem(self):
        Dialog = QFileDialog()
        Dialog.setOption(QFileDialog.DontUseNativeDialog, True)

        fname = Dialog.getOpenFileName(self, "Selecionar Imagem", "",
                                       "Image files (*.jpg *.png)")[0]

        self.lb_FotoProduto.setPixmap(
            QPixmap(fname).scaledToWidth(
                150, Qt.TransformationMode(Qt.FastTransformation)))
        # self.lb_FotoProduto.setScaledContents(True)
        self.bt_AddImagem.setHidden(True)
        self.bt_DelImagem.setVisible(True)

    def DelImagem(self):
        self.lb_FotoProduto.clear()
        self.bt_DelImagem.setHidden(True)
        self.bt_AddImagem.setVisible(True)

    # checando campo Id se é Edicao ou Novo Produto
    def IdCheckProduto(self):
        if not self.tx_idProduto.text():
            busca = CrudProduto()
            self.tx_idProduto.setText(str(busca.lastIdProduto()))

    # Lista combobox categoria
    def ListaCategoria(self):
        busca = CrudCatProduto()
        busca.listaCatProduto()

        for cat in busca.query:
            self.cb_CategoriaProduto.addItem(cat.categoria_produto,
                                             str(cat.id))

    # Listando marca por categoria

    def listaMarca(self, index):
        self.cb_MarcaProduto.clear()
        self.cb_MarcaProduto.addItem("SELECIONE")
        lista = CrudMarcaProduto()

        if self.cb_CategoriaProduto.count() > 0:
            id = self.cb_CategoriaProduto.currentData()
            lista.id = id
        lista.listaMarcaProdutos()

        for marca in lista.query:
            self.cb_MarcaProduto.addItem(marca.marca_produto, str(marca.id))

            pass
        # self.cb_MarcaProduto.addItems(busca.marca)
        # cindex = self.cb_MarcaProduto.findData('4')
        # self.cb_MarcaProduto.setCurrentIndex(cindex)

    # Funcao Botao Add Categoria e marca
    def AddMarca(self):
        self.cb_MarcaProduto.setHidden(True)
        self.bt_AddMarcaProduto.setHidden(True)
        self.bt_CalcelAddMarca.setVisible(True)
        self.tx_AddMarca.setVisible(True)
        self.tx_AddMarca.setFocus()

    def AddCategoria(self):
        self.cb_CategoriaProduto.setHidden(True)
        self.bt_AddCategoriaProduto.setHidden(True)
        self.bt_CancelAddCatergoria.setVisible(True)
        self.tx_AddCategoria.setVisible(True)
        self.tx_AddCategoria.setFocus()

    # Fim Botoes Categoria e Marca

    # Cancelado Add Marca / Categoria
    def CalcelAdd(self, *args):
        args[0].setHidden(True)
        args[1].setVisible(True)
        args[2].setHidden(True)
        args[3].setVisible(True)
        args[3].setFocus()

    # Add Marca Banco de Dados
    def AddMarcaDb(self):
        rowMarca = self.cb_MarcaProduto.count()
        INSERT = CrudMarcaProduto()
        self.cb_MarcaProduto.addItem(self.tx_AddMarca.text(),
                                     str(INSERT.lastIdMarcaProduto()))
        self.tx_AddMarca.setHidden(True)
        self.cb_MarcaProduto.setVisible(True)
        self.cb_MarcaProduto.setCurrentIndex(rowMarca)
        self.tx_AddMarca.clear()
        INSERT.id = INSERT.lastIdMarcaProduto()
        INSERT.marca_produto = self.cb_MarcaProduto.currentText()
        INSERT.inseriMarcaProduto()
        self.CalcelAdd(self.bt_CalcelAddMarca, self.bt_AddMarcaProduto,
                       self.tx_AddMarca, self.cb_MarcaProduto)

    # Add Categoria Banco de Dados
    def AddCategoriaDb(self):
        rowCategoria = self.cb_CategoriaProduto.count()
        INSERT = CrudCatProduto()
        self.cb_CategoriaProduto.addItem(self.tx_AddCategoria.text(),
                                         INSERT.lastIdCatProduto())
        self.tx_AddCategoria.setHidden(True)
        self.cb_CategoriaProduto.setVisible(True)
        INSERT.id = INSERT.lastIdCatProduto()
        INSERT.categoria_produto = self.tx_AddCategoria.text()
        INSERT.inseriCatProduto()
        self.tx_AddCategoria.clear()

        self.CalcelAdd(self.bt_CancelAddCatergoria,
                       self.bt_AddCategoriaProduto, self.tx_AddCategoria,
                       self.cb_CategoriaProduto)
        self.cb_CategoriaProduto.setCurrentIndex(rowCategoria)

    # Calculo porcentagem
    def CalculoPorcentagem(self, *args):
        if self.tx_ValorCompraProduto.text().replace(',', '.'):
            if float(self.tx_ValorCompraProduto.text().replace(
                    ',', '.')) > float(0):
                if args[0].text().replace(
                        ',',
                        '.') and float(args[0].text().replace(',', '.')) > 0:
                    lucro = float(args[0].text().replace(',', '.')) - \
                        float(self.tx_ValorCompraProduto.text().replace(',', '.'))
                    lucro = lucro / \
                        float(args[0].text().replace(',', '.')) * 100
                args[1].setText(format(lucro, ".2f"))

    # Verificando Inputs
    def VerificaInputProduto(self):
        if not self.tx_DescricaoProduto.text():
            self.tx_DescricaoProduto.setFocus()
        elif self.cb_CategoriaProduto.currentIndex() == 0:
            self.cb_CategoriaProduto.setFocus()
        elif self.cb_MarcaProduto.currentIndex() == 0:
            self.cb_MarcaProduto.setFocus()
        elif not self.tx_EstoqueMinimoProduto.text():
            self.tx_EstoqueMinimoProduto.setFocus()
        elif not self.tx_EstoqueMaximoProduto.text():
            self.tx_EstoqueMaximoProduto.setFocus()
        elif not self.tx_ValorCompraProduto.text():
            self.tx_ValorCompraProduto.setFocus()
        elif not self.tx_ValorUnitarioProduto.text():
            self.tx_ValorUnitarioProduto.setFocus()
        elif not self.tx_ValorAtacadoProduto.text():
            self.tx_ValorAtacadoProduto.setFocus()
        elif not self.tx_MinimoAtacado.text():
            self.tx_MinimoAtacado.setFocus()
        else:
            self.cadProduto()
        pass

        # Cadastro Produto
    def cadProduto(self):
        INSERI = CrudProduto()
        INSERI.id = self.tx_idProduto.text()
        INSERI.produto = self.tx_DescricaoProduto.text().upper()
        if self.lb_FotoProduto.pixmap():
            imagem = QPixmap(self.lb_FotoProduto.pixmap())
            data = QByteArray()
            buf = QBuffer(data)
            imagem.save(buf, 'PNG')
            INSERI.imagem = str(data.toBase64()).encode('utf8')[2:-1]
        else:
            INSERI.imagem = False

        INSERI.categoria = self.cb_CategoriaProduto.currentData()
        INSERI.marca = self.cb_MarcaProduto.currentData()
        INSERI.estoqueMinimo = self.tx_EstoqueMinimoProduto.text()
        INSERI.estoqueMaximo = self.tx_EstoqueMaximoProduto.text()
        INSERI.obsProduto = self.tx_ObsProduto.text()
        INSERI.valorCompra = self.tx_ValorCompraProduto.text()
        INSERI.valorUnitario = self.tx_ValorUnitarioProduto.text()
        INSERI.valorAtacado = self.tx_ValorAtacadoProduto.text()
        INSERI.qtdeAtacado = self.tx_MinimoAtacado.text()
        INSERI.inseriProduto()

        self.janelaProdutos()

    # Selecionando Produto
    def SelectProduto(self, valor):
        id = valor
        self.FormProdutos()
        self.tx_idProduto.setText(str(id))
        busca = CrudProduto()
        busca.id = id
        busca.selectProdutoId()
        self.tx_DescricaoProduto.setText(busca.produto)
        if busca.imagem:
            pixmap = QPixmap()
            pixmap.loadFromData(QByteArray.fromBase64(busca.imagem))
            self.lb_FotoProduto.setPixmap(
                pixmap.scaledToWidth(
                    150, Qt.TransformationMode(Qt.FastTransformation)))
            # self.lb_FotoProduto.setScaledContents(True)
            self.bt_AddImagem.setHidden(True)
            self.bt_DelImagem.setVisible(True)

        self.cb_CategoriaProduto.setCurrentIndex(
            self.cb_CategoriaProduto.findData(busca.categoria))
        self.cb_MarcaProduto.setCurrentIndex(
            self.cb_MarcaProduto.findData(busca.marca))
        self.tx_EstoqueMinimoProduto.setText(str(busca.estoqueMinimo))
        self.tx_EstoqueMaximoProduto.setText(str(busca.estoqueMaximo))
        self.tx_ObsProduto.setText(busca.obsProduto)
        self.tx_ValorCompraProduto.setText(str(busca.valorCompra))
        self.tx_ValorUnitarioProduto.setText(str(busca.valorUnitario))
        self.tx_ValorAtacadoProduto.setText(str(busca.valorAtacado))
        self.tx_MinimoAtacado.setText(str(busca.qtdeAtacado))

    # Imprimindo
    def imprimirProdutos(self):
        self.documento = QWebEngineView()

        headertable = [
            "Cod", "Descrição", "Disponível", "Valor Unitário", "Valor Atacado"
        ]

        cod = []
        produto = []
        qtde = []
        vunit = []
        vatac = []
        qtdeatac = []

        i = 0
        for i in range(self.tb_produtos.rowCount()):
            cod.append(self.tb_produtos.cellWidget(i, 2).text())
            produto.append(self.tb_produtos.cellWidget(i, 3).text())
            qtde.append(self.tb_produtos.cellWidget(i, 4).text())
            vunit.append(self.tb_produtos.cellWidget(i, 5).text())
            vatac.append(self.tb_produtos.cellWidget(i, 6).text())

        html = self.renderTemplate(
            "estoque.html",
            estilo=self.resourcepath('Template/estilo.css'),
            titulo="LISTAGEM PRODUTOS",
            headertable=headertable,
            codProduto=cod,
            descPRoduto=produto,
            qtdeEstoque=qtde,
            valorUnitario=vunit,
            valorAtacado=vatac)

        self.documento.load(QUrl("file:///" +
                                 self.resourcepath("report.html")))
        self.documento.loadFinished['bool'].connect(self.previaImpressao)
コード例 #38
0
ファイル: 22_browser_test.py プロジェクト: nnaabbcc/exercise
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl

import sys

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = QWebEngineView()
    view.load(QUrl('https://www.baidu.com'))
    view.show()
    sys.exit(app.exec_())
コード例 #39
0
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)
コード例 #40
0
class Principal(QMainWindow):
    def __init__(self):
        super().__init__()
        loadUi("principal2.ui", self)
        self.setWindowTitle("BusquedaCaminos")
        self.grafo = TGrafo()
        self.consultar.clicked.connect(self.Ver_Caminos)
        self.insertarciudad.clicked.connect(self.insertar_ciudad)
        self.insertarviaje.clicked.connect(self.insertar_viaje)
        cargargrafo(self.grafo)
        #print(self.grafo.tamanio)
        self.browser = QWebEngineView()
        self.browser.resize(500, 500)
        self.vermapa.clicked.connect(self.cargar_mapa)
        self.recorridomapa.clicked.connect(self.vermaparecorrido)
        self.show()

    def Ver_Caminos(self):
        self.recorridos.clear()
        self.combo.clear()
        valor1 = self.origennn.text()
        valor2 = self.destinooo.text()
        aux = busqueda(self.grafo, valor1)
        #print(aux.arcos.tamanio)
        if (aux != None):
            resultado = buscarcaminos2(self.grafo, valor1,
                                       valor2)  #resultado != []:
            self.resultado = resultado
            if resultado != []:
                cont = 0
                for solucion in resultado:
                    self.recorridos.append(" CAMINOS " + str(cont))
                    self.recorridos.append(" ")
                    self.combo.addItem(" CAMINOS " + str(cont))
                    barrido(solucion, self.recorridos)
                    self.recorridos.append(" ")
                    cont += 1
            else:
                self.recorridos.append(" NO HAY CAMINO")
        else:
            self.recorridos.append(" NO HAY CAMINO")

    def vermaparecorrido(self):
        if (self.combo.count() > 0):
            pila = self.resultado[self.combo.currentIndex()]
            paux = tpila()
            lista = []
            while (not pila_vacia(pila)):
                x = desapilar(pila)
                lista.append(x[0])
                apilar(paux, x)
            while (not pila_vacia(paux)):
                x = desapilar(paux)
                apilar(pila, x)
            m = MapaUrl()
            m.tipomapa(0)
            m.set_marcadores(lista)
            m.set_camino(lista)
            url = m.get_url()
            print(url)
            self.browser.load(QUrl(url))
            self.browser.show()

    """
    def mostrar_camino(resultado):
        for solucion in resultado:
            barrido(solucion)
            print()
    """

    def cargar_mapa(self):
        m = MapaUrl()
        m.tipomapa(0)
        lista = []
        aux = self.grafo.cab
        while (aux != None):
            lista.append(aux.info)
            aux = aux.sig
        m.set_marcadores(lista)
        #m.set_camino(lista)
        url = m.get_url()
        print(url)
        self.browser.load(QUrl(url))
        self.browser.show()

    def insertar_ciudad(self):
        self.ciudad.clear()
        #cargargrafo(self.grafo)
        ciud = self.insertarciud.text()
        if ciud != '':
            aux = busqueda(self.grafo, ciud)
            if (aux == None):
                insertarg(self.grafo, ciud, 'V')
                self.ciudad.append(" Se ha agregado con exito ")
                print(self.grafo.tamanio)
            else:
                aux1 = aux.arcos.cab
                self.ciudad.append(" Arcos:")
                while (aux1 != None):
                    self.ciudad.append(aux1.info)
                    aux1 = aux1.sig
        else:
            self.ciudad.append(" Debe ingresar una ciudad ")

    def insertar_viaje(self):
        self.viajes.clear()
        #cargargrafo(self.grafo)
        ori = self.origen.text()
        des = self.destino.text()
        ruta = self.opcioness.text()
        aux = busqueda(self.grafo, ori)
        aux1 = busqueda(self.grafo, des)
        if (ori != '') and ((des != '') and (ruta != '')):
            if (aux != None):
                if (aux1 != None):
                    insertarg(aux.arcos, des, 'A', 0, ruta)
                    self.viajes.append(" Se ha agregado con exito")
                else:
                    self.viajes.append(" El destino no esta cargado")
            else:
                self.viajes.append(" El origen no esta cargado")

                #aux2 = aux.arcos.cab
                #while(aux2!=None):
                #    self.viajes.append('',aux2.info)
                #    aux2 = aux2.sig
        else:
            self.viajes.append(" Debe ingresar todos los datos")
コード例 #41
0
ファイル: browser.py プロジェクト: GalaxyGroot/anki-plugins
class AwBrowser(QDialog):
    """
        Customization and configuration of a web browser to run within Anki
    """

    SINGLETON = None
    TITLE = 'Anki :: Web Browser Addon'

    _parent = None
    _fields = []
    _selectionHandler = None
    _web = None
    _context = None
    _lastAssignedField = None
    infoList = []
    providerList = []

    def __init__(self, myParent):
        QDialog.__init__(self, None)
        self._parent = myParent
        self.setupUI()

        if myParent:

            def wrapClose(fn):
                def clozeBrowser(evt):
                    self.close()
                    fn(evt)

                return clozeBrowser

            myParent.closeEvent = wrapClose(myParent.closeEvent)

    def setupUI(self):
        self.setWindowTitle(AwBrowser.TITLE)
        self.setWindowFlags(Qt.WindowMinMaxButtonsHint
                            | Qt.WindowCloseButtonHint)
        self.setGeometry(450, 200, 800, 450)
        self.setMinimumWidth(640)
        self.setMinimumHeight(450)
        self.setStyleSheet(Style.DARK_BG)

        mainLayout = QVBoxLayout()
        mainLayout.setContentsMargins(0, 0, 0, 0)
        mainLayout.setSpacing(0)
        self.setLayout(mainLayout)

        self._web = QWebEngineView(self)
        self._web.contextMenuEvent = self.contextMenuEvent
        self._web.page().loadStarted.connect(self.onStartLoading)
        self._web.page().loadFinished.connect(self.onLoadFinish)
        self._web.page().loadProgress.connect(self.onProgress)
        self._web.page().urlChanged.connect(self.onPageChange)

        # -------------------- Top / toolbar ----------------------
        navtbar = QToolBar("Navigation")
        navtbar.setIconSize(QSize(16, 16))
        mainLayout.addWidget(navtbar)

        backBtn = QAction(
            QtGui.QIcon(os.path.join(CWD, 'assets', 'arrow-back.png')), "Back",
            self)
        backBtn.setStatusTip("Back to previous page")
        backBtn.triggered.connect(self._web.back)
        navtbar.addAction(backBtn)

        self.forwardBtn = QAction(
            QtGui.QIcon(os.path.join(CWD, 'assets', 'arrow-forward.png')),
            "Forward", self)
        self.forwardBtn.setStatusTip("Next visited page")
        self.forwardBtn.triggered.connect(self._web.forward)
        navtbar.addAction(self.forwardBtn)

        refreshBtn = QAction(
            QtGui.QIcon(os.path.join(CWD, 'assets', 'reload.png')), "Reload",
            self)
        refreshBtn.setStatusTip("Reload")
        refreshBtn.triggered.connect(self._web.reload)
        navtbar.addAction(refreshBtn)

        self.createProvidersMenu(navtbar)

        self._itAddress = QtWidgets.QLineEdit(self)
        self._itAddress.setObjectName("itSite")
        self._itAddress.setStyleSheet('background-color: #F5F5F5;')
        self._itAddress.returnPressed.connect(self._goToAddress)
        navtbar.addWidget(self._itAddress)

        cbGo = QAction(QtGui.QIcon(os.path.join(CWD, 'assets', 'go-icon.png')),
                       "Go", self)
        cbGo.setObjectName("cbGo")
        navtbar.addAction(cbGo)
        cbGo.triggered.connect(self._goToAddress)

        self.stopBtn = QAction(
            QtGui.QIcon(os.path.join(CWD, 'assets', 'stop.png')), "Stop", self)
        self.stopBtn.setStatusTip("Stop loading")
        self.stopBtn.triggered.connect(self._web.stop)
        navtbar.addAction(self.stopBtn)
        # -------------------- Center ----------------------
        mainLayout.addWidget(self._web)
        # -------------------- Bottom bar ----------------------

        bottomWidget = QtWidgets.QWidget(self)
        bottomWidget.setFixedHeight(30)

        bottomLayout = QtWidgets.QHBoxLayout(bottomWidget)
        bottomLayout.setObjectName("bottomLayout")
        bottomWidget.setStyleSheet('color: #FFF;')

        lbSite = QtWidgets.QLabel(bottomWidget)
        lbSite.setObjectName("label")
        lbSite.setText("Context: ")
        lbSite.setFixedWidth(70)
        lbSite.setStyleSheet('font-weight: bold;')
        bottomLayout.addWidget(lbSite)

        self.ctxWidget = QtWidgets.QLabel(bottomWidget)
        self.ctxWidget.width = 300
        self.ctxWidget.setStyleSheet('text-align: left;')
        bottomLayout.addWidget(self.ctxWidget)

        self._loadingBar = QtWidgets.QProgressBar(bottomWidget)
        self._loadingBar.setFixedWidth(100)
        self._loadingBar.setProperty("value", 100)
        self._loadingBar.setObjectName("loadingBar")
        bottomLayout.addWidget(self._loadingBar)

        mainLayout.addWidget(bottomWidget)

        if cfg.getConfig().browserAlwaysOnTop:
            self.setWindowFlags(Qt.WindowStaysOnTopHint)

    @classmethod
    def singleton(cls, parent):
        if not cls.SINGLETON:
            cls.SINGLETON = AwBrowser(parent)
        return cls.SINGLETON

    def formatTargetURL(self, website: str, query: str = ''):
        return website.format(urllib.parse.quote(query, encoding='utf8'))

    @exceptionHandler
    def open(self, website, query: str):
        """
            Loads a given page with its replacing part with its query, and shows itself
        """

        self._context = query
        self._updateContextWidget()
        target = self.formatTargetURL(website, query)
        self._web.load(QUrl(target))
        self._itAddress.setText(target)

        self.show()
        self.raise_()
        return self._web

    def unload(self):
        try:
            self._web.setHtml(BLANK_PAGE)
            self._itAddress.setText('about:blank')
        except (RuntimeError) as err:
            pass

    def onClose(self):
        self._parent = None
        self._web.close()
        self.close()

    def onStartLoading(self):
        self.stopBtn.setEnabled(True)
        self._loadingBar.setProperty("value", 1)

    def onProgress(self, prog):
        self._loadingBar.setProperty("value", prog)

    def onLoadFinish(self, result):
        self.stopBtn.setDisabled(True)
        self._loadingBar.setProperty("value", 100)

        if not result:
            Feedback.log('No result on loading page! ')

    def _goToAddress(self):
        q = QUrl(self._itAddress.text())
        if q.scheme() == "":
            q.setScheme("http")

        self._web.load(q)
        self._web.show()

    def onPageChange(self, url):
        if url and url.toString().startswith('http'):
            self._itAddress.setText(url.toString())
        self.forwardBtn.setEnabled(self._web.history().canGoForward())

    def welcome(self):
        self._web.setHtml(WELCOME_PAGE)
        self._itAddress.setText('about:blank')
        self.show()
        self.raise_()

    def _updateContextWidget(self):
        self.ctxWidget.setText(self._context)

# ---------------------------------------------------------------------------------

    def createProvidersMenu(self, parentWidget):
        providerBtn = QAction(
            QtGui.QIcon(os.path.join(CWD, 'assets', 'gear-icon.png')),
            "Providers", parentWidget)
        providerBtn.setStatusTip("Search with Provider")
        providerBtn.triggered.connect(
            lambda: self.newProviderMenu(providerBtn))
        parentWidget.addAction(providerBtn)

    def newProviderMenu(self, parentBtn):
        ctx = ProviderSelectionController()
        ctx.showCustomMenu(parentBtn.parentWidget(), self.reOpenSameQuery)

    @exceptionHandler
    def reOpenSameQuery(self, website):
        self.open(website, self._context)

# ------------------------------------ Menu ---------------------------------------

    def _makeMenuAction(self, field, value, isLink):
        """
            Creates correct operations for the context menu selection.
            Only with lambda, it would repeat only the last element
        """
        def _processMenuSelection():
            self._lastAssignedField = field
            self._selectionHandler(field, value, isLink)

        return _processMenuSelection

    def contextMenuEvent(self, evt):
        """
            Handles the context menu in the web view. 
            Shows and handle options (from field list), only if in edit mode.
        """

        if not (self._fields and self._selectionHandler):
            return self.createInfoMenu(evt)

        isLink = False
        value = None
        if self._web.selectedText():
            isLink = False
            value = self._web.selectedText()
        else:
            if (self._web.page().contextMenuData().mediaType()
                    == QWebEngineContextMenuData.MediaTypeImage
                    and self._web.page().contextMenuData().mediaUrl()):
                isLink = True
                value = self._web.page().contextMenuData().mediaUrl()
                Feedback.log('Link: ' + value.toString())
                Feedback.log('toLocal: ' + value.toLocalFile())

                if not self._checkSuffix(value):
                    return

        if not value:
            Feedback.log('No value')
            return self.createInfoMenu(evt)

        if QApplication.keyboardModifiers() == Qt.ControlModifier:
            if self._assignToLastField(value, isLink):
                return

        self.createCtxMenu(value, isLink, evt)

    def _checkSuffix(self, value):
        if value and not value.toString().endswith(
            ("jpg", "jpeg", "png", "gif")):
            msgLink = value.toString()
            if len(value.toString()) < 80:
                msgLink = msgLink[:50] + '...' + msgLink[50:]
            answ = QMessageBox.question(
                self, 'Anki support',
                """This link may not be accepted by Anki: \n\n "%s" \n
Usually the suffix should be one of 
(jpg, jpeg, png, gif).
Try it anyway? """ % msgLink, QMessageBox.Yes | QMessageBox.No)

            if answ != QMessageBox.Yes:
                return False

        return True

    def createCtxMenu(self, value, isLink, evt):
        'Creates and configures the menu itself'

        m = QMenu(self)
        m.addAction(QAction('Copy', m, triggered=lambda: self._copy(value)))
        m.addSeparator()

        labelAct = QAction(Label.BROWSER_ASSIGN_TO, m)
        labelAct.setDisabled(True)
        m.addAction(labelAct)
        # sub = QMenu(Label.BROWSER_ASSIGN_TO, m)
        m.setTitle(Label.BROWSER_ASSIGN_TO)
        for index, label in self._fields.items():
            act = QAction(label,
                          m,
                          triggered=self._makeMenuAction(index, value, isLink))
            m.addAction(act)

        # m.addMenu(sub)
        action = m.exec_(self.mapToGlobal(evt.pos()))

    def createInfoMenu(self, evt):
        'Creates and configures a menu with only some information'
        m = QMenu(self)
        for item in self.infoList:
            act = QAction(item)
            act.setEnabled(False)
            m.addAction(act)
        action = m.exec_(self.mapToGlobal(evt.pos()))

    def _assignToLastField(self, value, isLink):
        'Tries to set the new value to the same field used before, if set...'

        if self._lastAssignedField:
            if self._lastAssignedField in self._fields:
                self._selectionHandler(self._lastAssignedField, value, isLink)
                return True
            else:
                self._lastAssignedField = None
        return False

    def _copy(self, value):
        if not value:
            return
        clip = QApplication.clipboard()
        clip.setText(value if isinstance(value, str) else value.toString())

    def load(self, qUrl):
        self._web.load(qUrl)

#   ----------------- getter / setter  -------------------

    def setFields(self, fList):
        self._fields = fList

    def setSelectionHandler(self, value):
        self._selectionHandler = value
コード例 #42
0
ファイル: single-site-browser.py プロジェクト: zacanger/z
    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_()
コード例 #43
0
ファイル: syncthingui.py プロジェクト: coolshou/syncthingui
class MainWindow(QMainWindow):

    """Main window class."""

    def __init__(self):
        """Init class."""
        super(MainWindow, self).__init__()
        self.pixmap_syncthingui = QPixmap(":/images/syncthingui.svg")
        tf = QTransform()
        self.pixmap_syncthingui0 = QPixmap(":/images/syncthingui.svg")
        tf.rotate(90.0)
        self.pixmap_syncthingui1 = self.pixmap_syncthingui0.transformed(tf)
        tf.rotate(180.0)
        self.pixmap_syncthingui2 = self.pixmap_syncthingui0.transformed(tf)
        tf.rotate(270.0)
        self.pixmap_syncthingui3 = self.pixmap_syncthingui0.transformed(tf)

        self.init_gui()
        self.init_menu()
        self.init_systray()

        self.run()

    def init_gui(self):
        """init gui setup"""
        self.setWindowIcon(QIcon(self.pixmap_syncthingui))

        self.progressbar = QProgressBar()
        self.statusBar().showMessage(getoutput(SYNCTHING + ' --version'))
        self.statusBar().addPermanentWidget(self.progressbar)
        self.setWindowTitle(__doc__.strip().capitalize())
        self.setMinimumSize(900, 600)
        self.setMaximumSize(1280, 1024)
        self.resize(self.minimumSize())
        self.center()

        # QWebView
        # self.view = QWebView(self)
        self.view = QWebEngineView(self)
        self.view.loadStarted.connect(self.start_loading)
        self.view.loadFinished.connect(self.finish_loading)
        self.view.loadProgress.connect(self.loading)
        self.view.titleChanged.connect(self.set_title)
        self.view.page().linkHovered.connect(
            lambda link_txt: self.statusBar().showMessage(link_txt[:99], 3000))
        QShortcut("Ctrl++", self, activated=lambda:
                  self.view.setZoomFactor(self.view.zoomFactor() + 0.2))
        QShortcut("Ctrl+-", self, activated=lambda:
                  self.view.setZoomFactor(self.view.zoomFactor() - 0.2))
        QShortcut("Ctrl+0", self, activated=lambda: self.view.setZoomFactor(1))
        QShortcut("Ctrl+q", self, activated=lambda: self.close())

        # syncthing console
        self.consolewidget = QWidget(self)
        # TODO: start at specify (w,h)
        self.consolewidget.setMinimumSize(QSize(200, 100))
        # TODO: setStyleSheet
        # self.consolewidget.setStyleSheet("margin:0px; padding: 0px; \
        # border:1px solid rgb(0, 0, 0);")
        # border-radius: 40px;")
        # TODO read syncthing console visible from setting
        # self.consolewidget.setVisible(False)
        # self.consolewidget.showEvent
        # self.consoletextedit = QPlainTextEdit(parent=self.consolewidget)
        self.consoletoolbar = QWidget(self)
        hlayout = QHBoxLayout()
        hlayout
        self.consoletoolbar.setLayout(hlayout)
        self.consoletextedit = QTextEdit(parent=self.consolewidget)
        self.consoletextedit.setWordWrapMode(QTextOption.NoWrap)
        # self.consoletextedit.setStyleSheet(" border:1px solid rgb(0, 0, 0);")
        # self.consoletextedit.setStyleSheet("margin:0px; padding: 0px;")
        layout = QVBoxLayout()
        layout.addWidget(self.consoletoolbar)
        layout.addWidget(self.consoletextedit)

        self.consolewidget.setLayout(layout)

        self.splitter = QSplitter(Qt.Vertical)
        self.splitter.addWidget(self.view)
        self.splitter.addWidget(self.consolewidget)

        # process
        self.process = QProcess()
        self.process.error.connect(self._process_failed)
        # QProcess emits `readyRead` when there is data to be read
        self.process.readyRead.connect(self._process_dataReady)
        self.process.stateChanged.connect(self._process_stateChanged)
        # Just to prevent accidentally running multiple times
    # Disable the button when process starts, and enable it when it finishes
    # self.process.started.connect(lambda: self.runButton.setEnabled(False))
    # self.process.finished.connect(lambda: self.runButton.setEnabled(True))

        # backend options
        self.chrt = QCheckBox("Smooth CPU ", checked=True)
        self.ionice = QCheckBox("Smooth HDD ", checked=True)
        self.chrt.setToolTip("Use Smooth CPUs priority (recommended)")
        self.ionice.setToolTip("Use Smooth HDDs priority (recommended)")
        self.chrt.setStatusTip(self.chrt.toolTip())
        self.ionice.setStatusTip(self.ionice.toolTip())
        # main toolbar
        self.toolbar = self.addToolBar("SyncthinGUI Toolbar")
        # self.toolbar.addAction(QIcon.fromTheme("media-playback-stop"),
        self.toolbar.addAction(QIcon(":/images/stop.svg"),
                               "Stop Sync", lambda: self.syncthing_stop())
        # self.toolbar.addAction(QIcon.fromTheme("media-playback-start"),
        self.toolbar.addAction(QIcon(":/images/start.svg"),
                               "Restart Sync", lambda: self.run())
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.chrt)
        self.toolbar.addWidget(self.ionice)
        self.toolbar.addSeparator()
        # TODO: test event API
        self.toolbar.addAction(QIcon(":/images/start.svg"),
                               "test ", lambda: self.test())

        # final gui setup
        self.setCentralWidget(self.splitter)

    def test(self):
        """ test some function """
        print("test")

    def init_menu(self):
        """init menu setup"""
        # file menu
        file_menu = self.menuBar().addMenu("File")
        # TODO: setting menu item
        file_menu.addAction("Exit", lambda: self.close())
        # Syncthing menu
        sync_menu = self.menuBar().addMenu("Syncthing")
        sync_menu.addAction("Start Syncronization", lambda: self.run())
        sync_menu.addAction("Stop Syncronization",
                            lambda: self.syncthing_stop())
        # TODO: restart
        # TODO: reflash F5
        sync_menu.addAction("Open in external browser",
                            lambda: open_new_tab(URL))

        # view menu
        view_menu = self.menuBar().addMenu("View")
        # TODO: syncthing console menu
        view_menu.addAction("syncthing console", lambda: self.show_console)
        #
        zoom_menu = view_menu.addMenu("Zoom browser")
        zoom_menu.addAction(
            "Zoom In",
            lambda: self.view.setZoomFactor(self.view.zoomFactor() + .2))
        zoom_menu.addAction(
            "Zoom Out",
            lambda: self.view.setZoomFactor(self.view.zoomFactor() - .2))
        zoom_menu.addAction(
            "Zoom To...",
            lambda: self.view.setZoomFactor(QInputDialog.getInt(
                self, __doc__, "<b>Zoom factor ?:", 1, 1, 9)[0]))
        zoom_menu.addAction("Zoom Reset", lambda: self.view.setZoomFactor(1))
        view_menu.addSeparator()
        act = view_menu.addAction("View Page Source",
                                  lambda: self.view_syncthing_source)
        act.setDisabled(True)

        # window menu
        window_menu = self.menuBar().addMenu("&Window")
        window_menu.addAction("Minimize", lambda: self.showMinimized())
        window_menu.addAction("Maximize", lambda: self.showMaximized())
        window_menu.addAction("Restore", lambda: self.showNormal())
        window_menu.addAction("Center", lambda: self.center())
        window_menu.addAction("Top-Left", lambda: self.move(0, 0))
        window_menu.addAction("To Mouse",
                              lambda: self.move_to_mouse_position())
        window_menu.addAction("Fullscreen", lambda: self.showFullScreen())
        window_menu.addSeparator()
        window_menu.addAction("Increase size", lambda: self.resize(
            self.size().width() * 1.2, self.size().height() * 1.2))
        window_menu.addAction("Decrease size", lambda: self.resize(
            self.size().width() // 1.2, self.size().height() // 1.2))
        window_menu.addAction("Minimum size", lambda:
                              self.resize(self.minimumSize()))
        window_menu.addAction("Maximum size", lambda:
                              self.resize(self.maximumSize()))
        window_menu.addAction("Horizontal Wide", lambda: self.resize(
            self.maximumSize().width(), self.minimumSize().height()))
        window_menu.addAction("Vertical Tall", lambda: self.resize(
            self.minimumSize().width(), self.maximumSize().height()))
        window_menu.addSeparator()
        window_menu.addAction("Disable Resize",
                              lambda: self.setFixedSize(self.size()))
        # help menu
        help_menu = self.menuBar().addMenu("&Help")
        help_menu.addAction("Support Forum", lambda: open_new_tab(HELP_URL_0))
        help_menu.addAction("Lastest Release",
                            lambda: open_new_tab(HELP_URL_1))
        help_menu.addAction("Documentation", lambda: open_new_tab(HELP_URL_2))
        help_menu.addAction("Bugs", lambda: open_new_tab(HELP_URL_3))
        help_menu.addAction("Source Code", lambda: open_new_tab(HELP_URL_4))
        help_menu.addSeparator()
        help_menu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self))
        help_menu.addAction("About Python 3",
                            lambda: open_new_tab('https://www.python.org'))
        help_menu.addAction("About " + __doc__,
                            lambda: QMessageBox.about(self, __doc__, HELPMSG))
        help_menu.addSeparator()
        help_menu.addAction("Keyboard Shortcuts", lambda:
                            QMessageBox.information(self, __doc__, SHORTCUTS))
        help_menu.addAction("View GitHub Repo", lambda: open_new_tab(__url__))
        if not sys.platform.startswith("win"):
            help_menu.addAction("Show Source Code", lambda: self.view_source())
        help_menu.addSeparator()
        help_menu.addAction("Check Updates", lambda: self.check_for_updates())

    def init_systray(self):
        """init system tray icon"""
        # self.tray = QSystemTrayIcon(QIcon(self.pixmap_syncthingui), self)
        self.tray = AnimatedSysTrayIcon(QIcon(self.pixmap_syncthingui), self)
        self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui0))
        self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui1))
        self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui2))
        self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui3))

        self.tray.setToolTip(__doc__.strip().capitalize())
        traymenu = QMenu(self)
        traymenu.addAction(__doc__).setDisabled(True)
        traymenu.addSeparator()
        # to test animate
        # traymenu.addAction("start", lambda: self.tray.animate_start())
        # traymenu.addAction("stop", lambda: self.tray.animate_stop())
        # traymenu.addSeparator()
        traymenu.addAction("Stop Sync", lambda: self.syncthing_stop())
        traymenu.addAction("Restart Sync", lambda: self.run())
        traymenu.addSeparator()
        traymenu.addAction("Show", lambda: self.show_gui())
        traymenu.addAction("Hide", lambda: self.hide())
        traymenu.addSeparator()
        # traymenu.addAction("Open Web", lambda: open_new_tab(URL))
        # traymenu.addAction("Quit All", lambda: self.close())
        traymenu.addAction("Quit All", lambda: self.app_exit())
        self.tray.setContextMenu(traymenu)
        self.tray.show()

    def show_gui(self):
        """
        Helper method to show UI, this should not be needed, but I discovered.
        """
        self.showNormal()
        # webview require 70Mb to show webpage
        self.view.load(QUrl(URL))

    def syncthing_start(self):
        """syncthing start"""
        self.run()

    def syncthing_stop(self):
        """syncthing stop"""
        print("try to stop syncthing")
        self.process.kill()
        # check there is no other syncthing is running!
        for proc in psutil.process_iter():
            # check whether the process name matches
            # print("procress: %s " % proc.name())
            if proc.name() == SYNCTHING:
                proc.kill()

    def run(self):
        """Run bitch run!."""
        # Stop first!
        self.syncthing_stop()

        command_to_run_syncthing = " ".join((
            "ionice --ignore --class 3" if self.ionice.isChecked() else "",
            "chrt --verbose --idle 0" if self.chrt.isChecked() else "",
            SYNCTHING, "-no-browser"))
        print(command_to_run_syncthing)
        self.process.start(command_to_run_syncthing)
        if not self.process.waitForStarted():
            self._process_failed()

    @pyqtSlot()
    def _process_failed(self):
        """Read and return errors."""
        self.statusBar().showMessage("ERROR:Fail:Syncthing blow up in pieces!")
        print("ERROR:Fail:Syncthing blow up in pieces! Wheres your God now?")
        return str(self.process.readAllStandardError()).strip().lower()

    @pyqtSlot()
    def _process_dataReady(self):
        """get process stdout/strerr when data ready"""
        # TODO: format the msg to remove extra b and \n
        msg = str(self.process.readAll())
        lines = msg.split("'")
        tmp = lines[1]
        tmp = tmp.splitlines(0)
        lines = tmp[0].split("\\n")
        for line in lines:
            if line != "":
                # print("1: %s" % line)
                self.consoletextedit.append(line)
        self.consoletextedit.ensureCursorVisible()
        # autoscroll to last line's first character
        self.consoletextedit.moveCursor(QTextCursor.End)
        self.consoletextedit.moveCursor(QTextCursor.StartOfLine)

    @pyqtSlot(QProcess.ProcessState)
    def _process_stateChanged(self, state):
        """ procress_stateChanged """
        # TODO handle procress_stateChanged
        print("procress_stateChanged: %s" % state)

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerpoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerpoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def show_console(self):
        """Show syncthing console"""
        visible = not self.consolewidget.isVisible
        print("bVisible: %s" % visible)
        self.consolewidget.setVisible(True)
        self.consolewidget.resize(QSize(200, 100))

    def view_source(self):
        """ TODO: Call methods to load and display source code."""
        # call(('xdg-open ' if sys.platform.startswith("linux") else 'open ')
        #      + __file__, shell=True)
        pass

    def view_syncthing_source(self):
        """Call methods to load and display web page source code."""
        print("view_syncthing_source start")
        # access_manager = self.view.page().networkAccessManager()
        # reply = access_manager.get(QNetworkRequest(self.view.url()))
        # reply.finished.connect(self.slot_source_downloaded)

    def slot_source_downloaded(self):
        """Show actual page source code."""
        reply = self.sender()
        # TODO: highlight html source editor/viewer
        self.textedit = QPlainTextEdit()
        self.textedit.setAttribute(Qt.WA_DeleteOnClose)
        self.textedit.setReadOnly(True)
        self.textedit.setPlainText(QTextStream(reply).readAll())
        self.textedit.show()
        reply.deleteLater()

    @pyqtSlot()
    def start_loading(self):
        """show progressbar when downloading data"""
        self.progressbar.show()

    @pyqtSlot(bool)
    def finish_loading(self, finished):
        """Finished loading content."""
        if not finished:
            # TODO: When loading fail, what should we do?
            print("load fail")
            if self.process.state() == QProcess.NotRunning:
                self.run()
                self.view.reload()
            # if self.process.state != QProcess.Running:
            #    print("syncthing is not running: %s" % self.process.state())
            # pass
        print("finish_loading: %s" % finished)
        # TODO: WebEngineView does not have following function?
        # self.view.settings().clearMemoryCaches()
        # self.view.settings().clearIconDatabase()

        # print("finish_loading %s" % datetime.strftime(datetime.now(),
        #                                              '%Y-%m-%d %H:%M:%S'))
        # TODO: following line need 6 sec to finish!!
        # TODO: (" INFO: Loading Web UI increases >250Mb RAM!.")
        # self.view.page().mainFrame().evaluateJavaScript(BASE_JS)
        # print("finish_loading %s" % datetime.strftime(datetime.now(),
        #                                             '%Y-%m-%d %H:%M:%S'))
        self.progressbar.hide()

    @pyqtSlot(int)
    def loading(self, idx):
        """loading content"""
        #print("loading %s" % idx)
        self.progressbar.setValue(idx)

    @pyqtSlot(str)
    def set_title(self, title):
        """set title when webview's title change"""
        # print("title: %s" % title)
        if len(title.strip()) > 0:
            self.setWindowTitle(self.view.title()[:99])

    def check_for_updates(self):
        """Method to check for updates from Git repo versus this version."""
        # print("TODO: https://github.com/coolshou/syncthingui/releases/latest")

        print("__version__: %s" % __version__)
        '''
        this_version = str(open(__file__).read())
        print("this_version: %s" % this_version)
        last_version = str(request.urlopen(__source__).read().decode("utf8"))
        print("last_version: %s" % last_version)

        TODO: previous use file compare, when diff then there is new file!!
        if this_version != last_version:
            m = "Theres new Version available!<br>Download update from the web"
        else:
            m = "No new updates!<br>You have the lastest version of" + __doc__
        return QMessageBox.information(self, __doc__.title(), "<b>" + m)
'''
    def closeEvent(self, event):
        """Ask to Quit."""
        if self.tray.isVisible():
            if self.tray.supportsMessages():
                self.tray.showMessage("Info",
                                      "The program will keep running in the "
                                      "system tray. To terminate the program,"
                                      " choose <b>Quit</b> in the context "
                                      "menu of the system tray entry.")
            else:
                print(" System tray not supports balloon messages ")
            self.hide()
            event.ignore()

    def app_exit(self):
        """exit app"""
        # TODO: do we need to show UI when doing close?
        # self.show_gui()
        # TODO: show QMessageBox on all virtual desktop
        the_conditional_is_true = QMessageBox.question(
            self, __doc__.title(), 'Quit %s?' % __doc__,
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        if the_conditional_is_true:
            self.syncthing_stop()
            self.ani_stop = True
            QApplication.instance().quit
            quit()