Set QLineEdit focus in Qt
Another trick that might work is by using the singleshot
timer:
QTimer::singleShot(0, line, SLOT(setFocus()));
Effectively, this invokes the setFocus()
slot of the QLineEdit
instance right after the event system is "free" to do so, i.e. sometime after the widget is completely constructed.
Keyboard focus is related to widget tab order, and the default tab order is based on the order in which widgets are constructed. Therefore, creating more widgets changes the keyboard focus. That is why you must make the QWidget::setFocus
call last.
I would consider using a sub-class of QWidget
for your main window that overrides the showEvent
virtual function and then sets keyboard focus to the lineEdit
. This will have the effect of always giving the lineEdit
focus when the window is shown.
In Qt setFocus() is a slot, you can try other overloaded method which takes a Qt::FocusReason parameter like the line shown below:
line->setFocus(Qt::OtherFocusReason);
You can read about focus reason options in the following link:
http://doc.trolltech.com/4.4/qt.html#FocusReason-enum
Perhaps this is an update as the last answer was in 2012 and the OP last edited the question in 2014. They way I got this to work was to change the policy and then set the focus.
line->setFocusPolicy(Qt::StrongFocus);
line->setFocus();