我正在使用Python 3.6中的matplotlib库和PyQt5。我在创建的窗口中添加了一个图形,希望为该图形设置透明背景,因为我将图像添加到窗口的背景中。但是,该图形并不真正透明,它会重复窗口的背景图像。
例如,有人两年前遇到了同样的问题: matplotlib and pyqt4 transparent background 这里有一个可工作的示例(具有黑色背景,但图形不是黑色的):
例如,有人两年前遇到了同样的问题: matplotlib and pyqt4 transparent background 这里有一个可工作的示例(具有黑色背景,但图形不是黑色的):
import sys, os
from PyQt5.QtCore import Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import matplotlib
matplotlib.use('Qt5Agg') # Make sure that we are using QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class SecondWindow(QWidget):
def __init__(self, parent=None):
super(SecondWindow, self).__init__(parent)
self.setupUi(self)
def setupUi(self, Form):
# WINDOW SETTINGS
Form.setWindowTitle('Hello')
self.p = QPalette()
self.pixmap = QPixmap(os.getcwd() + "/logo.png").scaled(self.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
self.p.setBrush(QPalette.Background, QBrush(self.pixmap))
self.setPalette(self.p)
# CREATE FIGURE AND SETTINGS
self.figure = plt.figure()
self.figure.patch.set_facecolor('None')
self.figure.patch.set_alpha(0)
self.canvas = FigureCanvas(self.figure)
self.axes = self.figure.add_subplot(111)
# WINDOW LAYOUT (with H1 and H2)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.canvas,1)
self.layout().setContentsMargins(50, 50, 50, 50)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = SecondWindow()
form.show()
sys.exit(app.exec_())
我花费了很长时间寻找答案,但还没有找到解决方案。谢谢你能提供的任何帮助!
- 操作系统: Windows 7 Pro
- Matplotlib版本: 2.0.2(通过Anaconda安装,使用命令conda install matplotlib --channel conda-forge)
- Python版本: Python 3.6
- Anaconda 3