2010-08-10 47 views
3

Qt讓我質疑我的理智和存在。我不知道爲什麼在我編寫的一個程序中運行的代碼在我編寫的另一個程序中不起作用。以下代碼在兩個程序中都是相同的。在P1中,只有左鍵點擊才能正常工作。在P2中它是完全一樣的,除了左鍵點擊代碼是做了不同的事情。Qt鼠標點擊檢測一直不能工作

在P2中,我檢查了左鍵單擊條件並執行代碼,如果它是真的。那麼,當我離開或右鍵點擊時,它不會執行代碼。如果我更改條件以檢查右鍵單擊並返回true,則左鍵單擊正常工作,但右鍵單擊不會返回。如果我刪除條件,左右點擊運行代碼。

我迷失了我的想法,因爲像這樣的愚蠢的東西一直在發生,我不知道爲什麼即使我和其他工作的程序(我寫的)一樣。

編輯:它似乎忽略了mouseRelease函數中的if-check併爲mousePress和mouseMove正常工作。

P1(此程序工作正是我想要它):

void GLWidget::mousePressEvent(QMouseEvent *event) 
{ 
    clickOn = event->pos(); 
    clickOff = event->pos(); 

    // right mouse button 
    if (event->buttons() & Qt::RightButton){ 
     return; 
    } 

    // rest of left-click code here 
} 

/*************************************/ 

void GLWidget::mouseReleaseEvent(QMouseEvent *event) 
{ 
    clickOff = event->pos(); 

    // right mouse button shouldn't do anything 
    if (event->buttons() & Qt::RightButton) 
     return; 

    // rest of left click code here 

} 

/*************************************/ 

void GLWidget::mouseMoveEvent(QMouseEvent *event) 
{ 
    clickOff = event->pos(); 

    // do it only if left mouse button is down 
    if (event->buttons() & Qt::LeftButton) { 

     // left click code 

     updateGL(); 

    } else if(event->buttons() & Qt::RightButton){ 

     // right mouse button code 

    } 
} 

P2(結構類似於P1,但工作不正常):

void GLWidget::mousePressEvent(QMouseEvent *event) 
{ 
    clickOn = event->pos(); 
    clickOff = event->pos(); 

    // do it only if left mouse button is down 
    if (event->buttons() & Qt::LeftButton) { 
     // left click code 
    } 

} 

void GLWidget::mouseReleaseEvent(QMouseEvent *event) 
{ 
    clickOff = event->pos(); 

    // do it only if left mouse button is down 
    if (event->buttons() & Qt::LeftButton) { 
     // left click code 
    } 

} 

void GLWidget::mouseMoveEvent(QMouseEvent *event) 
{ 
    clickOff = event->pos(); 
    clickDiff = clickOff - clickOn; 

    // do it only if left mouse button is down 
    if (event->buttons() & Qt::LeftButton) { 
     // left click code 
     updateGL(); 
    } 
} 

回答

3

QMouseEvent::buttons() documentation

對於鼠標釋放事件,這排除了導致事件的按鈕。

因此,解決方案是使用QMouseEvent ::按鈕()代替:

void GLWidget::mouseReleaseEvent(QMouseEvent *event) 
{ 
    clickOff = event->pos(); 

    // do it only if left mouse button is down 
    if (event->button() == Qt::LeftButton) { 
     // left click code 
    } 
} 
+1

啊,那工作!謝謝!我認爲P1可能有足夠的檢查,如果它沒有在特定的條件下完成,它就不會執行左鍵單擊代碼。 – alex 2010-08-10 22:08:13