在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)
{
//将事件转化为键盘事件 QKeyEvent *key_event = static_cast(event);
//按下Tab键执行焦点切换事件
if(key_event->key() == Qt::Key_Tab)
{
bool realm_edit_focus = realm_line_edit->hasFocus();
bool user_edit_focus = user_line_edit->hasFocus();
bool password_edit_focus = password_line_edit->hasFocus();
bool check_box_focus = check_box->hasFocus();
bool login_btn_focus = login_button->hasFocus();
bool get_pwd_btn_focus = forgot_pwd_button->hasFocus();
bool register_btn_focus = regist_button->hasFocus();
bool min_btn_focus = min_button->hasFocus();
bool close_btn_focus = close_button->hasFocus();
if(realm_edit_focus)
{
focusNextChild();
user_line_edit->setFocus();
}
else if
(user_edit_focus)
{
focusNextChild();
password_line_edit->setFocus();
}
else if(password_edit_focus)
{
focusNextChild();
check_box->setFocus();
}
else if(check_box_focus)
{
focusNextChild();
login_button->setFocus();
}
else if(login_btn_focus)
{
focusNextChild();
forgot_pwd_button->setFocus();
}
else if(get_pwd_btn_focus)
{
focusNextChild();
regist_button->setFocus();
}
else if(register_btn_focus)
{
focusNextChild();
min_button->setFocus();
}
else if(min_btn_focus)
{
focusNextChild();
close_button->setFocus();
}
else if(close_btn_focus)
{
focusNextChild();
realm_line_edit->setFocus();
}
else
{
focusNextChild();
}
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
在这里需要注意focusNextChild()把焦点传递到序列下一个窗口部件,这句话必须写上!然后就可以实现Tab键进行光标的自由切换了!
这里我主要是实现焦点的切换,如果要实现其他功能则直接修改Tab键中代码即可
注:
技术在于交流、沟通,转载请注明出处并保持作品的完整性。
作者:╰☆奋斗ing?孩子` 原文:http://blog.sina.com.cn/s/blog_a6fb6cc90101ayuo.html。