【问题标题】:How can I move the keyboard cursor/focus to a QLineEdit?如何将键盘光标/焦点移动到 QLineEdit?
【发布时间】:2016-06-16 05:29:33
【问题描述】:

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

调用line_edit->setFocus() 无效。

调用line_edit->grabKeyboard() 使其输入焦点但是

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

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

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

【问题讨论】:

  • 显示对话框后,哪个小部件获得焦点?您可以通过 GammaRay / QApplication 进行检查。

标签: qt


【解决方案1】:

如何将键盘输入光标设置为 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);
}

【讨论】:

  • 这行得通,尽管您的链接中引用的原因令人怀疑:“键盘焦点与小部件选项卡顺序有关,默认选项卡顺序基于小部件的构建顺序。因此,创建更多小部件会改变键盘焦点。这就是为什么您必须最后调用 QWidget::setFocus。" -- 我在构造结束时调用 setFocus (),在所有小部件都已创建并添加。其他事情正在发生。
  • 正确,这就是人们编写的stackoverflow页面的数量。一切都需要在实践中得到证明,许多不准确的陈述。
【解决方案2】:

接受的答案对我不起作用。 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2015-07-24
    • 2015-12-30
    相关资源
    最近更新 更多