将QLineEdit焦点设置在Qt中

问题描述 投票:19回答:4

我有一个qt问题。我希望QLineEdit小部件在应用程序启动时具有焦点。以下面的代码为例:

#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启动上,只有在布局小部件之后放置它并且如果在它不工作之前使用它?

c++ qt qlineedit
4个回答
24
投票

Keyboard focus与小部件tab order相关,默认的Tab顺序基于小部件的构造顺序。因此,创建更多小部件会更改键盘焦点。这就是为什么你必须让QWidget::setFocus呼叫最后。

我会考虑在你的主窗口中使用QWidget的子类来覆盖showEvent虚函数,然后将键盘焦点设置为lineEdit。这将产生在显示窗口时始终给予lineEdit焦点的效果。


24
投票

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

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

实际上,这在事件系统“自由”之后立即调用setFocus()实例的QLineEdit槽,即在完全构造窗口小部件之后的某个时间。


3
投票

也许这是一个更新,因为最后一个答案是在2012年,OP最后在2014年编辑了这个问题。我这样做的方式是改变策略然后设置焦点。

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

1
投票

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

line->setFocus(Qt::OtherFocusReason);

您可以在以下链接中阅读有关焦点原因选项的信息:

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

© www.soinside.com 2019 - 2024. All rights reserved.