0

我有一个 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();

渲染进行得很好,当我移动鼠标与推送和当前坐标连接的线时,该线被渲染。

但:

问题是,即使我在小部件上的某处按下鼠标并且不移动它,它也会随机生成(我认为)一些 (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());
4

1 回答 1

0

您可以尝试的一件事是更新currentX并且currentY在未按下mouseMoveEvent时:LeftButton

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());
    }
}
于 2013-09-03T16:02:56.117 回答