将小部件添加到 QTabWidget

Add widgets into a QTabWidget

我可以将 QLabelQPushButton 等小部件添加到 QTabWidget 中吗?

实际上,我想做这样的事情:

我正在使用 C++ 和 Qt。

谢谢

如果你想做这件事,我建议你使用 QTabBar 而不是 QTabWidget。例如,您的代码可以是(请记住,这只是一个非常简单的示例):

// Here some first widget
QWidget *wid1 = new QWidget(this);
QHBoxLayout *wid1Lay = new QHBoxLayout(wid1);
wid1Lay->addWidget(new QLabel(tr("Widget1")));

// Here some second widget
QWidget *wid2 = new QWidget(this);
QHBoxLayout *wid2Lay = new QHBoxLayout(wid2);
wid2Lay->addWidget(new QLabel(tr("Widget2")));

// Here some third widget
QWidget *wid3 = new QWidget(this);
QHBoxLayout *wid3Lay = new QHBoxLayout(wid3);
wid3Lay->addWidget(new QLabel(tr("Widget3")));

// Here your Tab bar with only bars
QTabBar *bar = new QTabBar(this);
bar->addTab("One");
bar->addTab("Two");
bar->addTab("Three");

// Here some label (for example, current time) and button
QLabel *lab = new QLabel(tr("Some text"), this);
QPushButton *but = new QPushButton(tr("Push"), this);

// Main layouts
QVBoxLayout *vLay = new QVBoxLayout(ui->centralWidget);
QHBoxLayout *hLay = new QHBoxLayout();

vLay->addLayout(hLay);
hLay->addWidget(bar);
// Spacer for expanding left and right sides
hLay->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum));
hLay->addWidget(lab);
hLay->addWidget(but);

vLay->addWidget(wid1);
vLay->addWidget(wid2);
vLay->addWidget(wid3);

// Some simple connect with lambda for navigation
connect(bar, &QTabBar::currentChanged, [=] (int index) {

    wid1->setVisible(false);
    wid2->setVisible(false);
    wid3->setVisible(false);

    switch(index) {
    case 0: wid1->setVisible(true);
        break;
    case 1: wid2->setVisible(true);
        break;
    case 2: wid3->setVisible(true);
        break;
    default:{}
    }

});

emit bar->currentChanged(0);

可以,就用QTabWidget::setCornerWidget

快速示例:

        QWidget* pTabCornerWidget = new QWidget(this);

        QLabel* pLabelTime = new QLabel(pTabCornerWidget);
        pLabelTime->setText("10:22:20");

        QPushButton* pButton = new QPushButton(pTabCornerWidget);
        pButton->setText("?");
        pButton->setMaximumSize(QSize(25, 25));

        QHBoxLayout* pHLayout = new QHBoxLayout(pTabCornerWidget);
        pHLayout->addWidget(pLabelTime);
        pHLayout->addWidget(pButton);

        mUI.tabWidget->setCornerWidget(pTabCornerWidget, Qt::TopRightCorner);