Reputation: 731
I need to display a context menu whenever a tab is clicked on and it needs to react to that specific tab. Is there any way to do this without subclassing it?
Upvotes: 10
Views: 6378
Reputation: 303
As per the comment by @Petrzio Berkerle, the solution found at https://www.qtcentre.org/threads/16703-QTabBar-Context-menu-on-tab?p=84057#post84057 worked very well for me. (Actually, it was the only one that worked at all.)
The code from the post there (by "spirit"):
...
m_tabBar = new QTabBar();
m_tabBar->addTab(tr("OK"));
m_tabBar->addTab(tr("NO"));
m_tabBar->addTab(tr("IGNORE"));
m_tabBar->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_tabBar, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(showContextMenu(const QPoint &)));
...
void Test::showContextMenu(const QPoint &point)
{
if (point.isNull())
return;
int tabIndex = m_tabBar->tabAt(point);
QMenu menu(this);
if (!tabIndex)
menu.addAction(tr("OK"));
else if (tabIndex == 1)
menu.addAction(tr("NO"));
else if (tabIndex == 2)
menu.addAction(tr("IGNORE"));
menu.exec(m_tabBar->mapToGlobal(point));
}
Upvotes: 2
Reputation: 261
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()
Upvotes: 3
Reputation: 94289
Easy way, but possibly not precisely what you need:
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:
Upvotes: 5
Reputation: 14416
I think you need to create your own class that inherits from QTabWidget and override the MousePressEvent(QMouseEvent) protected function in which you can create your context menu on right click.
Upvotes: 0