Set QLineEdit focus in Qt

I am having a qt question. I want the QLineEdit widget to have the focus at application startup. Take the following code for example:

#include <QtGui/QApplication>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLineEdit>
#include <QtGui/QFont>

 int main(int argc, char *argv[])
     QApplication app(argc, argv);

     QWidget *window = new QWidget();

     QHBoxLayout *layout = new QHBoxLayout(window);

     // Add some widgets.
     QLineEdit *line = new QLineEdit();

     QPushButton *hello = new QPushButton(window);
     hello->setText("Select all");
     hello->resize(150, 25);
     hello->setFont(QFont("Droid Sans Mono", 12, QFont::Normal));

     // Add the widgets to the layout.


     QObject::connect(hello, SIGNAL(clicked()), line, SLOT(selectAll()));
     QObject::connect(line, SIGNAL(returnPressed()), line, SLOT(selectAll()));

     return app.exec();

Why does line->setFocus() sets the focus on the line widget @app startup only if it is placed after laying out the widgets and if used before it's not working?


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 line edit. This will have the effect of always giving the line edit focus when the window is shown.

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.

In Qt setFocus() is a slot, you can try other overloaded method which takes a Qt::FocusReason parameter like the line shown below:


You can read about focus reason options in the following link:

Need Your Help

Form login button enabled after password field has focus

javascript jquery html css css3

hello guys I have a login page with two inputs username and password and one button. I want to put a class on that button after password field has first character filled in. How can I do that , Tha...

Access violation writing location when deleting a matrix

c++ memory memory-management memory-leaks

I am writing a program to perform a set of numeric methods. To do this I need to create matrices of arbitrary size and throw them between functions. Obviously if I don't clean up the creates matrices

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.