【Qt】Qt之Tab鍵切換焦點順序【轉】


簡介

Qt的窗口部件按用戶的習慣來處理鍵盤焦點。也就是說,其出發點是用戶的焦點能定向到任何一個窗口,或者窗口中任何一個部件。

焦點獲取方式比較多,例如:鼠標點擊、Tab鍵切換、快捷鍵、鼠標滾輪等。

習慣性的,我們經常會使用Tab鍵來控制焦點順序,比如:用戶注冊時,個人信息輸入框焦點的切換、執行按鈕焦點的切換等。

效果

這里寫圖片描述

實現方式

接口說明:

static void QWidget::setTabOrder(QWidget * first, QWidget * second)

Puts the second widget after the first widget in the focus order.

也就是說,按下Tan鍵后,焦點會從第一個控件切換到第二個控件。

注意,如果第二個控件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的順序。

設置獲取焦點時的樣式,以便我們更清楚的觀看效果。

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

 


原文作者:一去丶二三里
作者博客:去作者博客空間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM