Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit signal if all children widgets lose focus

Tags:

qt

I have a QStackedWidget which holds several pages full of various QLineEdit and QComboBox children. I want to emit a signal whenever the QStackedWidget no longer has any child with focus (given that a child had focus to begin with). So moving from child to child will not emit a signal, but once a widget is selected outside of the QStackedWidget, a signal is emitted. Any advice on how to implement this? I've looked at InstallEventFilter and QSignalMapper, but neither of those appear to fit my needs. Any advice would be appreciated.

like image 1000
Jmbryan10 Avatar asked Sep 11 '11 04:09

Jmbryan10


1 Answers

You can connect to the QApplication::focusChanged signal in order to evaluate the focus widgets within a corresponding slot. The clean way to do this is to derive from QStackedWidget:

class StackedFocusWidget : public QStackedWidget {

    Q_OBJECT

public:

    StackedFocusWidget(QWidget *parent = 0) : QStackedWidget(parent) {
        connect(qApp, SIGNAL(focusChanged(QWidget *, QWidget *)), this, SLOT(onFocusChanged(QWidget *, QWidget *)));
    }

private slots:

    void onFocusChanged(QWidget *old, QWidget *now) {
        bool focusOld = old != 0 && isAncestorOf(old);
        bool focusNow = now != 0 && isAncestorOf(now);
        if (!focusOld && focusNow) {
            emit gotFocus();
        } else if (focusOld && !focusNow) {
            emit lostFocus();
        }
    }

signals:

    void gotFocus();
    void lostFocus();
};

The signals StackedFocusWidget::gotFocus and StackedFocusWidget::lostFocus will be emitted whenever the stacked widget or any of its childs receives or loses focus.

like image 135
emkey08 Avatar answered Sep 22 '22 15:09

emkey08