Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Discover certain QWidget gained focus in QTabWidget



  • Hi

    I am working on simple application with a few tabs, each containing another feature and I added a few QWidget based objects to QTabWidget, I want to discover that focus was gained or lost in certain tab. I wish class QWidget have a signal like focusChanged(bool isFocused) and I could very simply implement certain actions on focus gained/lost inside those QWidget based classes, but there is no such a signal so I made an workaround: each tab has its own tab number passed in constructor and QTabWidget::currentChanged is connected to a slot which checks if currently chosen tab number is equal to its own tab number. It works, but I would love to get rid of it since I have other bloat code to take care of. Are there more elegant ways to catch that focus was gained?

    int tabNumber = 1;
    	
    someFencyTab = new SomeFencyTab(tabNumber++, &someNiceObject, this);
    this->tabWidget->addTab(someFencyTab, "Fency Tab");
    connect(tabWidget, &QTabWidget::currentChanged, someFencyTab, &SomeFencyTab::tabChanged);
    
    void SomeFencyTab::tabChanged(int tab_number)
    {
        bool const now_focused = tab_number == own_tab_number_;
    
        if (now_focused) {
            onFocusGained();
            prev_focused_ = true;
        }
        else if ((!now_focused) && prev_focused_) {
            onFocusLost();
            prev_focused_ = false;
        }
    }
    

    Reimplementing focusInEvent does not work, I tried following

    class SomeFancyTab : public QWidget
    {
    /* ... */
      protected:
        void focusInEvent(QFocusEvent* e);
    }
    
    void SomeFancyTab::focusInEvent(QFocusEvent* e)
    {
        qDebug() << "Focus gained";
    }
    

    Best regards



  • @RotflCopter said in Discover certain QWidget gained focus in QTabWidget:

    I wish class QWidget have a signal like focusChanged(bool isFocused) and I could very simply implement certain actions on focus gained/lost inside those QWidget

    What about QApplication::focusWidget?

    A QWidget is still a QWidget even when it's part of a tab.



  • Hi

    As usual, after posting topic I found solution:
    -reimplementing QObject general event handler to see what kinds of event comes when certain action happens (switching to tab)

    bool event(QEvent *event);
    

    -reimplementing specific handlers - in my case:

    void hideEvent(QHideEvent *event);
    void showEvent(QShowEvent *event);
    

    Best regards
    Hope this topic will help someone in future


Log in to reply