关于c ++:在Qt中设置QLineEdit焦点

Set QLineEdit focus in Qt

我有一个qt问题。 我希望QLineEdit小部件专注于应用程序启动。 以以下代码为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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();
 }

为什么line->setFocus()仅在将其放置在布局窗口小部件之后并且在其无法工作之前使用时,才将焦点放在行窗口小部件@app启动上?


另一个可行的技巧是使用singleshot计时器:

1
QTimer::singleShot(0, line, SLOT(setFocus()));

实际上,这在事件系统"自由"执行后即在小部件完全构造后的某个时间立即调用QLineEdit实例的setFocus()插槽。


键盘焦点与窗口小部件的选项卡顺序有关,默认选项卡的顺序基于窗口小部件的构造顺序。因此,创建更多的小部件会更改键盘焦点。这就是为什么必须最后进行QWidget::setFocus调用的原因。

我会考虑为您的主窗口使用QWidget的子类,该子类将覆盖showEvent虚拟功能,然后将键盘焦点设置为lineEdit。当显示窗口时,这将具有始终给予lineEdit焦点的效果。


也许这是最新的更新,因为最后一个答案是在2012年,OP上一次在2014年编辑了该问题。他们让我起作用的方法是更改??政策,然后确定重点。

1
2
line->setFocusPolicy(Qt::StrongFocus);
line->setFocus();

在Qt setFocus()是一个插槽中,您可以尝试其他采用Qt :: FocusReason参数的重载方法,如下所示:

1
line->setFocus(Qt::OtherFocusReason);

您可以在以下链接中了解焦点原因选项:

http://doc.trolltech.com/4.4/qt.html#FocusReason-enum