Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTabWidget: close tab button not working

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.

like image 314
Tab Avatar asked Oct 03 '13 05:10

Tab


4 Answers

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.

like image 135
Pavel Strakhov Avatar answered Nov 10 '22 02:11

Pavel Strakhov


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);
like image 39
f10w Avatar answered Nov 10 '22 04:11

f10w


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)
like image 8
Elliot Young Avatar answered Nov 10 '22 03:11

Elliot Young


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);
like image 4
Leonel Salazar Videaux Avatar answered Nov 10 '22 03:11

Leonel Salazar Videaux