Can't add a stretched background image with PyQt5
-
Hi,
I've been struggling with this for the last 3 days... I would like to simply add a stretched background image to my parent QWidget. I literally tried a dozens of times after searching everywhere but I'm still stuck with this issue. I don't use resources (from qt designer). PSB :
from PyQt5 import QtCore, QtWidgets, QtGui import sys class Ui_Form(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(self) self.setupUi(self) def setupUi(self, Form): Form.setObjectName("Form") Form.resize(860, 619) Form.setStyleSheet("QWidget#Form {border-image: url(space.png) 0 0 0 0 stretch stretch;}")
And it does not work. But when I execute this:
Form.setStyleSheet("border-image: url(space.png) 0 0 0 0 stretch stretch;")
All Qwidget's children get the background which is obviously not what I want. But it proves at least that there is no problem with the resource itself.
I've tried to make it work via Qpalette() and it works better but I don't know how to make the background image stretched =/ :
image = QtGui.QImage("space.png") palette = QtGui.QPalette() palette.setBrush(10, QtGui.QBrush(image)) Form.setPalette(palette)
Any idea ?
-
HI and welcome
Maybe you can "cheat" and use a QLabel ?
http://stackoverflow.com/questions/10915215/pyqt-qt-how-to-stretch-an-image-in-qlabel-widgetself.label.setScaledContents(true);
also as a note:
Form.setStyleSheet("borde xxx
have no type selector ("QWidget#..")
so it applies to all childs of the form.
"QMainwndow#" would target the form
http://doc.qt.io/qt-5/stylesheet-examples.html -
Thanks for your reply, you gave me some inspiration.
I took a look at "Qt Style Sheets Examples" and I could not find how to customize a QWidget so I simply convert my QWidget to a QMainWindow. I got rid of the menu bar and the status bar because I don't need them... everything works fine now with QMainWindow :)`class Ui_MainWindow(QtWidgets.QMainWindow):
def __init__(self): super().__init__() self.setupUi(self) def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(856, 610) MainWindow.setStyleSheet("#MainWindow { border-image: url(space.png) 0 0 0 0 stretch stretch; }") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget")`
-
super :)
also using "#MainWindow" makes sure it dont apply to childs as stylesheets does.