1

I've subclassed QDockWidget and I am setting the title-bar text via myDockWidget.setWindowTitle("Some text"). However, I'd like to display different text in the tab when the widget is docked. In other words, when the widget is docked, I'd like to display one string in the title-bar and a different string in the tab:

enter image description here

Is this possible and, if so, how can it be done?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
LKeene
  • 627
  • 1
  • 8
  • 22

1 Answers1

4

This can be achieved by reimplementing the paintEvent and overriding the default title-bar text. The window-title must still be used to set the tab-text:

class DockWidget(QtGui.QDockWidget):
    _title_text = None

    def titleText(self):
        if self._title_text is None:
            return self.windowTitle()
        return self._title_text

    def setTitleText(self, text):
        self._title_text = text
        self.repaint()

    def paintEvent(self, event):
        painter = QtGui.QStylePainter(self)
        if self.isFloating():
            options = QtGui.QStyleOptionFrame()
            options.initFrom(self)
            painter.drawPrimitive(QtGui.QStyle.PE_FrameDockWidget, options)
        options = QtGui.QStyleOptionDockWidgetV2()
        self.initStyleOption(options)
        options.title = self.titleText()
        painter.drawControl(QtGui.QStyle.CE_DockWidgetTitle, options)

dockWidget = DockWidget()
dockWidget.setWindowTitle('Tab Text')
dockWidget.setTitleText('Title Text')

PS:

Note that another option is to use setTitleBarWidget. However, the huge disadvantage of this, is that you lose all the native window decorations.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • For PyQt5, replacing `QtGui` to `QtWidgets`, and `QStyleOptionDockWidgetV2` to `QStyleOptionDockWidget` works for me. – Tong Jul 21 '23 at 15:28