If your widget could focus and “steal” the focus on some other widgets, it would be easier. Something like this might work:
class ToolBarWidget : public QWidget { Q_OBJECT public: explicit ToolBarWidget(QWidget * parent = 0) { setFocusPolicy(Qt::ClickFocus); } protected: void focusOutEvent(QFocusEvent * event) { close(); } }
And when creating any of your widgets, you would do:
ToolBarWidget * pWidget = new ToolBarWidget(this); pWidget->show(); pWidget->setFocus();
Done! Well, I think, not quiet. Firstly, you do not want the ToolBarWidget to get any focus in the first place. And secondly, you want the user to be able to click anywhere and ToolBarWidget to be hidden. This way you can track every created ToolBarWidget. For example, in the member variable QList ttWidgets. Then, whenever you create a new ToolBarWidget, you must do this:
ToolBarWidget * pWidget = new ToolBarWidget(this); pWidget->installEventFilter(this); pWidget->show();
and in your main widget class, implement the eventFilter () function. Something like:
bool MainWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::FocusOut || event->type() == QEvent::KeyPress || event->type() == QEvent::MouseButtonPress) { while (!ttWidgets.isEmpty()) { ToolBarWidget * p = ttWidgets->takeFirst(); p->close(); p->deleteLater(); } } return MainWidget::eventFilter(obj, event); }
And it will work. Because this way, even if your ToolTabWidgets do not get focus, some other widgets in your main widget have focus. And as soon as this changes (whether the user is called from your window or on another control inside it, or in this case a key or mouse button is pressed, the control will reach this eventFilter () function and close all your tab widgets.
BTW to capture MouseButtonPress, KeyPress, etc. from other widgets, you need to either install InstallEventFilter on them, or simply override the QWidget :: event (QEvent *) function in the main widgets and look for those events there.