在Qt中,有一些特殊的按键比如说Tab键,默认Tab事件(切换焦点)被先捕获了,所以如果想自定义Tab键的使用应该如何实现呢? 在实际需求中我主要是实现QLineEdit、QCheckBox、QPushButton、QToolButton之间的切换,可以根据自己的程序修改切换顺序。当然如果自己不去实现Tab键的功能,就像前面所言,Qt也会去捕获Tab键切换焦点,只不过顺序是死的!那么要想灵活的切换应该怎么实现呢?
1、安装事件过滤器
realm_line_edit->installEventFilter(this);
user_line_edit->installEventFilter(this);
password_line_edit->installEventFilter(this);
check_box->installEventFilter(this);
login_button->installEventFilter(this);
forgot_pwd_button->installEventFilter(this);
regist_button->installEventFilter(this);
min_button->installEventFilter(this);
close_button->installEventFilter(this);
2、重写eventFilter(QObject *obj, QEvent *event)
bool LoginDialog::eventFilter(QObject *obj, QEvent event)
{
if(obj == realm_line_edit || obj ==user_line_edit || obj == password_line_edit || obj == check_box||
obj == login_button || obj ==forgot_pwd_button || obj == regist_button || obj == min_button ||obj == close_button)
{
if(event->type() ==QEvent::KeyPress)
{
//将事件转化为键盘事件
QKeyEventkey_event = static_cast(event);
//按下Tab键执行焦点切换事件
if(key_event->key()== Qt::Key_Tab)
{
boolrealm_edit_focus = realm_line_edit->hasFocus();
booluser_edit_focus = user_line_edit->hasFocus();
boolpassword_edit_focus = password_line_edit->hasFocus();
boolcheck_box_focus = check_box->hasFocus();
boollogin_btn_focus = login_button->hasFocus();
boolget_pwd_btn_focus = forgot_pwd_button->hasFocus();
boolregister_btn_focus = regist_button->hasFocus();
boolmin_btn_focus = min_button->hasFocus();
boolclose_btn_focus = close_button->hasFocus();
if(realm_edit_focus)
{
focusNextChild();
user_line_edit->setFocus();
}
elseif(user_edit_focus)
{
focusNextChild();
password_line_edit->setFocus();
}
elseif(password_edit_focus)
{
focusNextChild();
check_box->setFocus();
}
elseif(check_box_focus)
{
focusNextChild();
login_button->setFocus();
}
elseif(login_btn_focus)
{
focusNextChild();
forgot_pwd_button->setFocus();
}
elseif(get_pwd_btn_focus)
{
focusNextChild();
regist_button->setFocus();
}
elseif(register_btn_focus)
{
focusNextChild();
min_button->setFocus();
}
elseif(min_btn_focus)
{
focusNextChild();
close_button->setFocus();
}
elseif(close_btn_focus)
{
focusNextChild();
realm_line_edit->setFocus();
}
else
{
focusNextChild();
}
returntrue;
}
}
}
return QDialog::eventFilter(obj, event);
}
在这里需要注意focusNextChild()把焦点传递到序列下一个窗口部件,这句话必须写上!然后就可以实现Tab键进行光标的自由切换了!
这里我主要是实现焦点的切换,如果要实现其他功能则直接修改Tab键中代码即可.
转:http://blog.sina.com.cn/s/blog_a6fb6cc90101ayuo.html
想问下如果再QWizard中如何设置焦点?