I'm making a custom browser in python but my AJAX calls don't work. (work on firefox and others browsers.)
#!/usr/bin/env python
import sys
import gtk
import webkit
DEFAULT_URL = '/var/www/profile.html' # Change this as you Wish
class SimpleBrowser: # needs GTK, Python, Webkit-GTK
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
self.window.connect('delete_event', self.close_application)
self.window.set_default_size(1366, 743)
self.window.set_position(0)
vbox = gtk.VBox(spacing=0)
vbox.set_border_width(0)
self.txt_url = gtk.Entry()
self.txt_url.connect('activate', self._txt_url_activate)
self.scrolled_window = gtk.ScrolledWindow()
self.webview = webkit.WebView()
self.scrolled_window.add(self.webview)
vbox.pack_start(self.scrolled_window, fill=True, expand=True)
self.window.add(vbox)
def _txt_url_activate(self, entry):
self._load(entry.get_text())
def _load(self, url):
self.webview.open(url)
def open(self, url):
self.txt_url.set_text(url)
self.window.set_title('007WallPaper')
self._load(url)
def show(self):
self.window.show_all()
#self.window.fullscreen()
def close_application(self, widget, event, data=None):
gtk.main_quit()
if __name__ == '__main__':
if len(sys.argv) > 1:
url = sys.argv[1]
else:
url = DEFAULT_URL
gtk.gdk.threads_init()
browser = SimpleBrowser()
browser.open(url)
browser.show()
gtk.main()
How can I "import" AJAX functionality into it ??
Maybe i can use pyqt ? Not sure how i can do that but i really need it.
Related
I'm developing a webview browser in Python and PyQt5 and I want to know How to highlight particular text in Python and PyQt5 web browser. I want to highlight particular text like web find text in other browsers.
self.browser = QWebEngineView()
self.browser.HighlightAllOccurrences('hello world')
You have to use the findText method of QWebEngineView (or QWebEnginePage), in the following example there is a search bar when you press Ctrl + F that allows to make the search easier for the user:
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
class SearchPanel(QtWidgets.QWidget):
searched = QtCore.pyqtSignal(str, QtWebEngineWidgets.QWebEnginePage.FindFlag)
closed = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(SearchPanel, self).__init__(parent)
lay = QtWidgets.QHBoxLayout(self)
done_button = QtWidgets.QPushButton('&Done')
self.case_button = QtWidgets.QPushButton('Match &Case', checkable=True)
next_button = QtWidgets.QPushButton('&Next')
prev_button = QtWidgets.QPushButton('&Previous')
self.search_le = QtWidgets.QLineEdit()
self.setFocusProxy(self.search_le)
done_button.clicked.connect(self.closed)
next_button.clicked.connect(self.update_searching)
prev_button.clicked.connect(self.on_preview_find)
self.case_button.clicked.connect(self.update_searching)
for btn in (self.case_button, self.search_le, next_button, prev_button, done_button, done_button):
lay.addWidget(btn)
if isinstance(btn, QtWidgets.QPushButton): btn.clicked.connect(self.setFocus)
self.search_le.textChanged.connect(self.update_searching)
self.search_le.returnPressed.connect(self.update_searching)
self.closed.connect(self.search_le.clear)
QtWidgets.QShortcut(QtGui.QKeySequence.FindNext, self, activated=next_button.animateClick)
QtWidgets.QShortcut(QtGui.QKeySequence.FindPrevious, self, activated=prev_button.animateClick)
QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Escape), self.search_le, activated=self.closed)
#QtCore.pyqtSlot()
def on_preview_find(self):
self.update_searching(QtWebEngineWidgets.QWebEnginePage.FindBackward)
#QtCore.pyqtSlot()
def update_searching(self, direction=QtWebEngineWidgets.QWebEnginePage.FindFlag()):
flag = direction
if self.case_button.isChecked():
flag |= QtWebEngineWidgets.QWebEnginePage.FindCaseSensitively
self.searched.emit(self.search_le.text(), flag)
def showEvent(self, event):
super(SearchPanel, self).showEvent(event)
self.setFocus(True)
class Browser(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Browser, self).__init__(parent)
self._view = QtWebEngineWidgets.QWebEngineView()
self.setCentralWidget(self._view)
self._view.load(QtCore.QUrl('https://doc.qt.io/qt-5/qwebengineview.html'))
self._search_panel = SearchPanel()
self.search_toolbar = QtWidgets.QToolBar()
self.search_toolbar.addWidget(self._search_panel)
self.addToolBar(QtCore.Qt.BottomToolBarArea, self.search_toolbar)
self.search_toolbar.hide()
self._search_panel.searched.connect(self.on_searched)
self._search_panel.closed.connect(self.search_toolbar.hide)
self.create_menus()
#QtCore.pyqtSlot(str, QtWebEngineWidgets.QWebEnginePage.FindFlag)
def on_searched(self, text, flag):
def callback(found):
if text and not found:
self.statusBar().show()
self.statusBar().showMessage('Not found')
else:
self.statusBar().hide()
self._view.findText(text, flag, callback)
def create_menus(self):
menubar = self.menuBar()
file_menu = menubar.addMenu('&File')
file_menu.addAction('&Find...', self.search_toolbar.show, shortcut=QtGui.QKeySequence.Find)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = Browser()
w.show()
sys.exit(app.exec_())
I've created a wizard with Pyside.
On one page, I create a new thread, which starts an installer.
When the installer is ready, the Wizard should go forward automatically, without clicking the next button.
I've read the pyside documentation, and now my understanding is, that QWizard has a next function. But how can I use this function?
My test is working fine:
from PySide.QtGui import *
from PySide.QtCore import *
...
...
class Install(QWizardPage):
def __init__(self, parent=None):
super(Install, self).__init__(parent)
def initializePage(self):
self.setTitle("Install")
label = QLabel("Install")
label.setWordWrap(True)
layout = QVBoxLayout()
self.progressBar = QProgressBar(self)
self.progressBar.setRange(0,1)
self.progressBar.setRange(0,0)
layout.addWidget(self.progressBar)
layout.addWidget(label)
self.setLayout(layout)
self.myTask = TaskThread()
self.myTask.start()
self.myTask.taskFinished.connect(self.Finished)
def Finished(self):
print("finish")
def isComplete(self):
return False
class TaskThread(QThread):
taskFinished = Signal()
def run(self):
a = 0
while a != 10000:
print("test")
a += 1
self.taskFinished.emit()
And when I try to use the next function I try:
self.CallNext = QWizard().next
self.myTask.taskFinished.connect(self.CallNext)
And also:
self.myTask.taskFinished.connect(QWizard().next)
But this is not working
This connection should be done in the context where the QWizard and QWizardPage exist, but before that we must move the creation of the QThread to the constructor, for example in the following example I do in the main:
class Install(QWizardPage):
def __init__(self, parent=None):
super(Install, self).__init__(parent)
self.myTask = TaskThread()
def initializePage(self):
[...]
self.setLayout(layout)
self.myTask.start()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
wizard = QWizard()
install = Install()
install.setTitle("installer")
install.myTask.taskFinished.connect(wizard.next)
wizard.addPage(install)
page = QWizardPage()
page.setTitle("next Page")
wizard.addPage(page)
wizard.show()
sys.exit(wizard.exec_())
I got a little issue concerning wxPython and the system tray.
Well, all I use is the system tray and I want to have it call a function right after the system tray got drawn, but EVT_PAINT seems to have no effect on the tray for me.
Anyways, here is my code:
#!/usr/bin/python2
import wxversion
wxversion.select('2.8')
import pynotify,subprocess,wx,os,json
#config
TRAY_TOOLTIP = 'Backups'
PROG_DIR = os.path.dirname(os.path.realpath(__file__))
class Config:
def __init__(self):
self.readFile()
def readFile(self):
jsons = ''
searchingJson = True
f = open(PROG_DIR+'/config.json')
lines = f.readlines()
f.close()
self.json = json.loads(lines)
pynotify.init("Backups")
def backup():
sysTray.set_icon(PROG_DIR+'/loading.png')
pynotify.Notification("Backups","Starting Backup",PROG_DIR+'/backup.png').show()
if subprocess.call(["rsync","-a",config.json['backup_dir'],"--exclude",".*",config.json['remote_dir']]):
pynotify.Notification("Backups","Backup Failed",PROG_DIR+'/backup.png').show()
else:
pynotify.Notification("Backups","Backup complete!",PROG_DIR+'/backup.png').show()
sysTray.set_icon(PROG_DIR+'/backup.png')
def create_menu_item(menu,label,func):
item = wx.MenuItem(menu,-1,label)
menu.Bind(wx.EVT_MENU,func,id=item.GetId())
menu.AppendItem(item)
return item
class TaskBarIcon(wx.TaskBarIcon):
def __init__(self):
super(TaskBarIcon,self).__init__()
self.set_icon(PROG_DIR+'/backup.png')
self.Bind(wx.EVT_PAINT,self.initial_backup)
def CreatePopupMenu(self):
menu = wx.Menu()
create_menu_item(menu,'Start Backup',self.on_backup)
menu.AppendSeparator()
create_menu_item(menu,'Exit',self.on_exit)
return menu
def set_icon(self,path):
icon = wx.IconFromBitmap(wx.Bitmap(path))
self.SetIcon(icon,TRAY_TOOLTIP)
def on_exit(self,event):
wx.CallAfter(self.Destroy)
def on_backup(self,event):
backup()
def initial_backup(self,event):
print 'test'
def main():
app = wx.App(False)
sysTray = TaskBarIcon()
app.MainLoop()
if __name__ == '__main__':
main()
Nothing gets printed to the terminal.
Thanks for help!
I have a browser application written in python with PySide Qt. But now I want to add a button in the toolbar to print the website. How do I do this? Because CTRL + P is not working in the application.
Here is the code:
import sys
from PySide import QtCore, QtGui, QtWebKit, QtHelp, QtNetwork
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
Action1 = QtGui.QAction('Google', self)
Action1.setShortcut('Ctrl+M')
Action1.triggered.connect(self.load_message)
self.toolbar1 = self.addToolBar('Google')
self.toolbar1.addAction(Action1)
Action2 = QtGui.QAction('Yahoo', self)
Action2.setShortcut('Ctrl+H')
Action2.triggered.connect(self.load_list)
self.toolbar2 = self.addToolBar('Yahoo')
self.toolbar2.addAction(Action2)
exitAction = QtGui.QAction('Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(self.on_exit)
self.toolbar3 = self.addToolBar('Exit')
self.toolbar3.addAction(exitAction)
self.resize(750, 750)
self.setWindowTitle('Browser')
self.web = QtWebKit.QWebView(self)
self.web.load(QtCore.QUrl('http://www.google.com'))
self.setCentralWidget(self.web)
def on_exit(self):
QtGui.qApp.quit
def load_message(self):
self.web.load(QtCore.QUrl('http://www.google.com'))
def load_list(self):
self.web.load(QtCore.QUrl('http://www.yahoo.com'))
app = QtGui.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('myicon.ico'))
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
In your __init__ method add a Print action:
printAction = QtGui.QAction('Print', self)
printAction.setShortcut('Ctrl+P')
printAction.triggered.connect(self.do_print)
self.toolbar4 = self.addToolBar('Print')
self.toolbar4.addAction(printAction)
And create a do_print method:
def do_print(self):
p = QtGui.QPrinter()
p.setPaperSize(QtGui.QPrinter.A4)
p.setFullPage(True)
p.setResolution(300)
p.setOrientation(QtGui.QPrinter.Portrait)
p.setOutputFileName('D:\\test.pdf')
self.web.print_(p)
This will print to a file D:\test.pdf.
To configure your printer differently see the QPrinter documentation. Also if you want a print preview dialog see the QPrintPreviewDialog docs.
If you want a standard print dialog the use:
def do_print(self):
p = QtGui.QPrinter()
dialog = QtGui.QPrintDialog(p)
dialog.exec_()
self.web.print_(p)
This is a pyside GUI, I have created 2 panel in 2 different .py files, main.py and sub.py each panel will display a we browser 'QWebView'. Currently when user press the button on main.py it will redirect the user to a page e.g "www.google" and user will have to click the button on sub.py to be redirected to e.g"www.facebook.com" they work as a indipendent function.
I would like to ask is there a way to link both together where user press the button on main.py and both webbrower will change together?
Yes, you can have multiple items triggered by the same connection.
QObject::connect(myButton, SIGNAL(clicked()),
this, SLOT(launchGoogleSiteOnBrowserA());
QObject::connect(myButton, SIGNAL(clicked()),
pointerToOtherClass, SLOT(launchFacebookSiteOnBrowserB());
http://qt-project.org/doc/qt-4.8/signalsandslots.html
EDIT: Following some another answer about using signals and slots in PyQt...
https://stackoverflow.com/a/7618282/999943
Here is a way to do it in PyQt:
widget.pyw
from PyQt4 import QtCore, QtGui
from mybrowser import Browser
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
self.myButton = QtGui.QPushButton('Open Facebook and Google')
self.myHLayout = QtGui.QHBoxLayout()
self.myVLayout = QtGui.QVBoxLayout()
self.myVLayout.addWidget(self.myButton)
url = QtCore.QUrl('http://www.yahoo.com')
self.browserLHS = Browser(url)
self.browserRHS = Browser(url)
self.myHLayout.addWidget(self.browserLHS)
self.myHLayout.addWidget(self.browserRHS)
QtCore.QObject.connect(self.myButton, QtCore.SIGNAL("clicked()"), self.changePageOnBothBrowsers )
self.myVLayout.addLayout(self.myHLayout)
self.setLayout(self.myVLayout)
def changePageOnBothBrowsers(self):
self.browserLHS.load(QtCore.QUrl.fromUserInput('google.com'))
self.browserRHS.load(QtCore.QUrl.fromUserInput('facebook.com'))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())
mybrowser.pyw
from PyQt4 import QtCore, QtGui, QtNetwork, QtWebKit
import jquery_rc
class Browser(QtWebKit.QWebView):
def __init__(self, url):
super(Browser, self).__init__()
self.progress = 0
fd = QtCore.QFile(":/jquery.min.js")
if fd.open(QtCore.QIODevice.ReadOnly | QtCore.QFile.Text):
self.jQuery = QtCore.QTextStream(fd).readAll()
fd.close()
else:
self.jQuery = ''
QtNetwork.QNetworkProxyFactory.setUseSystemConfiguration(True)
self.load(url)
self.loadFinished.connect(self.adjustLocation)
self.titleChanged.connect(self.adjustTitle)
self.loadProgress.connect(self.setProgress)
self.loadFinished.connect(self.finishLoading)
self.locationEdit = QtGui.QLineEdit(self)
self.locationEdit.setSizePolicy(QtGui.QSizePolicy.Expanding,
self.locationEdit.sizePolicy().verticalPolicy())
self.locationEdit.returnPressed.connect(self.changeLocation)
def adjustLocation(self):
self.locationEdit.setText(self.url().toString())
def changeLocation(self):
url = QtCore.QUrl.fromUserInput(self.locationEdit.text())
self.load(url)
self.setFocus()
def adjustTitle(self):
if 0 < self.progress < 100:
self.setWindowTitle("%s (%s%%)" % (self.title(), self.progress))
else:
self.setWindowTitle(self.title())
def setProgress(self, p):
self.progress = p
self.adjustTitle()
def finishLoading(self):
self.progress = 100
self.adjustTitle()
self.page().mainFrame().evaluateJavaScript(self.jQuery)
#if __name__ == '__main__':
#
# import sys
#
# app = QtGui.QApplication(sys.argv)
#
# if len(sys.argv) > 1:
# url = QtCore.QUrl(sys.argv[1])
# else:
# url = QtCore.QUrl('http://www.google.com/ncr')
#
# browser = Browser(url)
# browser.show()
#
# sys.exit(app.exec_())
Hope that helps.