c++ - 在 Qt 中设置 QLineEdit 焦点

标签 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();
 }

为什么line->setFocus()只有在布局小部件之后放置并且在它不起作用之前使用时才将焦点设置在线小部件@app启动上?

最佳答案

Keyboard focus与小部件 tab order 相关,并且默认的 Tab 键顺序基于小部件的构建顺序。因此,创建更多小部件会更改键盘焦点。这就是为什么你必须制作 QWidget::setFocus最后打电话。

我会考虑为您的主窗口使用 QWidget 的子类来覆盖 showEvent虚函数,然后将键盘焦点设置到 lineEdit。这将具有在显示窗口时始终给予 lineEdit 焦点的效果。

关于c++ - 在 Qt 中设置 QLineEdit 焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/526761/

相关文章:

c++ - 如何避免对大浮点或 double 值进行舍入?

c++ - 在 QtWebEngine 中捕获 JavaScript 事件

c++ - Qt 使用 isAutoRepeat() 处理 QPushButton Autorepeat() 行为

c++ - Qt:使用脚本从二进制文件运行时无法找到应用程序 pid

c++ - Qt 字符串函数之间的区别

python - 如何在左键单击时显示 QMenu

c++ - 每次将目标文件转储到其他目录时,makefile 都会重建

c++ - 使用返回另一个翻译单元中定义的占位符类型的函数

c++ - CGAL 段错误

c++ - Qt Creator(设计器): Single text line with horizontal scrollbar