Search code examples
c++qtqt5qt4.8qtabwidget

How to set QWidget in QTabWidget header?


I want to insert QLabel and QLineEdit in the header of QTabWidget. I've read the documentation of Qt but didn't able to find any function that can set any Qwidget in the Header of QTabWidget.

How can i do this? Or do i have to override the QTabWidget Painter function?

Any Suggestions?


Solution

  • You must use the setTabButton function:

    void QTabBar::setTabButton(int index, ButtonPosition position, QWidget * widget)

    Sets widget on the tab index. The widget is placed on the left or right hand side depending upon the position.

    Any previously set widget in position is hidden.

    The tab bar will take ownership of the widget and so all widgets set here will be deleted by the tab bar when it is destroyed unless you separately reparent the widget after setting some other widget (or 0).

    This function was introduced in Qt 4.5.

    This is not associated with QTabWidget but its QTabBar.

    To get the QtabBar you must use the function:

    QTabBar * QTabWidget::tabBar() const

    Returns the current QTabBar.

    Example:

    #include <QApplication>
    
    #include <QLabel>
    #include <QTabBar>
    #include <QTabWidget>
    #include <QLineEdit>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QTabWidget w;
        w.addTab(new QLabel("widget 1"), "1");
        w.addTab(new QLabel("widget 2"), "2");
    
        QTabBar *tabBar = w.tabBar();
    
        tabBar->setTabButton(0, QTabBar::LeftSide, new QLineEdit("LineEdit0"));
        tabBar->setTabButton(0, QTabBar::RightSide, new QLabel("label0"));
    
        tabBar->setTabButton(1, QTabBar::LeftSide, new QLineEdit("LineEdit1"));
        tabBar->setTabButton(1, QTabBar::RightSide, new QLabel("label1"));
        w.show();
    
        return a.exec();
    }
    

    Output:

    enter image description here