Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set QLineEdit focus in Qt

Tags:

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();      window->setWindowIcon(QIcon("qtest16.ico"));      window->setWindowTitle("QtTest");       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.      layout->addWidget(line);      layout->addWidget(hello);       line->setFocus();       QObject::connect(hello, SIGNAL(clicked()), line, SLOT(selectAll()));      QObject::connect(line, SIGNAL(returnPressed()), line, SLOT(selectAll()));       window->show();      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?

like image 758
hyperboreean Avatar asked Feb 09 '09 00:02

hyperboreean


2 Answers

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.

like image 123
Judge Maygarden Avatar answered Oct 13 '22 01:10

Judge Maygarden


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.

like image 44
Ariya Hidayat Avatar answered Oct 13 '22 02:10

Ariya Hidayat