Reputation: 31
Strangely, while I have successfully added a background containing transparency in a PyQt application, much of the image remains black.
from PyQt4.QtGui import *
import sys
class BackgroundIssue(QMainWindow):
def __init__(self):
super(BackgroundIssue, self).__init__()
def resizeEvent(self, event):
pixmap = QPixmap("res/background.png")
region = QRegion(pixmap.mask())
self.setMask(pixmap.mask())
def main():
app = QApplication(sys.argv)
window = BackgroundIssue()
palette = QPalette()
palette.setBrush(QPalette.Background,QBrush(QPixmap("res/background.png")))
window.setPalette(palette)
window.setWindowTitle("Partially Black Background Image")
window.show()
return app.exec_()
if __name__ == '__main__':
main()
The result is this while the actual image looks like this. (note that the white in the first link is correctly functioning transparency.)
I've looked everything and broke my head over this and tried a dozen different solutions. Can anyone at least explain what is this phenomenon called?
Thanks!
Upvotes: 0
Views: 4241
Reputation: 31
I've finally resolved this issue: the answer actually lies in overlaying. By setting QtGui.Qt.WA_TranslucentBackground
to True and then setting the background in a widget contained within, the main window draws the desktop background and then the transparent image within the widget draws from the parent window. It seems that it's impossible to have an image both directly inherit the transparency of the desktop and draw the background into the opacity. There seems to be a need for a layer of abstraction for any image that has partial opacity in it.
Final code:
from PyQt4 import QtGui, QtCore
import sys
class BackgroundWidget(QtGui.QWidget):
def __init__(self):
super(BackgroundWidget, self).__init__()
palette = QtGui.QPalette()
palette.setBrush(QtGui.QPalette.Background, QtGui.QBrush(QtGui.QPixmap("res/img/background.png")))
self.setAutoFillBackground(True)
self.setPalette(palette)
self.show()
class BackgroundIssue(QtGui.QMainWindow):
def __init__(self):
super(BackgroundIssue, self).__init__()
self._widget = BackgroundWidget()
self.setCentralWidget(self._widget)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.resize(1002, 660)
self.setWindowTitle("Partially Black Background Image")
self.show()
def resizeEvent(self, event):
pixmap = QtGui.QPixmap("res/background.png")
region = QtGui.QRegion(pixmap.mask())
self.setMask(pixmap.mask())
def main():
app = QtGui.QApplication(sys.argv)
window = BackgroundIssue()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Upvotes: 3