Reputation: 9727
I am developing a simple text editor which has mutlitabs. I want to implement a rightclick menu to rename clicked (not current) tab of a QTabWidget instance. To do this I have to find the index of clicked tab. How can I do this?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyApplication(...):
...
def contextMenuEvent(self, event):
tabIndex = ... # <- what should I type here?
menu = QMenu(self)
renameAction = menu.addAction("Rename")
action = menu.exec_(self.mapToGlobal(event.pos()))
if action == renameAction:
self.renameTabSlot(tabIndex)
def renameTabSlot(self, tabIndex):
...
Upvotes: 1
Views: 1973
Reputation: 1319
You can add context menus to the QTabBar widgets through code such as:
for i,tabbar in enumerate(bars):
tabbar.setContextMenuPolicy(Qt.ActionsContextMenu)
renameAction = QtGui.QAction("Rename",tabbar)
renameAction.triggered.connect(lambda x: self.renameTabSlot(i))
tabbar.addAction(renameAction)
The trick here is that you define a lambda for each tabbar based on its index such that the index will be passed to the rename function. See this page for more info on handling context menus.
Upvotes: 1
Reputation: 1211
You will probably need to check to clicked position (i.e. event.pos ()
) against the tab regions manually. My python is a bit rusty, so here's some C++ code instead. Assuming your tabwidget is called myTabWidget
:
int tabIndex = -1;
{
QTabBar* tabBar = myTabWidget->tabBar ();
QPoint globalPos = this ->mapToGlobal (event->pos ());
QPoint posInTabBar = tabBar->mapFromGlobal (globalPos);
for (int i=0; i<tabBar->count (); ++i)
{
if (tabBar->tabRect (i).contains (posInTabBar))
{
tabIndex = i;
break;
}
}
}
if (tabIndex < 0)
{
// No tab hit...
return;
}
I didn't compile&run this, but the idea should be clear. Note the mapToGlobal
and mapFromGlobal
calls to transform the given event's position into the tab-bars native coordinates. I hope I did it right.
Upvotes: 2