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

Calling setFocus() in the constructor doesn't work



  • I have a widget, derived from QWidget, that has code similar to this in its constructor:

    m_someWidget->setFocus();
    

    The problem is that the widget doesn't actually get the focus. I experimented with using a timer that calls setFocus() 1 second after the constructor runs. That works. However, I'd like to be able to set the focus from the constructor, without adding another signal/slot/both to my class.



  • @LorenDB
    @Pl45m4 is correct: "focus" is only implemented when widget is shown, it doesn't have any meaning during, say, construction. showEvent() is the earliest you should set your focus.



  • @LorenDB

    I guess while constructing your widget is not ready to receive focus.

    @LorenDB said in Calling setFocus() in the constructor doesn't work:

    without adding another signal/slot

    Why?

    Also, you don't need to add a slot to your subclass, you can connect your widget, where you create it and give focus since setFocus() is already a slot.



  • @Pl45m4 said in Calling setFocus() in the constructor doesn't work:

    you can connect your widget, where you create it and give focus since setFocus() is already a slot.

    Could you elaborate on how to do that?

    I currently am using a function in the widget's parent to focus after widget construction. A diagram:

    someWidget
     |__m_someOtherWidget
             |__m_widgetToFocus
    

    m_someOtherWidget has a function to focus m_widgetToFocus. This function is called by someWidget right after m_someOtherWidget is constructed.



  • @LorenDB

    Something like

    // #### Parent widget ####
    m_widget = new MyWidget;
    
    // #### widget constructor ####
    connect(this, &MyWidget::createdSignal, this, &MyWidget::setFocus);
    
    

    Then emit this signal either in your widget's c'tor or inside its showEvent, which should work better.
    After thinking about it, just moving setFocus() inside the reimplemented showEvent should also work (showEvent happens, when widget is fully constructed and about to get painted on your screen)



  • @Pl45m4 Thanks for the advice. I may just leave my setup as-is for simplicity, but what you said makes sense.

    P.S. I like your signature!



  • @LorenDB
    @Pl45m4 is correct: "focus" is only implemented when widget is shown, it doesn't have any meaning during, say, construction. showEvent() is the earliest you should set your focus.


Log in to reply