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

spr*_*aff 6 qt

我正在打开一个包含 QLineEdit 的 QDialog。我希望 QLineEdit 最初具有键盘焦点,闪烁的光标作为视觉提示。很简单吧?

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

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

  • 闪烁的插入符号不会移动到 line_edit
  • 如果我点击不同的 QLineEdit,闪烁的插入符号会出现那里,但按键仍会传送到line_edit

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

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

Ale*_*r V 2

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

来自对此线程的回复之一:Set QLineEdit focus in Qt

QTimer::singleShot(0, line_edit, SLOT(setFocus()));
Run Code Online (Sandbox Code Playgroud)

在我找到这种优雅的集中注意力方式之前,我开发了自己的方式:

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);
}
Run Code Online (Sandbox Code Playgroud)