[英]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.