Search code examples
qtuser-interfaceqwidget

QTabWidget: set a widget as the background widget when there is no tabs


I want to set a widget as the background widget of a tab widget when there is no tab opened. I wish it will work in this way:

  1. Initially there is no tab in the tab widget, I want to add a widget as the background of the tab widget, the background widget will show some hint text as the placeholder.
  2. When the user opens any tab, the background will be hidden automatially, and the background widget won't handle any user events(clicks, double-clicked, keyboard events).
  3. When all tabs are closed, the background shows again.

Any ideas? Thanks.


Solution

  • [Moved from comments]

    From the requirements you outline it sounds as if you don't really need a separate widget. Something like the following should suffice...

    #include <QApplication>
    #include <QLabel>
    #include <QPainter>
    #include <QTabWidget>
    
    namespace {
      class tab_widget: public QTabWidget {
        using super = QTabWidget;
      public:
        explicit tab_widget (QWidget *parent = nullptr)
          : super(parent)
          {}
      protected:
        virtual void paintEvent (QPaintEvent *event) override
          {
            super::paintEvent(event);
            if (!count()) {
              QPainter painter(this);
              painter.drawText(rect(), Qt::AlignCenter, "Some informative text goes here...");
            }
          }
      };
    }
    
    int
    main (int argc, char **argv)
    {
      QApplication app(argc, argv);
      tab_widget w;
      for (int i = 0; i < 5; ++i) {
        auto text = QString("Tab %1").arg(i);
        w.addTab(new QLabel(text), text);
      }
      w.show();
      return app.exec();
    }