Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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)

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);

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top