Search code examples
c++qtqtabwidget

How to set only one tab in a QTabWidget as not moveable in Qt?


I need to set only one tab in a QTabWidget as not moveable. I cannot find a way to do this. Also in Qt designer you can only (un)check "moveable", but this doesn't work for just one specific tab.


Solution

  • Looking at the source code of QTabBar (sub-element of QTabWidget), it seems that this is not possible. There is only one movable property for all tabs.

    However, you could try the following:

    1. Subclass QTabBar and catch the mouse press events before a drag starts to enable or disable the moving of tabs. Something like this:

      void MyTabBar::mousePressEvent(QMouseEvent *event) {
          // all tabs movable except first
          setMovable(tabAt(event->pos()) != 0);
      
          QTabBar::mousePressEvent(event);
      }
      
    2. Then before you add the tabs, replace the default tabbar with your subclass:

      myTabWidget->setTabBar(new MyTabBar());
      

    This is probably a bit leaky, I haven't tried it out. The first thing that comes to mind is that setMovable() does not work anymore. Maybe also dragging some other tabs will result in some odd behavior.


    Have you considered, that maybe a QTabWidget is not the right GUI-element? There is no graphical hint that tabs are draggable or not and might confuse the user. Maybe it's better to use a QStackedWidget and a custom way to change between the pages.