将小部件添加到QTabWidget中

时间:2016-06-06 03:33:20

标签: c++ qt qlabel qpushbutton qtabwidget

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

实际上,我想做这样的事情: enter image description here

我正在使用C ++和Qt。

由于

2 个答案:

答案 0 :(得分:7)

如果您想要这样做,我建议您使用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);

答案 1 :(得分:6)

这是可能的,只需使用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);