繁体   English   中英

在输入事件时填写QRect

[英]Fill the QRect on enter event

我有一个任务:当鼠标光标进入时,应该绘制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还没有进入事件()函数。 请你能否正确地提出如何做到这一点的建议。

QWidget::repaint()意思是“现在画画!!!我等不及了!” 使用QWidget :: update()代替,将多个绘制请求合并为一个(在doc中更好的解释)。

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

void myObj::mouseMoveEvent(QMouseEvent* event){   

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

您可以创建一个布尔类成员,例如_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框架。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM