【问题标题】:Get background color of QTabWidget in PyQt5在 PyQt5 中获取 QTabWidget 的背景颜色
【发布时间】: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


    【解决方案1】:

    调色板的颜色只是样式如何实际绘制小部件的参考。一些小部件使用渐变来显示它们的内容(考虑按钮,它通常“发光”为调色板按钮角色指定的颜色)。一些样式甚至使用看起来与该类型小部件无关的角色来绘制一些小部件。

    QTabWidget 的行为方式类似(取决于样式),因此即使您获得了它的背景,它也可能会涂上稍微不同的颜色。

    一种可能的解决方案是使用样式表设置小部件的背景,同时仍保留调色板参考:

        self.maintabs.setStyleSheet('background: palette(window);')
    

    请注意,这将使maintabs所有 子小部件使用纯背景色。

    【讨论】:

      【解决方案2】:

      您可以使用样式表来设置背景颜色,如下所示:

      self.maintabs.setStyleSheet("background-color: rgb(0,0,59)")
      

      【讨论】:

        猜你喜欢
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 2019-09-04
        • 2012-02-15
        • 2021-11-20
        相关资源
        最近更新 更多