PyQt4:如何分别为QTabWidget中的每个选项卡着色?

问题描述 投票:0回答:1

我正在开发一个带有GUI的项目,我正在使用Python和PyQt4模块。

这是我的演示代码:

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setWindowTitle('PyQt4 demo')
        self.setGeometry(50, 50, 1000, 1000)
        self.createTabs()
        self.styleTabs()
        self.show()

    def createTabs(self):
        '''Creates a QTabWidget with 5 tabs,
        named 1, 2, 3, 4, 5
        '''

        self.tabs = QtGui.QTabWidget(self)
        self.tabs.resize(1000, 1000)

        contents1 = QtGui.QWidget()
        contents2 = QtGui.QWidget()
        contents3 = QtGui.QWidget()
        contents4 = QtGui.QWidget()
        contents5 = QtGui.QWidget()

        self.tabs.addTab(contents1, '1')
        self.tabs.addTab(contents2, '2')
        self.tabs.addTab(contents3, '3')
        self.tabs.addTab(contents4, '4')
        self.tabs.addTab(contents5, '5')

    def styleTabs(self):
        #Would like to add some code here which colors
        #each tab with a different color.
        pass


def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

大多数对象(包括QtabWidget和QTabBar)使用.setStyleSheet(str)方法支持CSS样式。但有了这个,我只能用相同的颜色着色所有标签。我还找到了一种方法来选择颜色,第一个,最后一个选项卡,但是永远不能为标签着色:索引为2。

例如:

self.tabs.setStyleSheet('''
    QTabBar::tab {background-color: green;}
    QTabBar::tab:selected {background-color: red;}
    QTabBar::tab:first {background-color: red;}
    QTabBar::tab:last {background-color: red;}
    ''')

我也尝试将颜色应用到当前的QTabBar。这适用于Qt,但显然不适用于PyQt:

tab = self.tabs.tabBar()
tab.setStyleSheet('background-color: grey;')

PyQt4着色方法也不起作用:

plt = QtGui.QPalette()
clr = QtGui.QColor()
clr.setRgb(100, 100, 100)
plt.setColor(10, clr)
tab.setPalette(plt)

我一直在网上搜索很多,但没有找到任何解决这个问题的方法。在这一点上,我甚至不确定是否存在简单的解决方案。

有没有办法修改PyQt4源代码,所以可以应用上述技术之一?

附加信息:

  • Python 3.4版
  • PyQt版本4.12
python python-3.x pyqt pyqt4 qtabwidget
1个回答
0
投票

不幸的是,QTabBar没有公开它的所有属性,因为它的内容不是以正常方式布局的子窗口小部件,而是使用私有方法在内部绘制。

但是,有两种可能性。

  1. 使用paintEvent手动绘制tabbar。使用QStyle draw *方法,可以根据需要自定义它,同时保持与当前主题的一致性;这不是一件容易的事,但可以做到。
  2. 仅自定义当前所选选项卡的背景:使用QTabBar的currentChanged信号,您可以在每次更改当前索引时轻松重置样式表

这是一个例子:

def createTabs(self):
    #[create your tabs, then...]
    self.tabColors = {
        0: 'green', 
        1: 'red', 
        2: 'yellow', 
        3: 'orange', 
        4: 'blue', 
        }
    self.tabs.tabBar().currentChanged.connect(self.styleTabs)

[...]

def styleTabs(self, index):
    self.tabs.setStyleSheet('''
        QTabBar::tab {{}}
        QTabBar::tab:selected {{background-color: {color};}}
        '''.format(color=self.tabColors[index]))

您可能希望在首次显示窗口小部件时通过调用styleTabs(0)来“初始化”它,因为仅在触发信号时应用着色。

© www.soinside.com 2019 - 2024. All rights reserved.