cimpok
Posts: 2
Joined: Sun Sep 08, 2019 1:34 pm

PyQt5 QWebView loading images with centered aligment

Sun Sep 08, 2019 1:56 pm

I am using PyQt5's QWebView widget to display images stored in a playlist in a Python program, the simpified part is here:

Code: Select all

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebKit import *
from PyQt5.QtWebKitWidgets import *
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow

class Browser(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)
		self.webview = QWebView()
		self.setCentralWidget(self.webview)
		self.setWindowFlags(Qt.FramelessWindowHint)     # no title no border
		self.setStyleSheet("background-color:black;")
...
browser = Browser() 
browser.webview.load(QUrl("file:///home/pi/images/test.jpg"))
browser.showMaximized()
browser.show()
sys.exit(app.exec_())
The image shows horizontally centered (I don't know why, I have nowhere set the aligment to horizontal center) But I want to show the image both horizontally and vertically centered on the display, could someone help me out how to do this. Thank you.

User avatar
topguy
Posts: 5781
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: PyQt5 QWebView loading images with centered aligment

Mon Sep 09, 2019 10:50 am

Load a HTML file which loads the image and you can probably place it wherever you want. A webview is a web-browser after all.

With a little bit of Javascript you can add the imagename as a parameter in the url.

cimpok
Posts: 2
Joined: Sun Sep 08, 2019 1:34 pm

Re: PyQt5 QWebView loading images with centered aligment

Mon Sep 09, 2019 10:29 pm

Thank you topguy, that did it!
I was already thinking to load HTML instead of directly the image, but considered it as an overkill and tried to use the setStyleSheet method with various settings instead, but got tangled up with it.

With the idea of loading HTML you pushed me in the right direction. This is also more flexible, so I can add many more things to the page than just a plain image. I am trying to add fading in/out transitions via .css and javascript. Don't know however in what extent can webview run javascript, or is capable of this kind of DOM animation at all. I'll see.

Return to “General discussion”