LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Pyqt5 and qtwebengine (https://www.linuxquestions.org/questions/programming-9/pyqt5-and-qtwebengine-4175695802/)

francesco bat 05-30-2021 12:31 PM

Pyqt5 and qtwebengine
 
Hi!
I am trying to create a little browser.
I'm basing on:
https://github.com/learnpyqt/15-minu...browser_tabbed
I have no experience.
The problem I encountered, is that the functions imported doesn't work correctly.
Context menu, doesn't work:
- Save page
- View source page
- Reload
If i try ctrl+ or ctrl-, zoom doesn't work.
The problem is present also in other pyqt5 browser i downloaded online, all with same problem.
Do you know if it's a bug or i must to add some additional functions?
I wait clarification :)
Bye
Francesco bat

boughtonp 05-31-2021 07:40 AM


 
So you've downloaded some software, but the functionality in it doesn't work as expected.

Start by directing your questions to that software's issue tracker: https://github.com/learnpyqt/15-minute-apps/issues


francesco bat 05-31-2021 12:50 PM

As I've just written the problem is in many pyqt5 browsers, all with same problems.
Post a list:

https://github.com/alandmoore/wcgbrowser
https://github.com/karascr/Python-PyQt5-web-browser
https://github.com/learnpyqt/15-minu...browser_tabbed
and many others.

Others are pythons code all with same problems.
To contact all developers of all software is useless if the problem is other.
Now i want to understand if i must add functions to code for enable the present functions contextual menu or it's useless.
Bye
Francesco bat

boughtonp 05-31-2021 01:23 PM


 
There is a button in a piece of software that says "do X", and you've pressed that button and it does not do X, right?

* Does the documentation for the software say "X does not work unless you first add your own functions"?
* Does the readme for the software say "X is a known bug/limitation"?
* Have you searched the source code for X and found a stub saying "not yet implemented"?

The best person to address an issue with any software is usually a developer who has worked on that software.

Quote:

Originally Posted by https://github.com/alandmoore/wcgbrowser#bugs-and-limitations
If you find bugs, please report them as an "issue" at the project's github page: http://github.com/alandmoore/wcgbrowser/issues.


You don't need to go through all those projects (unless you want to), pick one or two that seem most promising.

If you've tried multiple pieces of software and think an issue is on your end, include that information in the bug report and ask the developer who has written software using that code and may well have encountered the issue themselves for advice on how to verify/diagnose the issue.

If you raise an issue and get no response, it's not unreasonable to ask on a forum at that point - pointing to the issue you raised - but LinuxQuestions is not a helpdesk for random GitHub projects, and doesn't have a special advantage over the developer of a piece of software, so start with the place most likely to solve the problem: raise an issue.


teckk 05-31-2021 03:02 PM

If you are talking about this:
https://github.com/learnpyqt/15-minu...wser_tabbed.py
https://raw.githubusercontent.com/le...wser_tabbed.py

I copied that to a text editor, and added a #!/usr/bin/python to the top of it. That little browser does work.

It is missing code that would allow it to open links in new tabs, change font size, turn scripts/images on/off, change the user agent etc. You'll need to add that.

I can't give you a PyQt5 - QtWebengine tutorial in one page. You are going to have to stick your face in the docs for a while.
https://docs.python.org/3/
https://www.riverbankcomputing.com/
https://wiki.qt.io/Porting_from_QtWebKit_to_QtWebEngine
https://www.guru99.com/python-tutorials.html
https://www.programcreek.com/python/


I can give you some basics.

Change user agent.
Code:

from PyQt5.QtWebEngineWidgets import QWebEngineProfile

a = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) ' 
        'Gecko/20100101 Firefox/86.0')
       
self.agent = QWebEngineProfile(self)
self.agent.defaultProfile().setHttpUserAgent(a)

Turn scripts/images on/off
Code:

from PyQt5.QtWebEngineWidgets import QWebEngineView

self.view = QWebEngineView(self)
self.view.setUrl(url)
self.view.settings().setAttribute(
            QWebEngineSettings.JavascriptEnabled, False)
           
self.view.settings().setAttribute(
            QWebEngineSettings.AutoLoadImages, True)

Font sizes:
Code:

from PyQt5.QtGui import QFont

font = QFont()
font.setPointSize(14)
self.fs = (20)

self.view.settings().globalSettings().setFontSize(
            QWebEngineSettings.MinimumFontSize, (self.fs))

And that's about as far as I am going. You'll need to study PyQt5, and QtWebengine docs. And they are not real intuitive. Good luck.

teckk 05-31-2021 04:03 PM

Here, this is as sloppy as it gets. A bit of code I had laying around. I removed some of it, left just a functional browser. I checked it, it works. You don't need any image files. I see that the source code display doesn't work. Fix it! Font +/- works. Also caches. Shows links on hover in status bar. Has toolbar. User agent works. Probably some imports that are no longer needed.

Also here is a new tabs example for PyQt5, it works too.

PyQt5-Qtwebengine Web Browser
Code:

#!/usr/bin/env python

#For remote debugging | script.py --remote-debugging-port=4900

import sys
from PyQt5.QtCore import Qt, QUrl, QTextStream, QCoreApplication
from PyQt5.QtNetwork import QNetworkRequest
from PyQt5.QtGui import QFont, QGuiApplication
from PyQt5.QtWidgets import (QAction, QApplication, QLineEdit,
        QMainWindow, QSizePolicy, QTextEdit, qApp, QMessageBox)
from PyQt5.QtWebEngineWidgets import (QWebEnginePage,
        QWebEngineView, QWebEngineSettings, QWebEngineProfile)
       
#Change home page here
home = 'file:///path/to/Bookmarks.html'

#Update user agent here
a = ('Mozilla/5.0 (Windows NT 10.1; Win64; x64; rv:86.0) ' 
        'Gecko/20100101 Firefox/86.0')

#Main window class
class MainWindow(QMainWindow):
    def __init__(self, url):
        super(MainWindow, self).__init__()
    #Main window size
        self.resize(1400,1000)

    #Font sizes for widgets and windows
        font = QFont()
        font.setPointSize(14)
        self.fs = (20)
        #Set default UA
        self.agent = QWebEngineProfile(self)
        self.agent.defaultProfile().setHttpUserAgent(a)

    #Default browser settings
        self.view = QWebEngineView(self)
        self.view.setUrl(url)
        self.view.settings().setAttribute(
                QWebEngineSettings.JavascriptEnabled, True)
        self.js = "True"
        self.view.settings().setAttribute(
                QWebEngineSettings.AutoLoadImages, True)
        self.im = "True"
        self.view.settings().setAttribute(
                QWebEngineSettings.PluginsEnabled, True)
        self.view.settings().globalSettings().setFontSize(
                QWebEngineSettings.MinimumFontSize, (self.fs))
        self.view.settings().setAttribute(
                QWebEngineSettings.LocalStorageEnabled, True)
    #Show link url's in status bar
        self.view.page().linkHovered.connect(self.link_hovered)
        self.statusBar().setFont(font)
        self.statusBar().show()
    #Connect to signals
        self.view.loadFinished.connect(self.adjustLocation)
        self.view.titleChanged.connect(self.adjustTitle)
        self.view.loadProgress.connect(self.setProgress)
        self.view.loadFinished.connect(self.finishLoading)
    #Url bar
        self.locationEdit = QLineEdit(self)
        self.locationEdit.setSizePolicy(QSizePolicy.Expanding,
                self.locationEdit.sizePolicy().verticalPolicy())
        self.locationEdit.returnPressed.connect(self.changeLocation)
        self.locationEdit.setFont(font)
    #Toolbar
        toolBar = self.addToolBar("Url bar")
        toolBar.setFont(font)
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Back))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Forward))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Reload))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Stop))
        toolBar.addWidget(self.locationEdit)       
    #Menubar
        menubar = self.menuBar()
        menubar.setFont(font)
    #File menu
        fileMenu = self.menuBar().addMenu("File")
        fileMenu.setFont(font)
        viewSourceAction = QAction("Page Source", self)
        viewSourceAction.setShortcut("Ctrl+p")
        viewSourceAction.triggered.connect(self.viewSource)
        fileMenu.addAction(viewSourceAction)

        homeAction = QAction("Home page", self)
        homeAction.setShortcut("Ctrl+h")
        homeAction.triggered.connect(self.home_page)
        fileMenu.addAction(homeAction)

        setFontSizeU = QAction("Font size +", self)
        setFontSizeU.setShortcut("Ctrl++")
        setFontSizeU.triggered.connect(self.fontPlus)
        fileMenu.addAction(setFontSizeU)

        setFontSizeD = QAction("Font size -", self)
        setFontSizeD.setShortcut("Ctrl+-")
        setFontSizeD.triggered.connect(self.fontMinus)
        fileMenu.addAction(setFontSizeD)

        exitAction = QAction ('Exit', self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.triggered.connect(qApp.quit)
        fileMenu.addAction(exitAction)
       
    #Tool menu
        toolsMenu = self.menuBar().addMenu("Tools")
        toolsMenu.setFont(font)

        jScriptOffAction = QAction("Scripts off", self)
        jScriptOffAction.triggered.connect(self.jsOff)
        toolsMenu.addAction(jScriptOffAction)

        jScriptOnAction = QAction("Scripts on", self)
        jScriptOnAction.triggered.connect(self.jsOn)
        toolsMenu.addAction(jScriptOnAction)

        imOffAction = QAction("Images off", self)
        imOffAction.triggered.connect(self.imOff)
        toolsMenu.addAction(imOffAction)

        imOnAction = QAction("Images on", self)
        imOnAction.triggered.connect(self.imOn)
        toolsMenu.addAction(imOnAction)
       
    #Main browser window
        self.setCentralWidget(self.view)
       
#Functions

#Set images on-off   
    def imOff(self):
        self.view.settings().setAttribute(
                QWebEngineSettings.AutoLoadImages, False)

    def imOn(self):
        self.view.settings().setAttribute(
                QWebEngineSettings.AutoLoadImages, True)
#Set scripts on-off
    def jsOff(self):
        self.view.settings().setAttribute(
                QWebEngineSettings.JavascriptEnabled, False)

    def jsOn(self):
        self.view.settings().setAttribute(
                QWebEngineSettings.JavascriptEnabled, True)
#Change font size
    def fontPlus(self):
        self.fs = ((self.fs) + 2)
        self.view.settings().globalSettings().setFontSize(
                QWebEngineSettings.MinimumFontSize, (self.fs))
        self.setStatusTip("Font size is " + str(self.fs))
                       
    def fontMinus(self):
        self.fs = ((self.fs) - 2)
        self.view.settings().globalSettings().setFontSize(
                QWebEngineSettings.MinimumFontSize, (self.fs))
        self.setStatusTip("Font size is " + str(self.fs))
#Home page       
    def home_page(self):
        url = QUrl(home)
        self.view.load(url)
   
#View source code
    def viewSource(self):
        accessManager = self.view.page().networkAccessManager()
        request = QNetworkRequest(self.view.url())
        reply = accessManager.get(request)
        reply.finished.connect(self.showSource)

    def showSource(self):
        reply = self.sender()
        self.textEdit = QTextEdit()
        font = QFont()
        font.setPointSize(14)
        self.textEdit.setFont(font)
        self.textEdit.setAttribute(Qt.WA_DeleteOnClose)
        self.textEdit.setGeometry(25, 25, 1000, 800)
        self.textEdit.show()
        self.textEdit.setPlainText(QTextStream(reply).readAll())
        reply.deleteLater()
        #self.textEdit.resize(1000, 800)
        #self.textEdit.move(25, 25)
#Location
    def adjustLocation(self):
        self.locationEdit.setText(self.view.url().toString())

    def changeLocation(self):
        url = QUrl.fromUserInput(self.locationEdit.text())
        self.view.load(url)
        self.view.setFocus()
#Adjust title to page
    def adjustTitle(self):
        if 0 < self.progress < 100:
            self.setWindowTitle("%s (%s%%)" % (self.view.title(), self.progress))
        else:
            self.setWindowTitle(self.view.title())
#Load progress
    def setProgress(self, p):
        self.progress = p
        self.adjustTitle()

    def finishLoading(self):
        self.progress = 100
        self.adjustTitle()
#Show links mouse hover
    def link_hovered(self, link):
        self.statusBar().showMessage(link)

if __name__ == '__main__':
    app = QApplication(sys.argv)
   
#Open with argument or home
    if len(sys.argv) > 1:
        url = QUrl(sys.argv[1])
    else:
        url = QUrl(home)
#Start the loop
    browser = MainWindow(url)
    browser.show()
    sys.exit(app.exec_())

Tabs example.
Code:

#!/usr/bin/python

import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication,
            QPushButton, QWidget, QAction, QTabWidget,
            QVBoxLayout, QLabel)
 
# Creating the main window
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.width = 500
        self.height = 500
        self.setWindowTitle('PyQt5 - QTabWidget')
        self.setGeometry(0,0,self.width, self.height)
 
        self.tab_widget = MyTabWidget(self)
        self.setCentralWidget(self.tab_widget)
        self.show()
 
# Creating tab widgets
class MyTabWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)
 
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tabs.resize(300, 200)
 
        # Add tabs
        self.tabs.addTab(self.tab1, "One")
        self.tabs.addTab(self.tab2, "Two")
        self.tabs.addTab(self.tab3, "Three")
 
        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.l = QLabel()
        self.l.setText("First tab here")
        self.tab1.layout.addWidget(self.l)
        self.tab1.setLayout(self.tab1.layout)
 
        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

Knock yourself out.

francesco bat 05-31-2021 04:22 PM

Thank you very much teckk.
I am looking for these info.
Now i understand i must add other functions.
I thought that with the "import" was all solved but it's not so.
ctrl+x ctrl+c ctrl+v works but no ctrl++ , ctrl+- and ctrl+f.
My work is developing well. it's very nice but without zoom, find in the page and things so stupid but important for a browser, it can to be used only from myself.
I hope to solve so i can share it :)
Bye
Francesco bat

teckk 06-01-2021 12:06 PM

Little bit neater.

Code:

#!/usr/bin/python

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtPrintSupport import *

a = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) ' 
        'Gecko/20100101 Firefox/88.0')
       
b = ('Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) '
        'AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 '
            'Mobile/14A403 Safari/602.1')
           
u = ('https://www.linuxquestions.org/questions/'
            'lqsearch.php?do=getnew&daysprune=7')

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.resize(1400,1000)
        font = QFont()
        font.setPointSize(18)
        self.fs = (20)

        self.agent = QWebEngineProfile(self)
        self.agent.defaultProfile().setHttpUserAgent(a)

        self.browser = QWebEngineView()
        #self.browser.setUrl(url)
        self.browser.settings().setAttribute(
                    QWebEngineSettings.JavascriptEnabled, False)
        self.browser.settings().setAttribute(
                    QWebEngineSettings.AutoLoadImages, False)
        self.browser.settings().setAttribute(
                    QWebEngineSettings.PluginsEnabled, True)
        self.browser.settings().globalSettings().setFontSize(
                    QWebEngineSettings.MinimumFontSize, (self.fs))
        self.browser.settings().setAttribute(
                    QWebEngineSettings.LocalStorageEnabled, True)
 
        self.browser.setUrl(QUrl(u))
        self.browser.urlChanged.connect(self.update_urlbar)
        self.browser.loadFinished.connect(self.update_title)
        self.setCentralWidget(self.browser)
 
        self.status = QStatusBar()
        self.setStatusBar(self.status)
        self.browser.page().linkHovered.connect(self.link_hovered)
        self.statusBar().setFont(font)
 
        navtb = QToolBar("Nav")
        self.addToolBar(navtb)
 
        back_btn = QAction("<", self)
        back_btn.setStatusTip("Back")
        back_btn.triggered.connect(self.browser.back)
        navtb.addAction(back_btn)
        navtb.addSeparator()
 
        next_btn = QAction(">", self)
        next_btn.setStatusTip("Forward")
        next_btn.triggered.connect(self.browser.forward)
        navtb.addAction(next_btn)
        navtb.addSeparator()
 
        reload_btn = QAction("R", self)
        reload_btn.setStatusTip("Reload")
        reload_btn.triggered.connect(self.browser.reload)
        navtb.addAction(reload_btn)
        navtb.addSeparator()
       
        stop_btn = QAction("X", self)
        stop_btn.setStatusTip("Stop")
        stop_btn.triggered.connect(self.browser.stop)
        navtb.addAction(stop_btn)
        navtb.addSeparator()
 
        home_btn = QAction("H", self)
        home_btn.setStatusTip("Home")
        home_btn.triggered.connect(self.navigate_home)
        navtb.addAction(home_btn)
       
        self.urlbar = QLineEdit()
        self.urlbar.returnPressed.connect(self.navigate_to_url)
        navtb.addWidget(self.urlbar)
       
        self.show()
 
    def update_title(self):
        title = self.browser.page().title()
        self.setWindowTitle("% s - LQ Latest" % title)
 
    def navigate_home(self): 
        self.browser.setUrl(QUrl(u))
 
    def navigate_to_url(self):
        q = QUrl(self.urlbar.text())
        if q.scheme() == "":
            q.setScheme("http")
        self.browser.setUrl(q)
 
    def update_urlbar(self, q):
        self.urlbar.setText(q.toString())
        self.urlbar.setCursorPosition(0)
       
    def link_hovered(self, link):
        self.statusBar().showMessage(link)

app = QApplication(sys.argv)
app.setApplicationName("LQLatest")
window = MainWindow()
app.exec_()

Open all the links that you click in a separate window.
Code:

#!/usr/bin/python

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtWebEngineWidgets import (QWebEngineView, QWebEnginePage,
                                        QWebEngineSettings)

u = ('https://www.linuxquestions.org/questions/'
            'lqsearch.php?do=getnew&daysprune=7')

class WebEnginePage(QWebEnginePage):
    external_windows = []

    def acceptNavigationRequest(self, url,  _type, isMainFrame):
        if _type == QWebEnginePage.NavigationTypeLinkClicked:
            w = QWebEngineView()
            w.setUrl(url)
            w.resize(1200,800)
            w.show()
            self.external_windows.append(w)
            return False
        return super().acceptNavigationRequest(url,  _type, isMainFrame)

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.resize(1400,1000)
        self.browser = QWebEngineView()
        self.browser.setPage(WebEnginePage(self))
        self.browser.setUrl(QUrl(u))
        self.setCentralWidget(self.browser)

app = QApplication(sys.argv)
window = MainWindow()
window.show()

app.exec_()

There is a lot of python here.
https://archlinux.org/packages/?sort...iner=&flagged=

https://aur.archlinux.org/packages/?O=0&K=python

francesco bat 07-10-2021 07:48 AM

Thank you very much.
I released it; Retroplanet Navigator:
http://www.lagrottadelpipistrello.al...net/index.html
Bye :)
Francesco bat


All times are GMT -5. The time now is 04:19 AM.