"QGLXContext: Failed to create dummy context" in Windows10 WSL2 with PyQt5 - python

I tried to run the following snippet in Windows10 Ubuntu WSL2 but got the error:
QGLXContext: Failed to create dummy context
QQuickWidget: Failed to make context current
QQuickWidget::resizeEvent() no OpenGL context
QQuickWidget: Failed to make context current
QQuickWidget: Attempted to render scene with no context
qt.qpa.backingstore: composeAndFlush: makeCurrent() failed
qt.qpa.backingstore: composeAndFlush: makeCurrent() failed
QQuickWidget: Attempted to render scene with no context
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtWebEngineWidgets
from PyQt5 import QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
url = "https://www.google.com"
self.browser = QtWebEngineWidgets.QWebEngineView()
self.browser.setUrl(QtCore.QUrl(url))
self.setCentralWidget(self.browser)
self.show()
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())

Related

Why is my next page button in python not working?

I followed a GUI course but the exact code does not work for me. I was trying to be guided to the next page when I clicked the button. But every time I click it, Python stops working with:
Process finished with exit code -1073740791 (0xC0000409)
Here's the code:
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi("screen1.ui", self)
self.button.clicked.connect(self.gotoScreen2)
def gotoScreen2(self):
widget.setCurrentIndex(widget.currentWidget()+1)
class Screen2(QMainWindow):
def __init__(self):
super(Screen2, self).__init__()
loadUi("screen2.ui",self)
self.button2.clicked.connect(self.gotoScreen1)
def gotoScreen1(self):
widget.setCurrentIndex(widget.currentWidget()+1)
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = QtWidgets.QStackedWidget()
mainwindow = MainWindow()
widget.addWidget(mainwindow)
screen2 = Screen2()
widget.addWidget(screen2)
widget.setFixedWidth(600)
widget.setFixedWidth(800)
widget.show()
try:
sys.exit(app.exec())
except:
print("Exiting..")
There may be some errors in code. It's my first time working on a GUI.
I have changed the
widget.setCurrentIndex(widget.currentWidget()+1)
to
widget.setCurrentIndex(1)
and it solved my problem. Now I can switch between pages without any crashes.
You have to install a module named 'PyQt5'

PySide6 + Qt Creator, pysideplugin error results in gray screen

Every time I create a Window UI - Dynamic load project in Qt Creator v8.0.2 and run the project I get the following error:
error: qt.pysideplugin: Environment variable PYSIDE_DESIGNER_PLUGINS
is not set, bailing out.
As a result, the window doesn't display any widgets, it is just a gray empty window
I have tried to configure os.environ['PYSIDE_DESIGNER_PLUGINS'] = '.' but then I get the following error:
error: qt.pysideplugin: No python files found in '.'.
Is there a way to load the pysideplugin to Qt Creator v8.0.2 or to remove the errors related to it and make the project run and show the widgets?
I am testing with a very simple UI
But when I run the project I can only see the following:
The complete code in the mainwindow.py file is:
# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.load_ui()
def load_ui(self):
loader = QUiLoader()
path = Path(__file__).resolve().parent / "form.ui"
ui_file = QFile(path)
ui_file.open(QFile.ReadOnly)
loader.load(ui_file, self)
ui_file.close()
if __name__ == "__main__":
#os.environ['PYSIDE_DESIGNER_PLUGINS']='.'
app = QApplication(sys.argv)
widget = MainWindow()
widget.show()
sys.exit(app.exec())
I am using python 3.10.5 and PySide6 version 6.4.0.1

Script is still running after closing pyqt5 window

import sys
import requests
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication
class MainWindow(QDialog):
def __init__(self):
super(MainWindow, self).__init__()
loadUi("tabletutorial.ui",self)
self.request_function()
def request_function(self):
for i in range(0,100):
resp=requests.get("https://www.google.com")
print(resp.status_code)
# main
app = QApplication(sys.argv)
mainwindow = MainWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(mainwindow)
widget.setFixedHeight(850)
widget.setFixedWidth(1120)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
This window is created by another main window.
Now the problem is when i quit the pyqt5 window the script is still running and i am getting the status code .I am running a big application with a bunch of requests.Anyone with relatable solution please ?
I TRIED:
self.close() not worked for me. #QtCore.pyqtSlot() also not worked.
I am new to here . Please ignore mistakes and kind answer are appriciated.

QFileDialog does not open a dialog window on MacOS

I am coding up a Qt GUI (PyQt5) in Python on MacOS. I run my program using python test.py in terminal.
When I attempt to use a QFileDialog static method such as QFileDialog.getOpenFileName, I get the following error instead of a dialog window opening:
2021-10-11 12:06:48.411 python[49048:17688470] +[NSXPCSharedListener endpointForReply:withListenerName:]: an error occurred while attempting to obtain endpoint for listener 'com.apple.view-bridge': Connection interrupted
I am able to get around this by constantly restarting the application and trying to open the dialog until it works. It usually works after 3 - 5 restarts. This is not ideal for any future users or if there is data that needs to be saved in the application prior to restarting.
Here is a minimal reproducible example script:
import sys
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QPushButton,
QFileDialog
)
class MainWindow(QWidget):
"""The main window of the application"""
def __init__(self, *args, **kwargs):
"""Initializes and shows the main window of the application"""
super().__init__(*args, **kwargs)
self.setLayout(QVBoxLayout())
# open file button
self.open_file_button = QPushButton(self)
self.open_file_button.setText("Open File")
self.open_file_button.clicked.connect(self.open_file)
self.layout().addWidget(self.open_file_button)
self.show()
def open_file(self):
file_name, _ = QFileDialog.getOpenFileName(self)
if file_name:
...
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec())
macOS version: Catalina 10.15.1 (19B88)
Python Version: 3.8.11
PyQt5 Version: 5.15.4
PyQt5-Qt5 Version: 5.15.2

How to render PDF using pdf.js viewer in PyQt?

I have tried adding the pdf.js viewer files in my project and it works in browsers like Chrome, Mozilla, Safari, etc, but it's not loading some pages in node-webkit and PyQt webkit.
I am trying to load the file using an iframe, like this:
<iframe src="/test/?file=/assets/pdf/example.pdf#page=3"> </iframe>
Below are some more up-to-date demo scripts for using pdf.js with PyQt4/QtWebKit or PyQt5/QtWebEngine. To try these, first download the latest stable version of pdf.js and unpack the zip file into a suitable location. (NB: if you're on Linux your distro may already have a pdf.js package, so that could be installed instead).
UPDATE:
As of Qt-5.13.0, it is also possible to use the built-in Chromium PDF Viewer with QWebEngineView:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
PDF = 'file://path/to/my/sample.pdf'
class Window(QtWebEngineWidgets.QWebEngineView):
def __init__(self):
super().__init__()
self.settings().setAttribute(
QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
self.settings().setAttribute(
QtWebEngineWidgets.QWebEngineSettings.PdfViewerEnabled, True)
self.load(QtCore.QUrl.fromUserInput(PDF))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 50, 800, 600)
window.show()
sys.exit(app.exec_())
PyQt5/QtWebEngine pdfjs script:
UPDATE:
NB: as of Aug 2022, it may be necessary to use the legacy build of pdfjs (i.e. the build for "older browsers" on the download page) to keep things working with PyQt5. The stable build should work okay with PyQt6, though.
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
PDFJS = 'file:///path/to/pdfjs-1.9.426-dist/web/viewer.html'
# PDFJS = 'file:///usr/share/pdf.js/web/viewer.html'
PDF = 'file:///path/to/my/sample.pdf'
class Window(QtWebEngineWidgets.QWebEngineView):
def __init__(self):
super().__init__()
self.load(QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF)))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 50, 800, 600)
window.show()
sys.exit(app.exec_())
PyQt4/QtWebKit pdfjs script:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
PDFJS = 'file:///path/to/pdfjs-1.9.426-dist/web/viewer.html'
# PDFJS = 'file:///usr/share/pdf.js/web/viewer.html'
PDF = 'file:///path/to/my/sample.pdf'
class Window(QtWebKit.QWebView):
def __init__(self):
super().__init__()
self.load(QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF)))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 50, 800, 600)
window.show()
sys.exit(app.exec_())
I've found this thread over at the Qt Forums, where thebeast44 posted a snippet of Qt code answering your question. My translation to python is below.
You'll also need to unpack the res folder from the author's original code, I think he just modified the viewer... I've also attached said code here.
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtNetwork
from PyQt4 import QtWebKit
class PDFViewer(QtWebKit.QWebView):
pdf_viewer_page = 'res/pdf-viewer.html'
def __init__(self, parent=None):
super().__init__(parent)
self.settings = QtWebKit.QWebSettings.globalSettings()
self.settings.setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessFileUrls, True )
self.settings.setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessRemoteUrls, True )
self.settings.setAttribute(QtWebKit.QWebSettings.DeveloperExtrasEnabled, True )
nam = QtNetwork.QNetworkAccessManager()
page = QtWebKit.QWebPage(self)
page.setNetworkAccessManager(nam)
self.setPage(page)
self.loadFinished.connect(self.onLoadFinish)
self.setUrl(QtCore.QUrl(self.pdf_viewer_page))
def onLoadFinish(self, success):
if success:
self.page().mainFrame().evaluateJavaScript("init();")
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
viewer = PDFViewer(parent=None)
viewer.show()
sys.exit(app.exec_())
From PyQt5 v5.13 you can load PDF files with the chromium API. According to the documentation https://doc.qt.io/qt-5/qtwebengine-features.html#pdf-file-viewing this option is by default enabled.
This minimal example is adapted from Simple Browser
import sys
from pathlib import Path
from PyQt5 import QAxContainer
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLineEdit, QApplication
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.main_layout = QVBoxLayout(self)
self.qlineedit = QLineEdit()
self.qlineedit.returnPressed.connect(self.go_action)
self.main_layout.addWidget(self.qlineedit)
self.read_btn = QPushButton('Test')
self.read_btn.clicked.connect(self.go_action)
self.main_layout.addWidget(self.read_btn)
self.WebBrowser = QAxContainer.QAxWidget(self)
self.WebBrowser.setFocusPolicy(Qt.StrongFocus)
self.WebBrowser.setControl("{8856F961-340A-11D0-A96B-00C04FD705A2}")
self.main_layout.addWidget(self.WebBrowser)
def go_action(self):
# convert system path to web path
f = Path(self.qlineedit.text()).as_uri()
# load object
self.WebBrowser.dynamicCall('Navigate(const QString&)', f)
if __name__ == "__main__":
a = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(a.exec_())
This example:

Categories