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.
-
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.
-
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 movingsetFocus()
inside the reimplementedshowEvent
should also work (showEvent
happens, when widget is fully constructed and about to get painted on your screen)