将QLineEdit焦点设置在Qt中

hyp*_*ean 21 c++ qt qlineedit

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

为什么line->setFocus()只在布局窗口小部件之后放置它并且如果在它不工作之前使用它时,将焦点放在行窗口小部件@app启动上?

Ari*_*yat 25

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

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

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


Jud*_*den 24

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

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

  • 小修正:Tab键顺序不是子构造_constructed_的顺序,而是它们_added_到父级的顺序. (2认同)