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.
def simulateDockTabClick(window, tabText):
Simulates a left mouse click event on a dock widget tab with the given
text. A possible use for this function is to recreate the effect of
collapsing a tabbed dock area as Qt doesn't expose a method to get this
:param window: The QMainWindow widget to use
:type window: QtGui.QMainWindow
:param tabText: the text in the tab to "click" on
:type tabText: str
:returns: True if dock tab was found and event was sent, else False if
no tab was found with the text.
assert isinstance(window, QtGui.QMainWindow), \
'Widget is not a QMainWindow instance'
for child in window.children():
if isinstance(child, QtGui.QTabBar):
for i in range(child.count()):
if child.tabText(i) == tabText:
tabPosition = child.tabRect(i).center()
event = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress,