QTabWidget: close tab button not working
Asked Answered
A

4

19

I have set ui->tabWidget->setTabsClosable(true); but QTabwidget only showing a cross on each tab that is not closing tab on click on this button. What else I have to do to make tabs closable? I tried to connect any slot (which would be proper for this work) of close to signal tabCloseRequested(int) but couldn't find any such slot in tabwidget. Please suggest the right way.

Airspace answered 3/10, 2013 at 5:4 Comment(0)
U
29

Create a slot e.g. closeMyTab(int) and connect the tab widget's tabCloseRequested(int) signal to this slot. In this slot call tab widget's removeTab method with the index received from the signal.

See this answer for more details.

Undulate answered 3/10, 2013 at 5:29 Comment(0)
R
9

For future stumblers upon this question looking for a PyQt5 solution, this can be condensed into a 1-liner:

tabs = QTabWidget()
tabs.tabCloseRequested.connect(lambda index: tabs.removeTab(index))

The tabCloseRequested signal emits an integer equal to the index of the tab that emitted it, so you can just connect it to a lambda function that takes the index as its argument.

The only problem I could see with this is that connecting a lambda function to the slot prevents the object from getting garbage collected when the tab is deleted (see here).

EDIT (9/7/21): The lambda function isn't actually necessary since QTabWidget.removeTab takes an integer index as its sole argument by default, so the following will suffice (and avoids the garbage-collection issue):

tabs.tabCloseRequested.connect(tabs.removeTab)
Ramshackle answered 18/2, 2020 at 0:38 Comment(0)
D
7

The best way to do it since we got new connection syntax (Qt 5) is:

QTabWidget* tabWidet = new QTabWidget();
connect(tabWidget->tabBar(), &QTabBar::tabCloseRequested, tabWidget->tabBar(), &QTabBar::removeTab);
Dingus answered 20/8, 2020 at 12:39 Comment(1)
Worked very well on Qt5 indeed. Recommending this solution.Rookie
R
5

You just need to tell the tabWidget itself to close the requested tab index (the param passed to the slot) as this:

ui->tabWidget->removeTab(index);
Rerun answered 17/4, 2015 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.