Example #1
0
class Event(QWidget):

    def __init__(self, parent=None):
        super(Event, self).__init__(parent)

        self.setWindowTitle('loadFinished Event')


        url = QUrl('https://www.torproject.org/')

        self.webView = QWebView()
        self.webView.setUrl(url)

        page = self.webView.page()
        frame = page.mainFrame()

        frame.loadFinished.connect(self.load_finished)
    

        self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.webView)

        self.setLayout(self.mainLayout)


    def load_finished(self):
        print 'load has finished'
Example #2
0
class HtmlFavoritePage():
    def __init__(self, page, layout, parent):
        self.page = page
        self.parent = parent
        
        container = QVBoxLayout()
        # actions section
        actionsContainer = QHBoxLayout()
        
        self.saveButton = QPushButton('Save')
        self.saveButton.clicked.connect(lambda: save_clicked(self))
                
        actionsContainer.addWidget(QLabel('Link: '))
        self.linkText = QLineEdit(page.url)
        
        label = QLabel('<a href="' + page.url + '">Open Externally</a>')
        label.setOpenExternalLinks(True)
        
        actionsContainer.addWidget(self.linkText)
        actionsContainer.addWidget(self.saveButton)
        actionsContainer.addWidget(label)
        container.addLayout(actionsContainer)
        
        # content 
        self.view = QWebView()
        self.view.setUrl(page.url)
        container.addWidget(self.view)
        layout.addLayout(container)        
Example #3
0
class webView():
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(400, 600)
        MainWindow.setMinimumSize(QtCore.QSize(400, 600))
        MainWindow.setMaximumSize(QtCore.QSize(400, 600))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.webView = QWebView(self.centralwidget)
        self.webView.setUrl(QtCore.QUrl("about:blank"))
        self.webView.setObjectName("webView")
        self.gridLayout.addWidget(self.webView, 0, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 300, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

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

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
Example #4
0
def main():
    app = QtGui.QApplication(sys.argv)
    browser = QWebView()
    browser.setWindowTitle('CreativeDrive Brazil')
    browser.setUrl(QUrl('http://127.0.0.1:5000'))
    browser.showMaximized()

    w = QtGui.QWidget()
    trayIcon = SystemTrayIcon(QtGui.QIcon("static/images/ico.png"), w)

    trayIcon.show()
    sys.exit(app.exec_())
Example #5
0
class TestLoadFinished(TimedQApplication):
    '''Test case for signal QWebView.loadFinished(bool)'''

    def setUp(self):
        #Acquire resources
        TimedQApplication.setUp(self, timeout=1000)
        self.view = QWebView()
        QObject.connect(self.view, SIGNAL('loadFinished(bool)'),
                        self.load_finished)
        self.called = False

    def tearDown(self):
        #Release resources
        del self.view
        self.called = False
        TimedQApplication.tearDown(self)

    def testLoadFinishedFromFile(self):
        url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__))
        self.view.setUrl(url)
        self.app.exec_()

        self.assert_(self.called)

    def testSetPageAndGetPage(self):
        twp = testWebPage()
        self.view.setPage(twp)
        del twp
        p = self.view.page()
        self.assertEqual(p.sayMyName(), 'testWebPage')

        # Setting the same webpage should not incref the python obj
        refCount = sys.getrefcount(p)
        self.view.setPage(p)
        self.assertEquals(sys.getrefcount(p), refCount)

        # Changing the webpage obj should decref the old one
        twp2 = testWebPage()
        self.view.setPage(twp2)
        self.assertEquals(sys.getrefcount(p), refCount - 1)

    def load_finished(self, ok):
        #Callback to check if load was successful
        self.app.quit()
        if ok:
            self.called = True
Example #6
0
class TestLoadFinished(TimedQApplication):
    '''Test case for signal QWebView.loadFinished(bool)'''
    def setUp(self):
        #Acquire resources
        TimedQApplication.setUp(self, timeout=1000)
        self.view = QWebView()
        QObject.connect(self.view, SIGNAL('loadFinished(bool)'),
                        self.load_finished)
        self.called = False

    def tearDown(self):
        #Release resources
        del self.view
        self.called = False
        TimedQApplication.tearDown(self)

    def testLoadFinishedFromFile(self):
        url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__))
        self.view.setUrl(url)
        self.app.exec_()

        self.assert_(self.called)

    def testSetPageAndGetPage(self):
        twp = testWebPage()
        self.view.setPage(twp)
        del twp
        p = self.view.page()
        self.assertEqual(p.sayMyName(), 'testWebPage')

        # Setting the same webpage should not incref the python obj
        refCount = sys.getrefcount(p)
        self.view.setPage(p)
        self.assertEquals(sys.getrefcount(p), refCount)

        # Changing the webpage obj should decref the old one
        twp2 = testWebPage()
        self.view.setPage(twp2)
        self.assertEquals(sys.getrefcount(p), refCount - 1)

    def load_finished(self, ok):
        #Callback to check if load was successful
        self.app.quit()
        if ok:
            self.called = True
class UserAgentExample(QWidget):

    def __init__(self, parent=None):
        super(UserAgentExample, self).__init__(parent)

        self.setWindowTitle('Custom User Agent Example')

        url = QUrl('http://getmyuseragent.com')
        page = CustomWebPage()

        self.webView = QWebView()
        self.webView.setPage(page)
        self.webView.setUrl(url)

        self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.webView)

        self.setLayout(self.mainLayout)
Example #8
0
class Basic(QWidget):

    def __init__(self, parent=None):
        # call QWidget's __init__
        super(Basic, self).__init__(parent)

        self.setWindowTitle('Basic Application')

        url = QUrl('http://www.bitcoin.org/')

        # declare our QWebView and set the URL. The URL must be an instance of QUrl, not a string
        self.webView = QWebView()
        self.webView.setUrl(url)

        # set up our layout and add the instance of the QWebView
        self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.webView)

        self.setLayout(self.mainLayout)
Example #9
0
class Settings(QWidget):

    def __init__(self, parent=None):
        super(Settings, self).__init__(parent)

        self.setWindowTitle('Settings, Debugger Application')

        url = QUrl('http://www.bitcoin.org/')

        settings = QWebSettings.globalSettings()
        settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)

        # more settings
        # http://pyside.org/docs/pyside/PySide/QtWebKit/QWebSettings.html#detailed-description

        self.webView = QWebView()
        self.webView.setUrl(url)

        self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.webView)

        self.setLayout(self.mainLayout)
Example #10
0
from urllib import urlretrieve
from selenium import webdriver
import time
import sys

from albert_fixtures import url

from PySide import QtGui
from PySide import QtCore
from PySide.QtWebKit import QWebView, QWebSettings

app = QtGui.QApplication(sys.argv)

win = QWebView()

win.setUrl(QtCore.QUrl(url))

print "Getting frame..."
frame = win.page().mainFrame().documentElement()
print dir(win.page())

print "Getting button..."
button = frame.findFirst("#video_mode > label:nth-child(5)")
button.evaluateJavaScript("this.click()")

print "Getting image..."
image = frame.findFirst("#img1")

print "Done."
win.show()
app.exec_()
Example #11
0
class Form(QMainWindow):

    def __init__(self, home, parent=None, *, stayOnTop=False, debug=False):
        super().__init__(parent)
        if stayOnTop:
            flags = self.windowFlags()
            flags |= Qt.WindowStaysOnTopHint
            self.setWindowFlags(flags)
        self.home = home
        self.debug = debug
        self.filenamesForWord = {}
        self.titleForFilename = {}
        self.createWidgets()
        self.createLayout()
        self.createConnections()
        self.createShortcuts()
        self.changePage(self.home)
        self.updateUi()
        if self.debug:
            self.mtime = 0
            self.timer = QTimer(self)
            self.timer.start(250)
            self.timer.timeout.connect(self.timeout)
        self.loadSettings()
        with open(Lib.get_path("doc/xix_style.css"), "r",
                  encoding=UTF8) as file:
            self.css = file.read()
        self.browser.setFocus()
        self.setWindowTitle("Help — {}".format(
            QApplication.applicationName()))


    def timeout(self):
        mtime = self.get_mtime()
        if mtime and mtime != self.mtime:
            self.mtime = mtime
            self.browser.reload()


    def get_mtime(self):
        filename = self.browser.url().toLocalFile()
        try:
            return os.path.getmtime(filename) if filename else 0
        except FileNotFoundError:
            time.sleep(0.1)
            return 0


    def createWidgets(self):
        self.backButton = QToolButton()
        self.backButton.setIcon(QIcon(":/go-back.svg"))
        self.backButton.setText("&Back")
        self.backButton.setToolTip("""\
<p><b>Back</b> ({})</p>
<p>Navigate to the previous page.</p>""".format(
            QKeySequence("Alt+Left").toString()))
        self.forwardButton = QToolButton()
        self.forwardButton.setIcon(QIcon(":/go-forward.svg"))
        self.forwardButton.setText("&Forward")
        self.forwardButton.setToolTip("""\
<p><b>Forward</b> ({})</p>
<p>Navigate to the page you've just come back from.</p>""".format(
            QKeySequence("Alt+Right").toString()))
        self.contentsButton = QToolButton()
        self.contentsButton.setIcon(QIcon(":/go-home.svg"))
        self.contentsButton.setText("&Contents")
        self.contentsButton.setToolTip("""\
<p><b>Contents</b> ({})</p>
<p>Navigate to the contents page.</p>""".format(
            QKeySequence("Alt+Home").toString()))
        self.searchLineEdit = Widgets.LegendLineEdit.LineEdit(
            "Search (F3 or Ctrl+F)")
        self.searchLineEdit.setToolTip("""\
<p><b>Search editor</p>
<p>Type in a word to search for in the online help pages and press
<b>Enter</b> or <b>F3</b> to search.</p>""")
        self.zoomInButton = QToolButton()
        self.zoomInButton.setIcon(QIcon(":/zoomin.svg"))
        self.zoomInButton.setText("&Zoom In")
        self.zoomInButton.setToolTip("""\
<p><b>Zoom In</b> ({})</p>
<p>Make the text bigger.</p>""".format(
            QKeySequence("Alt++").toString()))
        self.zoomOutButton = QToolButton()
        self.zoomOutButton.setIcon(QIcon(":/zoomout.svg"))
        self.zoomOutButton.setText("Zoom &Out")
        self.zoomOutButton.setToolTip("""\
<p><b>Zoom Out</b> ({})</p>
<p>Make the text smaller.</p>""".format(
            QKeySequence("Alt+-").toString()))
        width = self.fontMetrics().width(self.zoomOutButton.text() + " ")
        for button in (self.backButton, self.forwardButton,
                       self.contentsButton, self.zoomInButton,
                       self.zoomOutButton):
            button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
            button.setMinimumWidth(width)
            button.setFocusPolicy(Qt.NoFocus)
        self.browser = QWebView()
        page = self.browser.page()
        page.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        if self.debug:
            self.urlLabel = QLabel()


    def createLayout(self):
        hbox = QHBoxLayout()
        hbox.addWidget(self.backButton)
        hbox.addWidget(self.forwardButton)
        hbox.addWidget(self.contentsButton)
        hbox.addWidget(self.searchLineEdit, 1)
        hbox.addWidget(self.zoomInButton)
        hbox.addWidget(self.zoomOutButton)
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addWidget(self.browser, 1)
        if self.debug:
            vbox.addWidget(self.urlLabel)
        widget = QWidget()
        widget.setLayout(vbox)
        self.setCentralWidget(widget)


    def createConnections(self):
        self.browser.urlChanged.connect(self.updateUi)
        self.browser.linkClicked.connect(self.changePage)
        self.backButton.clicked.connect(self.browser.back)
        self.forwardButton.clicked.connect(self.browser.forward)
        self.contentsButton.clicked.connect(
            lambda: self.changePage(self.home))
        self.searchLineEdit.returnPressed.connect(self.search)
        self.searchLineEdit.textEdited.connect(self.search)
        self.zoomInButton.clicked.connect(lambda: self.zoom(1.1))
        self.zoomOutButton.clicked.connect(lambda: self.zoom(0.9))


    def createShortcuts(self):
        QShortcut(QKeySequence(Qt.Key_Escape), self, self.close)
        QShortcut(QKeySequence("Alt+Left"), self, self.browser.back)
        QShortcut(QKeySequence("Alt+Right"), self, self.browser.forward)
        QShortcut(QKeySequence("Alt+Home"), self, self.contentsButton.click)
        QShortcut(QKeySequence("Ctrl++"), self, self.zoomInButton.click)
        QShortcut(QKeySequence("Ctrl+="), self, self.zoomInButton.click)
        QShortcut(QKeySequence("Ctrl+-"), self, self.zoomOutButton.click)
        QShortcut(QKeySequence("F3"), self, self.search)
        QShortcut(QKeySequence("Ctrl+F"), self, self.search)
        if self.debug:
            QShortcut(QKeySequence(Qt.Key_F5), self, self.browser.reload)


    def changePage(self, page):
        if isinstance(page, QUrl) and not page.scheme():
            page = page.toString()
        if isinstance(page, str):
            url = QUrl.fromLocalFile(Lib.get_path(os.path.join("doc",
                                                               page)))
        else:
            url = page
            if not url.isLocalFile():
                webbrowser.open(url.toString())
                return
        self.browser.setUrl(url)


    def search(self):
        self.searchLineEdit.setFocus()
        text = self.searchLineEdit.text()
        words = self.searchWordsSet(text)
        if not words:
            return
        if not self.filenamesForWord:
            self.populateUrlForWord()
        result = [HTML_TOP.format(self.css)]
        pages1, pages2 = self.acquirePageSets(words)
        if not pages1 and not pages2:
            result.append("""\
<h3><font color=darkgray>No help pages match <i>{}</i></font></h3>"""
                          .format("</i> or <i>".join(text.split())))
        else:
            n = len(pages1) + len(pages2)
            result.append("""\
<h3><font color=navy>{:,} help page{} match{} <i>{}</i>:</font></h3><ul>"""
                          .format(n, "s" if n != 1 else "",
                                  "es" if n == 1 else "",
                                  "</i> or <i>".join(text.split())))
            for page in itertools.chain(sorted(pages1), (None,),
                                        sorted(pages2)):
                line = ("</ul><br><ul>" if page is None else
                        "<li><a href='{}'>{}</a></li>\n".format(page[1],
                                                                page[0]))
                result.append(line)
            result.append("</ul>\n")
        result.append("</body></html>\n")
        self.browser.setHtml("".join(result))


    def searchWordsSet(self, text):
        if len(text) < 2:
            return None
        words = set()
        for word in frozenset(re.split(r"\W+", text.strip().casefold())):
            words.add(word)
            words.add(Lib.stem(word))
        return words


    def acquirePageSets(self, words):
        pages1 = set()
        pages2 = set()
        for word in words:
            filenames = self.filenamesForWord.get(word, set())
            if filenames:
                for filename in filenames:
                    title = self.titleForFilename[filename]
                    if words & self.searchWordsSet(
                            Lib.htmlToPlainText(title)):
                        pages1.add((title, filename))
                    else:
                        pages2.add((title, filename))
        return pages1, pages2


    def populateUrlForWord(self):
        self.filenamesForWord = {}
        path = Lib.get_path("doc")
        for filename in os.listdir(path):
            if filename.endswith(".html"):
                with open(os.path.join(path, filename), "r",
                          encoding=UTF8) as file:
                    text = file.read()
                match = re.search(r"<title>(.*?)</title>", text,
                                  re.IGNORECASE)
                title = filename if match is None else match.group(1)
                self.titleForFilename[filename] = title
                text = Lib.htmlToPlainText(text).casefold()
                for word in re.split(r"\W+", text):
                    if word:
                        self.filenamesForWord.setdefault(
                            word, set()).add(filename)
                        wordstem = Lib.stem(word)
                        if wordstem and wordstem != word:
                            self.filenamesForWord.setdefault(
                                wordstem, set()).add(filename)


    def zoom(self, factor):
        factor *= self.browser.textSizeMultiplier()
        self.browser.setTextSizeMultiplier(factor)
        settings = QSettings()
        settings.setValue(HELP_ZOOM, factor)


    def updateUi(self):
        history = self.browser.history()
        self.backButton.setEnabled(history.canGoBack())
        self.forwardButton.setEnabled(history.canGoForward())
        self.contentsButton.setEnabled(self.browser.url() != self.home)
        if self.debug:
            self.urlLabel.setText(self.browser.url().toString())
            self.mtime = self.get_mtime()


    def showEvent(self, event):
        self.loadSettings()


    def loadSettings(self):
        settings = QSettings()
        zoom = float(settings.value(HELP_ZOOM, 1.0))
        if not Lib.isclose(zoom, 1.0):
            self.browser.setTextSizeMultiplier(zoom)
        self.restoreGeometry(settings.value(HELP_GEOMETRY))


    def hideEvent(self, event):
        self.saveSettings()


    def closeEvent(self, event):
        self.saveSettings()


    def saveSettings(self):
        settings = QSettings()
        settings.setValue(HELP_GEOMETRY, self.saveGeometry())
Example #12
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1270, 570)
        MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.list_kategori = QtGui.QListWidget(self.centralwidget)
        self.list_kategori.setGeometry(QtCore.QRect(20, 100, 141, 261))
        self.list_kategori.setObjectName("list_kategori")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 80, 59, 18))
        self.label.setObjectName("label")
        self.list_item = QtGui.QListWidget(self.centralwidget)
        self.list_item.setGeometry(QtCore.QRect(200, 100, 141, 261))
        self.list_item.setObjectName("list_item")
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(200, 80, 59, 18))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(170, 220, 21, 31))
        font = QtGui.QFont()
        font.setPointSize(30)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.webview = QWebView(self.centralwidget)
        self.webview.setGeometry(QtCore.QRect(370, 10, 880, 500))
        self.webview.setUrl(QtCore.QUrl("about:blank"))
        self.webview.setObjectName("webview")
        self.btn_tampil = QtGui.QPushButton(self.centralwidget)
        self.btn_tampil.setGeometry(QtCore.QRect(250, 370, 88, 34))
        self.btn_tampil.setObjectName("btn_tampil")
        self.label_4 = QtGui.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(70, 10, 221, 61))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setWeight(50)
        font.setBold(False)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.scrollArea = QtGui.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(20, 429, 321, 71))
        self.scrollArea.setFrameShape(QtGui.QFrame.NoFrame)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setAlignment(QtCore.Qt.AlignLeading
                                     | QtCore.Qt.AlignLeft
                                     | QtCore.Qt.AlignTop)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 321, 71))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.horizontalLayout = QtGui.QHBoxLayout(
            self.scrollAreaWidgetContents)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_deskripsi = QtGui.QLabel(self.scrollAreaWidgetContents)
        self.label_deskripsi.setAlignment(QtCore.Qt.AlignLeading
                                          | QtCore.Qt.AlignLeft
                                          | QtCore.Qt.AlignTop)
        self.label_deskripsi.setWordWrap(True)
        self.label_deskripsi.setObjectName("label_deskripsi")
        self.horizontalLayout.addWidget(self.label_deskripsi)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.label_butir = QtGui.QLabel(self.centralwidget)
        self.label_butir.setGeometry(QtCore.QRect(20, 410, 321, 18))
        font = QtGui.QFont()
        font.setWeight(75)
        font.setBold(True)
        self.label_butir.setFont(font)
        self.label_butir.setObjectName("label_butir")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1270, 30))
        self.menubar.setObjectName("menubar")
        self.menuTentang = QtGui.QMenu(self.menubar)
        self.menuTentang.setObjectName("menuTentang")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuTentang.menuAction())

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

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            QtGui.QApplication.translate("MainWindow", "Kamus SIBI", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.label.setText(
            QtGui.QApplication.translate("MainWindow", "Kategori", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(
            QtGui.QApplication.translate("MainWindow", "Butir", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(
            QtGui.QApplication.translate("MainWindow", ">", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.btn_tampil.setText(
            QtGui.QApplication.translate("MainWindow", "Tampilkan", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.label_4.setText(
            QtGui.QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\"><span style=\" font-size:20pt; font-weight:600;\">Kamus SIBI</span><br/>(Sistem Isyarat Bahasa Indonesia)</p></body></html>",
                None, QtGui.QApplication.UnicodeUTF8))
        self.label_deskripsi.setText(
            QtGui.QApplication.translate("MainWindow", "Deskripsi", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.label_butir.setText(
            QtGui.QApplication.translate("MainWindow", "Kategori -> Butir",
                                         None, QtGui.QApplication.UnicodeUTF8))
        self.menuTentang.setTitle(
            QtGui.QApplication.translate("MainWindow", "Te&ntang", None,
                                         QtGui.QApplication.UnicodeUTF8))
Example #13
0
class PysideGui(generic.GenericGui):

    def __init__(self):
        generic.GenericGui.__init__(self)
        window = QWidget()
        window.setWindowTitle('quichem-pyside')

        self.compiler_view = QListWidget()
        self.compiler_view.currentRowChanged.connect(self.show_source)
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)
        self.edit = QLineEdit()
        self.edit.setPlaceholderText('Type quichem input...')
        self.edit.textChanged.connect(self.change_value)
        self.view = QWebView()
        self.view.page().mainFrame().setScrollBarPolicy(Qt.Vertical,
                                                        Qt.ScrollBarAlwaysOff)
        self.view.page().action(QWebPage.Reload).setVisible(False)
        self.view.setMaximumHeight(0)
        self.view.setUrl('qrc:/web/page.html')
        self.view.setZoomFactor(2)
        self.view.page().mainFrame().contentsSizeChanged.connect(
            self._resize_view)
        # For debugging JS:
        ## from PySide.QtWebKit import QWebSettings
        ## QWebSettings.globalSettings().setAttribute(
        ##     QWebSettings.DeveloperExtrasEnabled, True)

        button_image = QPushButton('Copy as Image')
        button_image.clicked.connect(self.set_clipboard_image)
        button_image.setToolTip('Then paste into any graphics program')
        button_word = QPushButton('Copy as MS Word Equation')
        button_word.clicked.connect(self.set_clipboard_word)
        button_html = QPushButton('Copy as Formatted Text')
        button_html.clicked.connect(self.set_clipboard_html)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(button_image)
        button_layout.addWidget(button_word)
        button_layout.addWidget(button_html)
        source_layout = QHBoxLayout()
        source_layout.addWidget(self.compiler_view)
        source_layout.addWidget(self.stacked_widget, 1)
        QVBoxLayout(window)
        window.layout().addWidget(self.edit)
        window.layout().addWidget(self.view)
        window.layout().addLayout(button_layout)
        window.layout().addWidget(line)
        window.layout().addLayout(source_layout, 1)

        window.show()
        window.resize(window.minimumWidth(), window.height())
        # To prevent garbage collection of internal Qt object.
        self._window = window

    def show_source(self, index):
        if not self.sources:
            return
        self.stacked_widget.setCurrentIndex(index)
        self.change_value(self.edit.text())

    def _resize_view(self):
        """Set the QWebView's minimum height based on its current
        contents.

        """
        div = self.view.page().mainFrame().findFirstElement('.output')
        scrollbar_width = QApplication.style().pixelMetric(
            QStyle.PM_ScrollBarExtent)
        self.view.setMaximumHeight(
            div.geometry().height() + scrollbar_width + 16)

    def make_source(self, name):
        self.compiler_view.addItem(name)
        self.compiler_view.setCurrentRow(0)
        scrollbar_width = QApplication.style().pixelMetric(
            QStyle.PM_ScrollBarExtent)
        self.compiler_view.setMaximumWidth(
            self.compiler_view.sizeHintForColumn(0) + scrollbar_width + 16)
        page = QWidget()
        QHBoxLayout(page)
        page.layout().setContentsMargins(*(0,) * 4)
        source = QTextEdit()
        source.setStyleSheet('min-width: 0; min-height: 0')
        source.setReadOnly(True)
        QVBoxLayout(source)
        button = QPushButton('Copy')
        button.clicked.connect(functools.partial(self.set_clipboard, source))
        page.layout().addWidget(source)
        source.layout().addWidget(button, 0, Qt.AlignRight | Qt.AlignBottom)
        self.stacked_widget.addWidget(page)
        return source

    def run_script(self, js):
        self.view.page().mainFrame().evaluateJavaScript(js)

    def set_source(self, widget, source_factory):
        if widget.isVisible():
            widget.setPlainText(source_factory())

    def set_clipboard_image(self):
        """Export the formatted output to an image and store it in the
        clipboard.

        The image stored in the clipboard is a PNG file with alpha
        transparency.

        """
        div = self.view.page().mainFrame().findFirstElement('.output')
        images = {}
        for background in (Qt.transparent, Qt.white):
            image = QImage(div.geometry().size(),
                           QImage.Format_ARGB32_Premultiplied)
            image.fill(background)
            painter = QPainter(image)
            div.render(painter)
            painter.end()
            images[background] = image

        # Windows needs this buffer hack to get alpha transparency in
        # the copied PNG.
        buffer_ = QBuffer()
        buffer_.open(QIODevice.WriteOnly)
        images[Qt.transparent].save(buffer_, 'PNG')
        buffer_.close()
        data = QMimeData()
        data.setData('PNG', buffer_.data())
        data.setImageData(images[Qt.white])
        QApplication.clipboard().setMimeData(data)

    def set_clipboard_word(self):
        """Store the formatted output in the clipboard in a Microsoft
        Word friendly format.

        Microsoft Word interprets the clipboard contents as an
        equation. Other programs will see it as plain text containing
        XML.

        """
        QApplication.clipboard().setText(generic.word_equation_from_mathml(
            self.view.page().mainFrame().evaluateJavaScript(generic.MML_JS)))

    def set_clipboard_html(self):
        """Place the HTML displayed in the HTML view widget into the
        system clipboard.

        """
        data = QMimeData()
        data.setText(self.plain)
        data.setHtml(self.html)
        QApplication.clipboard().setMimeData(data)

    def set_clipboard(self, source):
        """Place the text displayed in the given source widget into the
        system clipboard.

        """
        QApplication.clipboard().setText(source.toPlainText())