Search code examples
pythonpyqt4titlebarqdockwidget

How to set different text for a QDockWidget's tab and window title?


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?


Solution

  • 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.