我有一个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启动上,只有在布局小部件之后放置它并且如果在它不工作之前使用它?
Keyboard focus与小部件tab order相关,默认的Tab顺序基于小部件的构造顺序。因此,创建更多小部件会更改键盘焦点。这就是为什么你必须让QWidget::setFocus
呼叫最后。
我会考虑在你的主窗口中使用QWidget
的子类来覆盖showEvent
虚函数,然后将键盘焦点设置为lineEdit
。这将产生在显示窗口时始终给予lineEdit
焦点的效果。
可能有用的另一个技巧是使用singleshot
计时器:
QTimer::singleShot(0, line, SLOT(setFocus()));
实际上,这在事件系统“自由”之后立即调用setFocus()
实例的QLineEdit
槽,即在完全构造窗口小部件之后的某个时间。
也许这是一个更新,因为最后一个答案是在2012年,OP最后在2014年编辑了这个问题。我这样做的方式是改变策略然后设置焦点。
line->setFocusPolicy(Qt::StrongFocus);
line->setFocus();
在Qt中,setFocus()是一个插槽,您可以尝试其他重载方法,该方法采用Qt :: FocusReason参数,如下所示:
line->setFocus(Qt::OtherFocusReason);
您可以在以下链接中阅读有关焦点原因选项的信息: