【发布时间】:2020-10-20 19:50:11
【问题描述】:
创建 PyQt5 选项卡小部件时,背景颜色比普通小部件的背景更白。我正在寻找一种方法来获取标签的确切背景颜色。
与这个问题相关的一些很好的例子是:
Get the background color of a widget - really
How to make the background color the same as the form background?
获取背景颜色最常见的建议是使用:
widget.palette().color(QtGui.QPalette.Background)
# alternatively with QtGui.QPalette.Base
没有一个得到确切的颜色。前者太黑,后者太白。
这是否适用还取决于您使用的样式和系统。就我而言,它是在 Linux Mint 设置上,但该应用程序也适用于 Windows。
===== 用这个来设置matplotlib图的背景=====
这个问题的用例是保持 matplotlib 图形的 facecolor 与其嵌入的小部件一致。
这是我的例子:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import matplotlib as mpl
class Window(QtWidgets.QMainWindow):
""" Class to use the data pattern widget in a separate window"""
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
# ===== Setup the window =====
self.setWindowTitle("background")
self.resize(600, 400)
self.maintabs = QtWidgets.QTabWidget(self)
self.setCentralWidget(self.maintabs)
self.page = QtWidgets.QWidget(self)
self.mpl_layout = QtWidgets.QHBoxLayout(self.page)
self.maintabs.addTab(self.page, 'Demo tab')
# ===== Set up matplotlib canvas =====
self.mpl_canvas = None
# get background color from widget and convert it to RBG
pyqt_bkg = self.maintabs.palette().color(QtGui.QPalette.Background).getRgbF()
mpl_bkg = mpl.colors.rgb2hex(pyqt_bkg)
self.pltfig = mpl.figure.Figure()
self.pltfig.set_facecolor(mpl_bkg) # uses the background of mainwindow and not tab
self.plot_ax = self.pltfig.add_subplot(111)
self.addmpl(self.pltfig)
def addmpl(self, fig):
self.mpl_canvas = FigureCanvas(fig)
self.mpl_layout.addWidget(self.mpl_canvas)
self.mpl_canvas.draw()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec())
导致,
【问题讨论】:
标签: python qt matplotlib pyqt pyqt5