2009-07-17 90 views
1

我想在用戶發佈時撥打一些自定義複製代碼Ctrl + C。當CCtrl之前發佈時,Qt發送與QKeySequence::Copy匹配的關鍵事件。當CtrlC之前發佈時,發佈事件不匹配。如何在Ctrl'C'之前釋放Ctrl時用Qt捕捉Ctrl + C鍵事件?

當按鍵釋放事件開始與按Ctrl,有沒有辦法,看看是否仍然被按住Ç

當我不處理Ctrl首先被釋放,事件被傳遞,它做一個正常的副本,這正是我不想發生的事情。

bool 
MyWidget::eventFilter(QObject* object, QEvent* event) 
{ 
    // the text edit box filters its events through here 
    if (object == m_text_edit_box) 
    { 
     if (event->type() == QEvent::KeyPress) 
     { 
     QKeyEvent *key_event = static_cast<QKeyEvent*>(event); 

     if (key_event->matches(QKeySequence::Copy)) 
     { 
      // don't do anything and don't pass along event 
      return true; 
     } 
     } 
     else if (event->type() == QEvent::KeyRelease) 
     { 
     QKeyEvent *key_event = static_cast<QKeyEvent*>(event); 

     if (key_event->matches(QKeySequence::Copy)) 
     { 
      // we only get in here if 'c' is released before ctrl 
      callCustomCopy(); 
      return true; 
     } 
     } 
    } 

    // pass along event 
    return false; 
} 

回答

1

您可以專門查詢字母'C'和元鍵'Ctrl'而不依賴於key_even-> matches()。您當然可以在您在keydown事件存儲中找到eventfilter的對象中查看keydown序列與副本匹配的事實。

這個(未經測試的)可能適用於您,請注意,靜態變量應該是包含在其中的類的成員變量,這在本示例的上下文中似乎更清晰。您想要完成的確切邏輯可能需要更多的狀態信息才能在事件之間進行。

bool MyWidget::eventFilter(QObject* object, QEvent* event) 
{ 
    // Remember state between events 
    static foundCopy = false; 
    // the text edit box filters its events through here 
    if (object == m_text_edit_box) 
    { 
    if (event->type() == QEvent::KeyPress) 
    { 
    QKeyEvent *key_event = static_cast<QKeyEvent*>(event); 
     if (key_event->matches(QKeySequence::Copy)) 
     { 
     foundCopy = true; 
     // don't do anything and don't pass along event 
     return true; 
     } 
     else 
     { 
     foundCopy = false; 
     // This is another sequence, ignore and pass event 
     // Note that this will trigger with ctrl+c+a and others 

     } 
    } 
    else if (event->type() == QEvent::KeyRelease) 
    { 
     QKeyEvent *key_event = static_cast<QKeyEvent*>(event); 
     if (foundCopy) 
     { 
     callCustomCopy(); 
     foundCopy = false; 
     return true; 
     } 
     // This should keep the system copy from triggering 
     if (key_event->matches(QKeySequence::Copy)) 
     { 
     return true; 
     } 
    } 
    } 

    // pass along event 
return false; 
} 

另一種方法是收集在當前時間按下所有按鍵,然後實際的狀態時,一個被釋放了解哪些仍然壓制。

從用戶界面的角度來看,請記住,所有的鍵盤操作都是在按下時執行的(例如鍵入,窗口粘貼),一般在發佈時執行操作可能會混淆用戶,特別是當有可見結果那個行動。我無法從你的例子中看出你正在努力完成什麼。