Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. After calling setFocus, can I restore focus to its previous holder without explicitly knowing which widget it was?

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

Scheduled Pinned Locked Moved General and Desktop
3 Posts 3 Posters 2.5k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • V Offline
    V Offline
    Violet Giraffe
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • A Offline
      A Offline
      andreyc
      wrote on last edited by
      #2

      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.

      1 Reply Last reply
      0
      • M Offline
        M Offline
        mbnoimi
        wrote on last edited by
        #3

        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]

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved