qt移动焦点,在Qt中设置QLineEdit焦点

本文讨论了如何在Qt应用启动时确保QLineEdit获得焦点,解释了布局顺序对键盘焦点的影响,并提供了通过子类化QWidget解决方法。关键在于理解焦点与控件tab顺序的关系及如何正确设置焦点调用时机。
摘要由CSDN通过智能技术生成

I am having a qt question. I want the QLineEdit widget to have the focus at application startup. Take the following code for example:

#include

#include

#include

#include

#include

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();

}

Why does line->setFocus() sets the focus on the line widget @app startup only if it is placed after laying out the widgets and if used before it's not working?

解决方案

Keyboard focus is related to widget tab order, and the default tab order is based on the order in which widgets are constructed. Therefore, creating more widgets changes the keyboard focus. That is why you must make the QWidget::setFocus call last.

I would consider using a sub-class of QWidget for your main window that overrides the showEvent virtual function and then sets keyboard focus to the line edit. This will have the effect of always giving the line edit focus when the window is shown.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值