Qt的窗口部件按用户的习惯来处理键盘焦点。也就是说,其出发点是用户的焦点能定向到任何一个窗口,或者窗口中任何一个部件。css
焦点获取方式比较多,例如:鼠标点击、Tab键切换、快捷键、鼠标滚轮等。markdown
习惯性的,咱们常常会使用Tab键来控制焦点顺序,好比:用户注册时,我的信息输入框焦点的切换、执行按钮焦点的切换等。this
接口说明:spa
static void QWidget::setTabOrder(QWidget * first, QWidget * second)
.net
Puts the second widget after the first widget in the focus order.code
也就是说,按下Tan键后,焦点会从第一个控件切换到第二个控件。blog
注意,若是第二个控件Tab顺序改变,则应该这样设置一个顺序链:接口
//设置a、b、c、d顺序
setTabOrder(a, b); //a->b
setTabOrder(b, c); //a->b->c
setTabOrder(c, d); //a->b->c->d
而不是这样:图片
//错误
setTabOrder(c, d); // c->d
setTabOrder(a, b); // a->b 和 c->d
setTabOrder(b, c); // a->b->c, 但不是c->d
这里以三个按钮如三个输入框为例,来讲明Tab的顺序。get
设置获取焦点时的样式,以便咱们更清楚的观看效果。
QPushButton *pButton1 = new QPushButton(this);
QPushButton *pButton2 = new QPushButton(this);
QPushButton *pButton3 = new QPushButton(this);
QLineEdit *pLineEdit1 = new QLineEdit(this);
QLineEdit *pLineEdit2 = new QLineEdit(this);
QLineEdit *pLineEdit3 = new QLineEdit(this);
pButton1->setText("1");
pButton2->setText("3");
pButton3->setText("5");
pLineEdit1->setText("6");
pLineEdit2->setText("4");
pLineEdit3->setText("2");
pButton1->setStyleSheet("QPushButton:focus{border:none; background: green; color: white;}");
pButton2->setStyleSheet("QPushButton:focus{border:none; background: green; color: white;}");
pButton3->setStyleSheet("QPushButton:focus{border:none; background: green; color: white;}");
pLineEdit1->setStyleSheet("QLineEdit:focus{border:2px solid green;}");
pLineEdit2->setStyleSheet("QLineEdit:focus{border:2px solid green;}");
pLineEdit3->setStyleSheet("QLineEdit:focus{border:2px solid green;}");
QWidget::setTabOrder(pButton1, pLineEdit3);
QWidget::setTabOrder(pLineEdit3, pButton2);
QWidget::setTabOrder(pButton2, pLineEdit2);
QWidget::setTabOrder(pLineEdit2, pButton3);
QWidget::setTabOrder(pButton3, pLineEdit1);
就这样,简简单单的一个接口解决了咱们的问题。有兴趣的小伙伴能够看下focusNextChild
。
原文做者:一去丶二三里
做者博客:去做者博客空间