QTabWidget -- multi page switching for creating tabs

QTabWidget is used for pagination display
Important functions:
1.void setTabText(int, QString); // Set the name of the page
2.void setTabToolTip(QString); // Set the prompt information of the page
3.void setTabEnabled(bool); // Set whether the page is activated
4.void setTabPosition(QTabPosition::South); // Set the location of the page name
5.void setTabsClosable(bool); // Set page close button.
6.int currentIndex(); // Returns the subscript of the current page, starting from 0
7.int count(); // Returns the number of pages
8.void clear(); // Clear all pages
9.void removeTab(int); // Delete page
10.void setMoveable(bool); // Set whether the page can be dragged and moved
11.void setCurrentIndex(int); // Sets the currently displayed page

signals:
1.void tabCloseRequested(int). // A signal is sent when the close button of the second parameter tab is clicked
2.void tabBarClicked(int). // When the parameter tab is clicked, a signal is sent
3.void currentChanged(int). // Signal when the parameter tab is changed
4.void tabBarDoubleClicked(int). // Signals when the second tab is double clicked
c.cpp

#include "c.h"
c::c(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    //Connect the signal to the slot
    connect(ui.insertButton, SIGNAL(clicked()), this, SLOT(addPageSlot()));    connect(ui.removeButton, SIGNAL(clicked()), this, SLOT(removePageSlot()));    connect(ui.dragButton, SIGNAL(clicked()), this, SLOT(dragPageSlot()));
}
c::~c()
{
}
void c::addPageSlot()
{
    //Define a QWidget
    QWidget *temp = new QWidget;
    //Inserts a new page after the current page
    ui.tabWidget->insertTab(ui.tabWidget->currentIndex() + 1, temp, QIcon("Icons/2.png"), QString::number(count));    //Displays a new page
    ui.tabWidget->setCurrentIndex(ui.tabWidget->indexOf(temp));
    count++;
}
void c::removePageSlot()
{
    //Delete the current page
    ui.tabWidget->removeTab(ui.tabWidget->currentIndex());}
void c::dragPageSlot()
{
    //Setting page items can be moved
    ui.tabWidget->setMovable(true);}    

c.h

#ifndef C_H
#define C_H
#include <QtWidgets/QMainWindow>
#include "ui_c.h"
#include <QTabWidget>
#include <QPushButton>
class c : public QMainWindow
{
    Q_OBJECT
    public:
    c(QWidget *parent = 0);
    ~c();
    private slots:   
     void addPageSlot();    
     void removePageSlot();    
     void dragPageSlot();private:
     Ui::cClass ui;   
     int count = 0;
};#endif

The QTabWidget can add tabs by using the addTab method and the insertTab method.
1. Add addTab method of tab

addTab is used to add a tab to QTabWidget. The tab position is behind all the existing tabs. The calling syntax is as follows:

int addTab(QWidget page, str label)
int addTab(QWidget page, QIcon icon, str label)

explain:

page For one QWidget Instance object whose name is the name of the corresponding tab
label The tab title text displayed for the tab bar, which can be represented by and symbols(&)With a shortcut key letter, the corresponding shortcut key is: Alt+Letter after symbol
icon Tab icons displayed for the tab bar
 The return value is the location index of the newly added tab in the tab bar

be careful:

If you call addTab () after QTabWidget's window show (), the layout system will try to adjust the component hierarchy to cause flickering. In order to prevent this situation, the QWidget.updateselebled property of the window can be set to False before changing, and the property will be set to True when the change is complete, so that the component can receive the drawing event again.
Example code:

	self.tab_reportManner = QtWidgets.QWidget()
    self.tab_reportManner.setObjectName("tab_reportManner")
    icon.addPixmap(QtGui.QPixmap(":/IT/image file/blog.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.tabWidget.addTab(self.tab_reportManner, icon, "Epidemic situation reporting method")

2. insertTab method for inserting tabs

The insertTab method of QTabWidget is used to insert a tab at the specified position of QTabWidget. The calling syntax is as follows:

int insertTab(int index, QWidget page, str label)
int insertTab(int index, QWidget page, QIcon icon, str label)

explain:

insertTab Method has more than one parameter index Except for parameters, other parameters and return values are the same
 If index If the value is out of range, the new tab is at the end of all tabs
 If before calling this function QTabWidget If there is no tab, the inserted tab will become the current page, otherwise the current page will remain unchanged

Qt – multi page switching component

I Multi page switching component
Multi page switching is very extensive in our daily software use and has good convenience. The following picture shows the convenience of multi page use

You can see that different page contents will appear when you click different titles with the mouse

A. QTabWidget, a multi page switching component in QT

Qt provides a special class QTabWidget for the implementation of multi page switching. It can switch the contents of different pages freely in the same window. It is a container type component that provides a friendly page switching mode. QTabWidget class provides many practical functions in engineering, For example, many functions are used in practical applications, such as setting the position of the Tab, void setTabPosition(TabPosition)(North South West East), setting the appearance of the Tab, void setTabShape(), setting the closed mode of the Tab, void setTabsClosable(). The specific functions can be queried in the Qt assistant.

Usage of QTabWidget - create QTabWidget objects in the application in Qt and add other QWidget objects to the object (adding a component to the QTabWidget object will generate a new page, and the QTabWidget object can only add one QWidget object at a time), but in actual use, each page will have multiple sub components, At this time, you should create a container type component object in the project, lay out multiple sub components in the container object, and finally add the container object to QTabWidget to generate a new page

1. Be able to freely switch the contents of different pages in the same window

2. It is a container type component and provides a friendly page switching mode

Qt – multi page switching component
How to use QTabWidget
1. Create an object of QTabWidget in the application
2. Add other QWidget objects to this object

Implementation process
1. Create the component object of the container class
2. Lay out multiple sub components in the container object
3. Add the container object to the QTabWidget to generate a new page
Qt – multi page switching component
Basic usage of QTabWidget component
Qt – multi page switching component

B. Advanced usage of qtabwidget component
1. Set the position of Tab label
2. Set the appearance of Tab
3. Set the closeable mode of Tab

QTabWidget component predefined signals
void currentChange(int index) – the currently displayed page sends changes, and index is the subscript of the new page
void tabCloseRequsted(int index) – the close button on the index page is clicked to issue a close request
Code example
Widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTableWidget>

class Widget : public QWidget
{
    Q_OBJECT

    QTabWidget m_tabWidget;
protected slots:
    void onTabCurrentChanged(int index);
    void onTabCloseRequested(int index);
public:
    Widget(QWidget *parent = 0);
    ~Widget();
};

#endif // WIDGET_H

Widget.cpp

#include "Widget.h"
#include <QPlainTextEdit>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //Basic settings of QTabWidget
    m_tabWidget.setParent(this);
    m_tabWidget.move(10, 10);
    m_tabWidget.resize(200, 200);
    m_tabWidget.setTabPosition(QTabWidget::North);
    m_tabWidget.setTabShape(QTabWidget::Triangular);
    m_tabWidget.setTabsClosable(false);

    QPlainTextEdit* edit = new QPlainTextEdit(&m_tabWidget);
    edit->insertPlainText("Page 1");

    m_tabWidget.addTab(edit, "1st");

    QWidget* widget = new QWidget(&m_tabWidget);
    QVBoxLayout* layout = new QVBoxLayout();
    QLabel* lbl = new QLabel(widget);
    QPushButton* btn = new QPushButton(widget);

    lbl->setText("Page 2");
    lbl->setAlignment(Qt::AlignCenter);

    btn->setText("Page 2");

    layout->addWidget(lbl);
    layout->addWidget(btn);

    widget->setLayout(layout);

    m_tabWidget.addTab(widget, "2nd");

    m_tabWidget.setCurrentIndex(1);

    connect(&m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabCurrentChanged(int)));
    connect(&m_tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(onTabCloseRequested(int)));
}

void Widget::onTabCurrentChanged(int index)
{
    qDebug() << "Page change to: " << index;
}

void Widget::onTabCloseRequested(int index)
{
    m_tabWidget.removeTab(index);
}

Widget::~Widget()
{

}

The running results are shown in the figure

QTabWidget realizes double clicking to close the tab

Overloaded QTabWidget (because tabBar() is protected), so you can get the tag.

1 class Tab : public QTabWidget
2 {
3     Q_OBJECT
4 public:
5     Tab(QWidget *parent = 0);
6     QTabBar* GetBar();
7 protected:
8     void mousePressEvent(QMouseEvent *event);
9 };

Then, when implementing an event filter, first judge whether the event is a double-click event, and then judge whether it is a label position. If yes, delete the current tab. Because the double-click event must trigger a click, that is, the tab selects an event, there is no need to consider the index change caused by double clicking other tabs.

 1 #ifndef MYEVENTFILTER_H
 2 #define MYEVENTFILTER_H
 3 #include <QMainWindow>
 4 #include <QMouseEvent>
 5 #include "tab.h"
 6 
 7 extern int tabindex_current;
 8 extern int tabindex_old;
 9 extern Tab *tabWidget;
10 extern QPoint tableft;
11 extern int tabwidth;
12 extern int tabheight;
13 
14 //Double click to close the Tab tab
15 class myEventFilter: public QObject
16 {
17   public:
18   myEventFilter():QObject()
19   {};
20   ~myEventFilter(){};
21 
22   bool eventFilter(QObject* object,QEvent* event)
23   {
24       if (event->type()==QEvent::MouseButtonDblClick)
25       {
26           QMouseEvent *e = static_cast<QMouseEvent*>(event);
27           QPoint pos = e->pos();
28           int x1 = tableft.x();
29           int x2 = tableft.x()+tabwidth;
30           int y1 = tableft.y();
31           int y2 = tableft.y()+tabheight;
32           if (pos.x() >= x1 && pos.y() >= y1 && pos.x() <= x2 && pos.y() <= y2)
33               tabWidget->removeTab(tabindex_current);
34       }
35       return QObject::eventFilter(object,event);
36   };
37 };
38 
39 #endif // MYEVENTFILTER_H
Finally, bind to the main function main To capture all events:
1 qApp->installEventFilter(new myEventFilter());

In addition, the width information needs to be updated during tab switching (the height does not need to be updated):

1 void MainWindow::updateBar()
2 {
3     tabindex_current = tabWidget->currentIndex();
4     tabindex_old = tabindex_current;
5     QTabBar *bar = tabWidget->GetBar();
6     if (bar->size().width() > 0)
7          tabwidth = bar->size().width();
8 }

QTabWidget add close sub tag function

QTabWidget adds the function of closing sub tags. QTabWidget has a property tabsClosable. Set it to True to display the close button. By default, the close button on each tab has no response. We need to add a close response for it ourselves. The closing signal is void tabCloseRequested(int index) and the closing function is void removeTab(int index). Note that the closing tag is an ordinary public function, not a slot function, and cannot be directly connected to the signal. We need to manually define a slot function that accepts int type, and then pass the parameters to the closing function.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTabWidget>
#include <QTextEdit>
MainWindow::MainWindow(QWidget *parent) :
                    QMainWindow(parent),
                   ui(new Ui::MainWindow)
{
     ui->setupUi(this);
     connect(ui->tabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT(removeSubTab(int)));
}
  
MainWindow::~MainWindow()
{
     delete ui;
}
  
void MainWindow::removeSubTab(int index)
{
      ui->tabWidget->removeTab(index);
}
  
void MainWindow::on_pushButton_clicked()
{
      QTextEdit *edit=new QTextEdit;
      ui->tabWidget->addTab(edit,"hitemp 1");
}

Keywords: Qt UI

Added by BTalon on Tue, 04 Jan 2022 07:11:34 +0200