的QTabWidget选项卡的颜色变化 [英] Change color of QTabWidget tab's

查看:6119
本文介绍了的QTabWidget选项卡的颜色变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要定制一个QTabWidget,让每一个标签都有它自己的背景颜色。我知道,这不能用样式表来完成,所以我子类QTabBar,改变它的paintEvent。然后,我取代QTabWidget的默认QTabBar用我自己的实现。然而,翼片的背景颜色不发生变化。有谁知道我缺少的是什么?

I want to customize a QTabWidget, so that every tab has it's own background color. I know, that this cannot be done with stylesheets, so I subclassed QTabBar and changed it's paintEvent. Then, I replaced the default QTabBar of QTabWidget with my own implementation. However, the background color of the tabs doesn't change. Does anybody know what I am missing?

下面是说明我的问题,一个小演示应用程序:

Here is a small demo application which illustrates my problem:

from PyQt4 import QtGui 

import sys

class coloredTabBar(QtGui.QTabBar):
    def __init__(self, parent = None):
        QtGui.QTabBar.__init__(self, parent)

    def paintEvent(self, event):
        p = QtGui.QStylePainter(self)
        painter = QtGui.QPainter(self)
        for index in range(self.count()): #for all tabs
            tab = QtGui.QStyleOptionTabV3() #create styled tab
            self.initStyleOption(tab, index) #initialize with default values
            #change background color to red
            tab.palette.setColor(QtGui.QPalette.Base, QtGui.QColor(255, 0, 0)) 
            p.drawControl(QtGui.QStyle.CE_TabBarTab, tab) #draw tab


class coloredTabWidget(QtGui.QTabWidget):
    def __init__(self, parent = None):
        QtGui.QTabWidget.__init__(self, parent)

        coloredTabs = coloredTabBar()
        self.setTabBar(coloredTabs) #replace default tabBar with my own implementation

if __name__ == "__main__":     
    app = QtGui.QApplication(sys.argv)

    tabWidget = coloredTabWidget()

    tabWidget.addTab(QtGui.QWidget(), "Hello")
    tabWidget.addTab(QtGui.QWidget(), "World")

    tabWidget.show()

    sys.exit(app.exec_())

亲切的问候

伯恩哈德

推荐答案

您使用了错误的调色板作用。您需要 QPalette.Window ,这是一般的小部件背景色,而不是 QPalette.Base ,这是更专业的元素,如编辑的控件:

You're using the wrong palette role. You need QPalette.Window, which is the general widget background color, rather than QPalette.Base, which is for more specialized elements like edit-controls:

tab.palette.setColor(QtGui.QPalette.Window, QtGui.QColor(255, 0, 0))

然而,你应该知道,以这种方式画的标签将无法在所有的平台上工作。这是因为一些Windows和Mac风格的使用像素图绘制标签的时候,所以不要拿调色板变化考虑进去。看到这个<一个href=\"https://wiki.qt.io/Qt_project_org_faq#Why_does_nothing_happen_when_I_set_the_palette_background_color_on_a_QPushButton_in_some_styles.3F\"相对=nofollow> Qt的常见问题解答更多的细节。

这篇关于的QTabWidget选项卡的颜色变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆