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

Focus transmission rejecting



  • I would like to reject the focus transfer from one widget to another input widget when the data is invalid.
    I tried to process focusOutEvent, but at the same time I can "return" the focus, but not prohibit its transmission.

    I am using qt 4.8.6.

    Is it possible?

    Thanks.


  • Lifetime Qt Champion

    Hi,

    Wouldn't it be simpler to disable whatever cannot be accessed while the prior data are invalid ?



  • I solved the problem by processing the KeyPressEvent for Key_Tab and Key_BackTab in the event filter and overriding the focusNextPrevChild method of the parent widget.

    bool EditorGroup::eventFilter(QObject * obj, QEvent * event )
    {
        ReportableBase * editor = dynamic_cast<ReportableBase *>(obj);
        if ( event->type() == QEvent::KeyPress )
        {
            QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
            if( editor )
            {
                if( keyEvent->key() == Qt::Key_Return ||
                        keyEvent->key() == Qt::Key_Tab )
                {
                    focusNextChild();
                    return true;
                }
                else if ( keyEvent->key() == Qt::Key_Backtab )
                {
                    focusPrev();
                }
            }
        }
        else if ( event->type() == QEvent::FocusIn )
        {
            if(editor)
            {
                focusWgt = editor->toWidget();
            }
        }
        return false;
    }
    
    bool EditorGroup::focusNextPrevChild( bool next )
    {
        ReportableBase * editor = dynamic_cast<ReportableBase *>( focusWgt );
        if(editor)
        {
            QString message;
            if(editor->isDataValid(message))
            {
                ReportableBase * nextEditor = 0;
                while (nextEditor == 0)
                {
                    focusWgt = next ?
                                focusWgt->nextInFocusChain() :
                                focusWgt->previousInFocusChain();
                    nextEditor = dynamic_cast<ReportableBase *>(focusWgt);
                }
                focusWgt->setFocus( next ?
                                        Qt::TabFocusReason :
                                        Qt::BacktabFocusReason );
                return true;
            }
            else
            {
                editor->report_warning(message);
            }
        }
        return false;
    }
    

Log in to reply