我有一个 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/