Code Snippet: Qt Dockwidget Tab Click Simulation

If you have used dock widgets in Qt, you may have docked with with tabs for easy stacking of other dock widgets. One handy feature of the tabs is when you click on the active tab, it will collapse the dock area and clicking a tab will expand it again. One thing however that is missing in Qt is a way to trigger this behavior yourself. If you simply hide the dock widget, the tab will disappear so that is no use. There is no slot or function to control the action. After lots of investigating I came to the conclusion that there is some custom Qt event handling specifically for mouse button clicks on a dock widget tab.  Triggering this event causes some way to hide the dock but keep the tabs using some other special method. The Qt source code doesn’t expose this either so there is no way to find what is happening and recreate it yourself.

But I didn’t give up, I wanted my tabbed dock widgets to be collapsed upon opening the UI to keep tools that are not needing to be seen from distracting the user. So how can I trigger this behavior programmatically? Well, I simulate a mouse button click event on the tab so I trick Qt on thinking the user did click on the tab! By creating my own QMouseEvent, I send the event to the tab bar with the position of where the “click” happened and let the tab bar handle what it does, which is collapse/expand the dock widget. Simple!

Below is the code snippet I created to reproduce a mouse button press event over the tab that has the same text. Simply pass it a QMainWindow instance and the text on the tab you want to “click” on.  The return will be True if the tab was found and event was sent otherwise False. Now you can too programmatically trigger this feature which should have been included in the first place. By the way, this is for Qt 4.8, maybe future versions will support this.


About the author: Scott

2 comments to “Code Snippet: Qt Dockwidget Tab Click Simulation”

You can leave a reply or Trackback this post.
  1. Daniel Vogelbacher - Dec 11, 2016 Reply

    I use tabbed dock widgets, but clicking on a tab will not collapse/expand as you explained. The dock is just always visible (Qt 5.4). Can you post a hint how to get the behavior you have described?

    • Scott - Dec 11, 2016 Reply

      I have not tried this yet in Qt 5. Since Maya 2017 made the switch to this version, I will have to try it update this code if something has changed. Thanks for letting me know so I can take a look!

Leave a Reply to Daniel Vogelbacher Cancel reply

Your email address will not be published.Email address is required.