【问题标题】:Closable QTabWidget tabs, but not all of them可关闭的 QTabWidget 选项卡,但不是全部
【发布时间】:2016-02-24 08:55:15
【问题描述】:

在一段 Qt/C++ 代码中,我有一个带有不同选项卡的 QTabWidget 类。 我想添加最后一个“+”标签,所以当用户点击它时,我会创建一个新标签。
但是,我希望所有选项卡都可以关闭(选项卡右侧的“x”),除了最后一个我不希望显示“x”的选项卡。我怎样才能在可关闭标志中有这种粒度?

【问题讨论】:

  • 这可能是一个解决方案,但不会阻止“x”显示在我的“+”附近,我想避免这种情况。
  • 我不明白...你不需要为一个标签显示关闭按钮 - 我给你一个解决方案。请澄清您的问题。
  • 是的,如果打开了 5 个标签,我希望第 4 个显示 'x' 关闭按钮,而第 5 个标签上什么都没有。

标签: c++ qt qtabwidget


【解决方案1】:

惊讶地发现这还没有回答。有一些时间,我已经实现了一个工作示例。请注意,我没有使用其中一个选项卡作为“+”按钮,而是使用了QToolButton,从而使使用QTabWidget::setTabsClosable(bool)关闭选项卡变得更简单

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTabWidget>
#include <QToolButton>
#include <QLabel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QTabWidget* _pTabWidget;

private slots:
    void slotAddTab();
    void slotCloseTab(int);
};

#endif // MAINWINDOW_H

主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    _pTabWidget = new QTabWidget(this);
    this->setCentralWidget(_pTabWidget);

    // Create button what must be placed in tabs row
    QToolButton* tb = new QToolButton(this);
    tb->setText("+");

    // Add empty, not enabled tab to tabWidget
    _pTabWidget->addTab(new QLabel("Add tabs by pressing \"+\""), QString());
    _pTabWidget->setTabEnabled(0, false);

    // Add tab button to current tab. Button will be enabled, but tab -- not
    _pTabWidget->tabBar()->setTabButton(0, QTabBar::RightSide, tb);

    // Setting tabs closable and movable
    _pTabWidget->setTabsClosable(true);
    _pTabWidget->setMovable(true);
    connect(tb,SIGNAL(clicked()),this,SLOT(slotAddTab()));
    connect(_pTabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT(slotCloseTab(int)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotAddTab()
{
    QWidget* newTab = new QWidget(_pTabWidget);
    _pTabWidget->addTab(newTab, tr("Tab %1").arg(QString::number(_pTabWidget->count())));
    _pTabWidget->setCurrentWidget(newTab);
}

void MainWindow::slotCloseTab(int index)
{
    delete _pTabWidget->widget(index);
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

【讨论】:

  • 好像需要在mainwindow.h中添加#include &lt;QTabBar&gt;,否则Qt creator会报错:use of undefined type 'QTabBar'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多