After calling setFocus, can I restore focus to its previous holder without explicitly knowing which widget it was?



  • clearFocus on the widget that was activated by setFocus just removes focus altogether. How can I transfer focus back to the widget that had it last?



  • You can call "QWidget * QApplication::focusWidget() [static]":http://qt-project.org/doc/qt-5/qapplication.html#focusWidget before calling setFocus to get the widget with the focus (or 0 if none has it)
    Or you can connect to "void QApplication::focusChanged(QWidget * old, QWidget * now) [signal]":http://qt-project.org/doc/qt-5/qapplication.html#focusChanged to get the widget that had focus before.



  • You can use focusNextPrevChild()

    Below a snippet may help you:
    [code]MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    QList<QWidget *> lines = ui->centralWidget->findChildren<QWidget *>();
    foreach (QWidget *widget, lines) {
    widget->installEventFilter(this);
    }
    }

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
    if(event->type() == QEvent::KeyPress) {
    QKeyEvent *key = static_cast<QKeyEvent *>(event);

        if((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return)) {
            this->focusNextPrevChild(false);
        } else {
            return QObject::eventFilter(obj, event);
        }
        return true;
    } else {
        return QObject::eventFilter(obj, event);
    }
    return false;
    

    }[/code]


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.