如何在QTabWidget header中设置QWidget?

How to set QWidget in QTabWidget header?

我想在QTabWidget 的header 中插入QLabel 和QLineEdit。我已经阅读了 Qt 的文档,但没有找到任何可以在 QTabWidget 的 Header 中设置任何 Qwidget 的函数。

我该怎么做?或者我是否必须重写 QTabWidget Painter 函数?

有什么建议吗?

您必须使用setTabButton函数:

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.

这与 QTabWidget 无关,但与 QTabBar 相关。

要获得 QtabBar,您必须使用函数:

QTabBar * QTabWidget::tabBar() const

Returns the current QTabBar.

示例:

#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();
}

输出: