Issue
I have a QTabWidget
and I want a property on the individual tabs that holds whether the tab is persistent or not (similar to the tabs in VSCode, where if you don't double click a file it won't persist in the editor)
I have this so far. I want the TabItem
's with _persistent=False
to be in italic's and the others to be in normal font.
from PySide2 import QtWidgets, QtCore, QtGui
class TabItem(QtWidgets.QWidget):
def __init__(self, persistent=False):
super(TabItem, self).__init__()
self._persistent = persistent
self.setProperty('persistent', '0' if not persistent else '1')
class TabWidget(QtWidgets.QTabWidget):
def __init__(self):
super(TabWidget, self).__init__()
item1 = TabItem(persistent=False)
item2 = TabItem(persistent=True)
self.addTab(item1, 'FirstItem')
self.addTab(item2, 'SecondItem')
self.setStyleSheet("""
QTabBar::tab{
font: normal;
}
QTabBar::tab[persistent="0"]{
font: italic;
}
""")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
win = TabWidget()
win.show()
sys.exit(app.exec_())
Solution
Style sheet pseudo selectors don't support property selectors, because properties are set for the widget, whereas pseudo selectors are elements of that widget.
The only way to achieve that (besides completely overriding the paintEvent()
of the QTabBar) is through a QProxyStyle, and by implementing drawControl
.
The trick is to find which tab the current option rect belongs to, and eventually check the property of that tab to set the font.
class TabStyle(QtWidgets.QProxyStyle):
def drawControl(self, ctl, opt, qp, widget=None):
if ctl == self.CE_TabBarTabLabel:
for i in range(widget.count()):
tabRect = widget.tabRect(i)
if tabRect == opt.rect:
tabWidget = widget.parent()
try:
if tabWidget.widget(i)._persistent:
qp.save()
font = qp.font()
font.setItalic(True)
qp.setFont(font)
super().drawControl(ctl, opt, qp, widget)
qp.restore()
return
except:
pass
super().drawControl(ctl, opt, qp, widget)
# ...
app = QtWidgets.QApplication(sys.argv)
app.setStyle(TabStyle())
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.