Search code examples
c++qtqt4qtabwidget

QTabWidget tab context menu


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?


Solution

  • Easy way, but possibly not precisely what you need:

    1. Connect to the 'currentChanged' signal of your QTabWidget
    2. In the slot which is connected to the signal, create a QMenu and populate it as needed
    3. 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:

    1. Call QObject::installEventFilter on your QTabWidget, so that all the events on your QTabWidget are redirected to your own object.
    2. In your own object, reimplement QObject::customEvent and handle all QMouseEvent events.
    3. Populate a QMenu as needed and call QMenu::exec at the position of the QMouseEvent you're handling.