Issue
Is there a way for me to set base64 code to the background of a QMainWindow. I don't want to save these images, but I just want to set them as the background.
This is the code I use to turn base64 code into a QPixmap
:
bkgnd = QtGui.QPixmap(QtGui.QImage.fromData(base64.b64decode('some base64 code')))
With some base64 code, it can look like this:
bkgnd = QtGui.QPixmap(QtGui.QImage.fromData(base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAeElEQVQ4T2NkoBAwUqifgboGzJy76AIjE3NCWmL0BWwumzV/qcH/f38XpCfHGcDkUVwAUsDw9+8GBmbmAHRDcMlheAGbQnwGYw0DZA1gp+JwFUgKZyDCDQGpwuIlrGGAHHAUGUCRFygKRIqjkeKERE6+oG5eIMcFAOqSchGwiKKAAAAAAElFTkSuQmCC')))
I've searched up how to set a QPixmap as a window background, but I don't get anything that works.
Solution
There is no direct way to do this, so you need to implement the paint event of the main window, and ensure that its central widget does not paint its background (by setting the background color in the stylesheet or using autoFillBackground()
).
The following will render the pixmap at the center:
class Win(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setCentralWidget(QtWidgets.QWidget())
self.bkgnd = QtGui.QPixmap # base64 data ...
def paintEvent(self, event):
qp = QtGui.QPainter(self)
pmRect = self.bkgnd.rect()
pmRect.moveCenter(self.centralWidget().geometry().center())
qp.drawPixmap(pmRect, self.bkgnd)
You can also get tiling:
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.fillRect(self.centralWidget().geometry(), QtGui.QBrush(self.bkgnd))
Or stretch the contents of the image:
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.drawPixmap(self.centralWidget().geometry(), self.bkgnd)
Or scale by keeping the aspect ratio:
def paintEvent(self, event):
qp = QtGui.QPainter(self)
rect = self.centralWidget().geometry()
scaled = self.bkgnd.scaled(rect.size(), QtCore.Qt.KeepAspectRatio)
pmRect = scaled.rect()
pmRect.moveCenter(rect.center())
qp.drawPixmap(pmRect, scaled)
In all the situations above, you can also try to use the full rectangle of the main window (self.rect()
) instead of that of the central widget, if you want to set a background that also renders under menus, toolbars, etc, but I would not suggest you to do so, as it would probably make those elements difficult to see, and it's also possible that some styles would paint their background in any case.
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.