用鼠标光标移动圆?

时间:2019-06-27 16:40:43

标签: c++ qt

我想通过光标移动圆,但是此代码通过光标移动了图像。 如何根据光标移动圆。

label.cpp

void Label::mousePressEvent(QMouseEvent* event){
    mousePressed = true; 
    mCirc.setTopLeft(event->pos());
    mCirc.setBottomRight(event->pos());

    offset = event->pos();
}

void Label::mouseMoveEvent ( QMouseEvent * mouse_event )
{
    if(mouse_event->type() == QEvent::MouseMove &&  mousePressed == true)
    {
        mCirc.setBottomRight(mouse_event->pos());
    }

    update();
    if(mouse_event->buttons() & Qt::LeftButton)
    {
        this->move(mapToParent(mouse_event->pos() - offset));
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用moveCenter方法移动椭圆。

void Label::mousePressEvent(QMouseEvent* event){
    mousePressed = true; 
    if( mouse_event->buttons() & Qt::RightButton ){
        mCirc.setTopLeft(event->pos());
        mCirc.setBottomRight(event->pos());
    }
    if( mouse_event->buttons() & Qt::LeftButton) {
        offset = event->pos();
        center = mCirc.center();
    }
}

void Label::mouseMoveEvent ( QMouseEvent * mouse_event )
{
    ...
    if(mouse_event->buttons() & Qt::LeftButton) {
        QPoint delta = mouse_event->pos() - offset;    
        mCirc->moveCenter( center + delta);
    }
    update();
}

您可能还想通过选中右键来保护其他操作。

void Label::mouseMoveEvent ( QMouseEvent * mouse_event )
{
    if(mouse_event->type() == QEvent::MouseMove &&  mousePressed == true){
        if(mouse_event->buttons() & Qt::RightButton) {
            mCirc.setBottomRight(mouse_event->pos());
        }
        if(mouse_event->buttons() & Qt::LeftButton) {
            QPoint delta = mouse_event->pos() - offset;    
            mCirc->moveCenter( center + delta);
        }
        update();
    }
}