Solved How to set the widget has the default focus properties
-
I want to have a default focus on a widget when the program is running. For example, I joined QLineEdit_1 and QLineEdit_2. When the program is running, the default focus is always displayed in QLineEdit_1 above, how to set QLineEdit_2 to get the focus firstly?
Thanks in advance for any advice. -
Probably what you need is setFocusProxy.
If that doesn't work you can set the focus "manually" after the widget has been shown.
-
-
I have used this function. But it doesn't work.
study::study(QWidget *parent) : QMainWindow(parent) { widget = new QWidget; l1 = new QLineEdit; l2 = new QLineEdit; m1 = new QLabel(tr("Label1")); m2 = new QLabel(tr("Lable2")); lay = new QHBoxLayout(widget); lay->addWidget(m1); lay->addWidget(l1); lay->addWidget(m2); lay->addWidget(l2); lay->setSpacing(10); lay->setMargin(10); l2->setFocus(); this->setCentralWidget(widget); }
Should this function be used here?
-
@Qt_crazyer
Please try l2->setFocus(Qt::otherFocusReason); -
@Taz742
Yes, I have also tried this function, but it doesn't work. This is just a sample program, it is very simple. I do not understand why?...
-
@Qt_crazyer
An other solution is to use a singleShot timer :QTimer::singleShot(0,lineEdit,SLOT(setFocus()));
The focus will then be set once the application is free.
See solution follow the link..
-
@Qt_crazyer I am assuming l2 is a member (using "m" as prefix for members would help).
Just set the focus with a delay, in your case:
QTimer::singleShot(0, this, [this] { l2->setFocus(); });
-
@Taz742
Thank you so much. The problem has been solved. Thank you for your patient guidance. -
@vivaladav
Thank you for your reply. This method is really effective. -
@Qt_crazyer
Nope. Do not forget mark this topic as SOLVED. -
What about this ?
setTabOrder(l2,l1);
-
@mpergand
Thank you for your advice. I have tried this function. This is indeed an effective way. -
Keep in mind that setTabOrder might not be the right solution if you introduce more widgets (as in any normal working application).