2016-06-21 264 views
0

奇怪的是,雖然我成功地在PyQt應用程序中添加了一個包含透明度的背景,但大部分圖像仍爲黑色。PyQt透明背景圖像部分黑

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() 

結果是this而實際的圖像看起來像this。 (請注意,第一個鏈接中的白色正確運行的透明度。)

我已經看了一切,並打破了我的頭,並嘗試了一打不同的解決方案。任何人至少可以解釋這種現象稱爲什麼?

謝謝!

回答

1

我終於解決了這個問題:答案實際上在於重疊。通過將QtGui.Qt.WA_TranslucentBackground設置爲True,然後在其中包含的窗口小部件中設置背景,主窗口將繪製桌面背景,然後窗口小部件中的透明圖像將從父窗口繪製。看起來,不可能有圖像直接繼承桌面的透明度,並將背景繪製爲不透明。對於部分不透明的圖像,似乎需要一層抽象。

最終代碼:

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()