首先來說說為什么要設置焦點吧。
設置焦點可以讓應用更便捷。比如當你打開百度主頁或其他帶有編輯框的頁面時,不需要先用鼠標點擊編輯框就可以直接輸入文字等信息到其中。這就是由於搜索框設置了焦點。
一個空間要先設置它焦點事件的模式,即窗口如何接受焦點事件(通過鼠標單擊、Tab鍵、不接受焦點事件等)
用
| void |
setFocusPolicy ( Qt::FocusPolicy policy ) |
設置獲得焦點的方式
| Constant | Value | Description |
|---|---|---|
| Qt::TabFocus | 0x1 | 通過Tab鍵獲得焦點 |
| Qt::ClickFocus | 0x2 | 通過被單擊獲得焦點 |
| Qt::StrongFocus | TabFocus | ClickFocus | 0x8 | 可通過上面兩種方式獲得焦點 |
| Qt::WheelFocus | StrongFocus | 0x4 | 類似Qt::StrongFocus只不過再加上鼠標滑輪 |
| Qt::NoFocus | 0 | 不能通過上兩種方式獲得焦點(默認值),setFocus仍可使其獲得焦點. |
當前有焦點事件的窗口只能有一個,當一個窗口獲取焦點事件或失去焦點事件時,可能需要相應的操作,或者如
何判斷一個才窗口有沒有焦點事件。Qt中亦有相應的函數。
void QWidget::focusInEvent ( QFocusEvent * event ) [virtual protected]
void QWidget::focusOutEvent ( QFocusEvent * event ) [virtual protected]
這兩個就是窗口獲取或失去焦點事件的函數,需要我們重寫(好多窗口都是從QWidget繼承這兩個函數的)
bool hasFocus () const
這個函數就是判斷當前窗口有沒有焦點事件的,返回布爾值。
void QWidget::setFocus ( Qt::FocusReason reason )
void QWidget::clearFocus ()
這兩個函數就是設置或清除焦點事件的。
| Constant | Value | Description |
|---|---|---|
| Qt::TabFocus | 0x1 | the widget accepts focus by tabbing. |
| Qt::ClickFocus | 0x2 | the widget accepts focus by clicking. |
| Qt::StrongFocus | TabFocus | ClickFocus | 0x8 | the widget accepts focus by both tabbing and clicking. On Mac OS X this will also be indicate that the widget accepts tab focus when in 'Text/List focus mode'. |
| Qt::WheelFocus | StrongFocus | 0x4 | like Qt::StrongFocus plus the widget accepts focus by using the mouse wheel. |
| Qt::NoFocus | 0 | the widget does not accept focus. |
