C++ 输入事件时填写QRect

C++ 输入事件时填写QRect,c++,qt,C++,Qt,我有一个任务:当鼠标光标进入QRect对象时,应该绘制该对象。 几个小时后我做了这个 void myObj::mouseMoveEvent(QMouseEvent* event){ int x1, y1, x2, y2; QPoint point = event->pos(); rect->getCoords(&x1, &y1, &x2, &y2); if((point.x() >= x1) &&am

我有一个任务:当鼠标光标进入QRect对象时,应该绘制该对象。 几个小时后我做了这个

void myObj::mouseMoveEvent(QMouseEvent* event){   
    int x1, y1, x2, y2;
    QPoint point = event->pos();
    rect->getCoords(&x1, &y1, &x2, &y2);
    if((point.x() >= x1) && (point.x() <= x2) && (point.y() >= y1) && (point.y() <= y2)){
       changeRectColour();
    }else{
       brush->setColor(Qt::green);
       repaint();
    }
}
void myObj::mouseMoveEvent(QMouseEvent*event){
int-x1,y1,x2,y2;
QPoint point=事件->位置();
rect->getCoords(&x1,&y1,&x2,&y2);
如果((point.x()>=x1)&&&(point.x()=y1)&&(point.y()设置颜色(Qt::绿色);
重新油漆();
}
}
myObj是从QWidget继承的。 但我认为我的想法是无效的,因为每次鼠标移动到QRect之外,它都会将颜色变为绿色(即使是绿色)。 不幸的是,QRect没有enterEvent()函数。 请您给出一个正确的建议。

QWidget::repaint()的意思是“立即绘制!!!我等不及了!”。改用它,它会将多个绘制请求合并为一个(在文档中有更好的解释)

顺便说一句,您基本上是在重新实现
QRect::contains()
。您的新代码将

void myObj::mouseMoveEvent(QMouseEvent* event){   

    QPoint point = event->pos();
    if(rect->contains(point, true)){
       changeRectColour(); 
    }
    else{
       brush->setColor(Qt::green);
       update();
    }
}

您可以创建一个布尔类成员,例如
\u lastPositionwasinInside
,将其初始化为
false
,并对if语句进行如下编程:

bool positionIsInsideRect = (point.x() >= x1) && (point.x() <= x2) && (point.y() >= y1) && (point.y() <= y2));

if( positionIsInsideRect && !_lastPositionWasInsideRect )
{
    _lastPositionWasInsideRect = true;
    // do the changes which are required when entering the rect
}
else if( !positionIsInsideRect && _lastPositionWasInsideRect )
{
    _lastPositionWasInsideRect = false;
    // do the changes which are required when leaving the rect     
}
bool positionisinsidect=(point.x()>=x1)和&(point.x()=y1)和&(point.y())