QTabWidget tab context menu
Easy way, but possibly not precisely what you need:
- Connect to the 'currentChanged' signal of your QTabWidget
- In the slot which is connected to the signal, create a QMenu and populate it as needed
- Finally, in the slot which is connected to the signal, call QMenu::exec( QCursor::pos() )
This will get a function called whenever the tab is changed (not necessarily clicked) and spawn a menu at the current mouse position.
Complicated way, which exactly does what you describe:
- Call QObject::installEventFilter on your QTabWidget, so that all the events on your QTabWidget are redirected to your own object.
- In your own object, reimplement QObject::customEvent and handle all QMouseEvent events.
- Populate a QMenu as needed and call QMenu::exec at the position of the QMouseEvent you're handling.
create a QMenu:
m_menu = new QMenu;
add your actions to menu.
Create a slot to be called when context menu requested on tab bar:
connect(m_tabWidget->tabBar(), &QTabBar::tabBarClicked, this, &MyClass::on_contextMenuRequested);
In the slot, show the menu. Definition of slot:
void MyClass::on_contextMenuRequested(int tabIndex)
{
m_menu->popup(QCursor::pos());
}
If you need index of current tab in another function, use following:
m_tabWidget->tabBar()->currentIndex()