我有一个任务:当鼠标光标进入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();
}
}myObj是从QWidget继承的。但我觉得我的想法没有效率。因为每次鼠标在QRect外移动时,它都会将颜色更改为绿色(即使它是绿色的)。不幸的是,QRect没有enterEvent()函数。你能不能,请给我一个建议,如何做好这件事。
发布于 2014-03-10 08:50:18
您可以创建一个布尔类成员,例如_lastPositionWasInsideRect,将其初始化为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
}一个更容易的选择是考虑使用QGraphicsView框架。
https://stackoverflow.com/questions/22295287
复制相似问题