如何将键盘光标/焦点移动到QLineEdit?

问题描述:

我打开一个包含QLineEdit的QDialog。我希望QLineEdit最初具有键盘焦点,闪烁的光标作为视觉提示。很简单,对吧?如何将键盘光标/焦点移动到QLineEdit?

调用line_edit->setFocus()没有效果。

调用line_edit->grabKeyboard()给它输入焦点,但

  • 闪烁的插入符号不会移动到line_edit
  • 如果我点击进入一个不同的QLineEdit的,闪烁的插入符号去但按键仍然传递到line_edit

如果我没有做,我必须点击进入line_edit来获取插入符和输入焦点。查看QLineEdit::mousePressEvent的源代码,似乎关键功能是QWidgetLineControl::moveCursor,但是无法通过公共API进行访问,并且进一步查看源代码并不显示任何有希望的内容。

那么,我该如何移动该死的键盘输入光标?

+0

后显示对话框,该控件获得焦点?你可以用GammaRay /'QApplication'来检查。 – peppe

如何将键盘输入光标设置为QLineEdit控件?

来自对此主题的回复之一:Set QLineEdit focus in Qt

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

之前,我发现,优雅的方式来设置焦点我开发我自己的:

void forceFocus(QWidget* widget) 
{ 
    // unless set active, no stable set focus here 
    widget->activateWindow(); 
    // the event object is released then in event loop (?) 
    QFocusEvent* eventFocus = new QFocusEvent(QEvent::FocusIn); 
    // posting event for forcing the focus with low priority 
    qApp->postEvent(widget, (QEvent *)eventFocus, Qt::LowEventPriority); 
} 
+0

虽然在你的链接中引用的原因是可疑的,但它仍然有效:*“键盘焦点与小部件标签顺序有关,默认的标签顺序基于小部件的构建顺序,因此创建更多小部件会改变键盘焦点。这就是为什么你必须最后调用QWidget :: setFocus。“* - 在构建完所有小部件之后,我在调用setFocus()方法。其他事情正在发生。 – spraff

+0

正确,那就是人们写了多少个计算器页面。一切都需要在实践中得到证实,如此多的不准确的陈述。 – AlexanderVX

接受的答案并没有为我工作。 qApp->focusWidget()已正确更新,但插入符号未显示。我在grabKeyboard()setReadOnly()setCursorPosition(),activateWindow(),cursorBackward(),cursorForward(),cursorFlashTime()等等事物上尝试了很多变化,但都无济于事。他们透露光标位于正确的位置,只是没有被绘制。

不知道我的情况如何与OP不同。就像在Activate cursor in QTextEdit中,在回应另一个按钮按下之后,我打电话给setFocus(),但除此之外非常标准。

最后,使用线索在OP,这个大锤做法让我有:

QPoint pos(line_edit->width()-5, 5); 
QMouseEvent e(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, 0); 
qApp->sendEvent(line_edit, &e); 
QMouseEvent f(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, 0); 
qApp->sendEvent(line_edit, &f);