根据鼠标位置渲染线条时出现的问题

时间:2013-09-03 15:32:05

标签: c++ qt mouseevent mousemove mouseclick-event

我有一个openGL小部件,我想渲染一条依赖于鼠标位置的行,如下所示:

        glPushMatrix();
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glColor4f(1, 0, 0, 0.1);
        glScalef(a, b, 0);
        glBegin(GL_LINES);
        glVertex2f(pushedX, pushedY);
        glVertex2f(currentX, currentY);
        glEnd();
        glFlush();
        glDisable(GL_BLEND);
        glPopMatrix();

其中:

pushedX=buttonPressCoordinates.x();
pushedY=buttonPressCoordinates.y();
currentX=mouseCurrentPosition.x();
currentY=mouseCurrentPosition.y();

渲染效果很好,当我移动鼠标连接线和按下的当前坐标时,线条会根据需要渲染。

BUT:

问题是,即使我将鼠标按在窗口小部件的某个位置并且不移动它,它也会随机生成(我认为)某些(x,y)并将其与坐标为一条线连接起来。鼠标按下位置。虽然当我开始移动鼠标时它开始工作正常。

请帮助修复此错误。

修改

分配鼠标当前值的代码

void MainWindow::mouseMoveEvent(QMouseEvent *eventMove)
{
    if(eventMove->buttons() & Qt::LeftButton)
    {
        GLWidget *widget = this->findChild<GLWidget *>("glwidget");
        float x = widget->getNormalizedWidth(widget->mapFromGlobal(QCursor::pos()).x());
        float y = widget->getNormalizedHeight(widget->mapFromGlobal(QCursor::pos()).y());
        float y_ = 1.0 - y;
        mouseCurrentPosition.setX(x);
        mouseCurrentPosition.setY(y_);
        widget->setCurrentX(mouseCurrentPosition.x());
        widget->setCurrentY(mouseCurrentPosition.y());
    }
}

注意: QPointF mouseCurrentPosition;getNormalizedWidth(...)是我定义的资金,完美无缺。

修改-2

鼠标点击坐标更新如下:

setMouseTracking(true);
m = true;
GLWidget *widget = this->findChild<GLWidget *>("glwidget");
float x = widget->getNormalizedWidth(widget->mapFromGlobal(QCursor::pos()).x());
float y = widget->getNormalizedHeight(widget->mapFromGlobal(QCursor::pos()).y());
float y_ = 1.0 - y;
buttonPressCoordinates.setX(x);
buttonPressCoordinates.setY(y_);
qDebug() << buttonPressCoordinates.x() << buttonPressCoordinates.y();
widget->setQ(true);
widget->setPushedX(buttonPressCoordinates.x());
widget->setPushedY(buttonPressCoordinates.y());

1 个答案:

答案 0 :(得分:0)

您可以尝试的一件事是在currentX未按currentY时更新mouseMoveEventLeftButton

void MainWindow::mouseMoveEvent(QMouseEvent *eventMove)
{

     GLWidget *widget = this->findChild<GLWidget *>("glwidget");
     float x = widget->getNormalizedWidth(widget->mapFromGlobal(QCursor::pos()).x());
     float y = widget->getNormalizedHeight(widget->mapFromGlobal(QCursor::pos()).y());
     float y_ = 1.0 - y;

    if(eventMove->buttons() & Qt::LeftButton)
    {      
        buttonPressCoordinates.setX(x);
        buttonPressCoordinates.setY(y_);      
        widget->setPushedX(buttonPressCoordinates.x());
        widget->setPushedY(buttonPressCoordinates.y());
    }
    else
    {
        mouseCurrentPosition.setX(x);
        mouseCurrentPosition.setY(y_);
        widget->setCurrentX(mouseCurrentPosition.x());
        widget->setCurrentY(mouseCurrentPosition.y());
    }
}