首页 文章

将QLineEdit焦点设置在Qt中

提问于
浏览
17

我有一个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启动上?

4 回答

  • 23

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

    我会考虑在你的主窗口中使用一个QWidget子类来覆盖showEvent虚函数,然后将键盘焦点设置为行编辑 . 这将具有在显示窗口时始终给出线编辑焦点的效果 .

  • 1

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

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

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

  • 1

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

    line->setFocus(Qt::OtherFocusReason);
    

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

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

  • 23

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

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

相关问题