gpt4 book ai didi

c++ - Qt鼠标点击检测一直不工作

转载 作者:太空狗 更新时间:2023-10-29 21:30:04 26 4
gpt4 key购买 nike

Qt 让我质疑我的理智和存在。我不知道为什么在我编写的一个程序中有效的代码在我编写的另一个程序中不起作用。以下代码在两个程序中是相同的。在 P1 中,它仅允许左键单击即可正常工作。在 P2 中,它完全相同,除了左键单击代码做了一些不同的事情。

在 P2 中,我让它检查左键单击条件,如果为真,则执行代码。好吧,当我左键或右键单击时,它不会执行代码。如果我更改条件以检查右键单击并返回如果为真,则左键单击正常,但右键单击不会返回。如果我删除条件,左键和右键单击都会运行代码。

我正在失去理智,因为像这样愚蠢的事情一直在发生,我不知道为什么,尽管我做的每件事都和其他有效的程序(我写的)一样。

编辑:它似乎忽略了 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();
}
}

最佳答案

来自 QMouseEvent::buttons() documentation :

For mouse release events this excludes the button that caused the event.

所以解决方案是使用 QMouseEvent::button() 代替:

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
}
}

关于c++ - Qt鼠标点击检测一直不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com