如何在Pyside2的QTabWidget中更改特定选项卡的字体?

问题描述

事件触发后,我想将特定选项卡的字体更改为使用粗体而不是非粗体。

qtabwidget.tabs[4].setFontWeight(Bold)

该怎么做?

解决方法

一种可能的解决方案是使用QProxyStyle:

import sys

from PySide2 import QtCore,QtGui,QtWidgets


class TabBarStyle(QtWidgets.QProxyStyle):
    def drawControl(self,element,option,painter,widget=None):
        index = -1
        if element == QtWidgets.QStyle.CE_TabBarTab:
            if isinstance(widget,TabBar):
                for i in widget.fonts.keys():
                    if widget.tabRect(i) == option.rect:
                        index = i
                        break
            if index > -1:
                painter.save()
                painter.setFont(widget.fonts[index])
        super(TabBarStyle,self).drawControl(element,widget)
        if index > -1:
            painter.restore()


class TabBar(QtWidgets.QTabBar):
    def __init__(self,parent=None):
        super(TabBar,self).__init__(parent)
        self._fonts = dict()

    @property
    def fonts(self):
        return self._fonts


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)

        self.tab_widget = QtWidgets.QTabWidget()
        self.setCentralWidget(self.tab_widget)

        self.tab_bar = TabBar()
        self.tabbar_style = TabBarStyle(self.tab_bar.style())
        self.tab_bar.setStyle(self.tabbar_style)
        self.tab_widget.setTabBar(self.tab_bar)

        self.tab_widget.addTab(QtWidgets.QWidget(),"Foo")
        self.tab_widget.addTab(QtWidgets.QWidget(),"Bar")
        self.tab_widget.addTab(QtWidgets.QWidget(),"Baz")

        font = self.tab_widget.font()
        font.setBold(True)
        self.tab_bar.fonts[1] = font
        self.tab_bar.update()


def main():
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...