2010-06-10 21 views
4

我希望能夠知道是否在QLineEdit這是一個點擊。所以我想我應該重新實現以下功能(??):如何知道QLineEdit是否得到了重點?

void QLineEdit::focusInEvent (QFocusEvent * e) [virtual protected] 

我應該怎麼做?

另外,請告訴我如何使用focusInEvent()函數,以便知道QLineEdit myEdit;對象是否有焦點。

編輯:我寫了下面的功能:

bool LoginDialog::eventFilter(QObject *target, QEvent *event) 
{ 
    if (target == m_passwordLineEdit) 
    { 
     if (event->type() == QEvent::FocusIn) 
     { 
      if(checkCapsLock()) 
      { 
       QMessageBox::about(this,"Caps Lock", "Your caps lock is ON!"); 

      } 
      return true; 

     } 
    } 
    return QDialog::eventFilter(target, event); 
} 

並在LoginDialog類的構造函數註冊m_passwordLineEdit這樣的:

m_passwordLineEdit->installEventFilter(this); 

而且它落入MessageBox-的無限循環ES。請幫我解決這種情況。其實我想用彈出窗口來實現這個功能(不是用QMessageBox)。需要使用QLabel可以嗎?

回答

3

類似的東西:

class YourWidget : public QLineEdit 
{ 
    Q_OBJECT 

    protected: 

    void focusInEvent(QFocusEvent* e); 
}; 

.cpp文件:

void YourWidget::focusInEvent(QFocusEvent* e) 
{ 
    if (e->reason() == Qt::MouseFocusReason) 
    { 
     // The mouse trigerred the event 
    } 

    // You might also call the parent method. 
    QLineEdit::focusInEvent(e); 
} 

你可以找到所有可能的原因on this page列表。

+0

我想用bool eventFilter(QObject * target,QEvent * event)實現以便不寫一個子類。已經寫以下代碼: BOOL ::的LoginDialog eventFilter(的QObject *目標,QEvent的*事件) { 如果(目標== m_passwordLineEdit) { 如果(事件 - >類型()== QEvent的::的focusIn) (checkCapsLock()) QMessageBox :: about(this,「Caps Lock」,「Your caps lock is ON!」); } return true; } } return QDialog :: eventFilter(target,event); } 我陷入了無限循環的MessageBox-es。 :( – Narek 2010-06-10 09:32:40

+2

這是因爲你的'm_passwordLineEdit'會在顯示一個消息框時失去焦點,當這個盒子關閉時再次獲得焦點,導致再次顯示該盒子... – Job 2010-06-10 09:54:29

+1

我建議顯示一些永久消息(例如,在你的下面(在線編輯)當Caps Lock打開時,即使它沒有焦點 – Job 2010-06-10 09:57:47

0

如果你想知道有人點擊一個小部件,你應該覆蓋mousePressEvent (QMouseEvent* event)。一個focusInEvent可以觸發其他來源,而不是鼠標點擊。

例如:

class MyLineEdit : public QLineEdit 
{ 
     Q_OBJECT 
    public: 
     //... 
    protected: 
     void mousePressEvent(QMouseEvent* event) 
     { 
       //pass the event to QLineEdit 
       QLineEdit::mousePressEvent(event); 
       //register the click or act on it 
     } 
}; 

如果你想知道當你的小部件獲得焦點,做當然是focusInEvent相同。

+0

如果他想要知道點擊是否關注小部件,這樣做是不安全的。 – ereOn 2010-06-10 07:30:43

+0

「不安全」可能確實太多了;)我的意思是某些小部件可能會觸發mousePressEvent(),但仍然沒有獲得焦點。但你明白了我的觀點。 – ereOn 2010-06-10 07:34:48

6

另外,請告訴我怎麼用 focusInEvent()函數,以 知道QLineEdit的爲myedit;對象得到了 的重點。

你應該自己連接到以下信號:

void QApplication::focusChanged (QWidget * old, QWidget * now) [signal] 

當新QWidget的是你的QLineEdit的,你知道它有焦點!

希望它有幫助!

+0

啊不知道那個信號。這非常有用,因爲您不必爲了重寫'focusInEvent'而繼承一個小部件!缺點是您必須對您的應用程序中的每個*焦點更改作出反應。仍然值得+1 – Job 2010-06-10 09:21:25

+0

這是一個矯枉過正。應該是我認爲更好的方法。不管怎樣,謝謝。 – Narek 2010-06-10 10:01:07

+0

這將如何在Python中完成?我不想爲過濾器構建自定義類,然後將其安裝爲'QLineEdit.installEventFilter(CustomeFilterClass)' – 2013-11-01 08:17:42

相關問題