1.首先在OccView中添加用于显示矩形框的类
//! rubber rectangle for the mouse selection.Handle(AIS_RubberBand) mRectBand;
2.设置框选的属性
mRectBand = new AIS_RubberBand();
//设置属性
mRectBand->SetLineType(Aspect_TOL_SOLID); //设置变宽线型为实线
mRectBand->SetLineColor(Quantity_NOC_RED);
3.在鼠标移动的事件中添加新的事件
void OccView::mouseMoveEvent(QMouseEvent* theEvent)
{if ((theEvent->buttons() & Qt::LeftButton) && (theEvent->buttons() & Qt::RightButton)){//鼠标左右按键一起按,执行平移myView->Pan(theEvent->pos().x() - myXmax, myYmax - theEvent->pos().y());//沿视图投影的x和y轴平移视图中心,可用于交互式平移操作myXmax = theEvent->x();myYmax = theEvent->y();}else if (theEvent->buttons() & Qt::MiddleButton){//鼠标滚轮按键if (qApp->keyboardModifiers() == Qt::ShiftModifier) //且按下shift按键{//鼠标滚轮按键执行平移myView->Pan(theEvent->pos().x() - myXmax, myYmax - theEvent->pos().y());myXmax = theEvent->x();myYmax = theEvent->y();}else{myView->Rotation(theEvent->x(), theEvent->y());}}else if (theEvent->buttons() & Qt::LeftButton){//绘制选择框//获得视口尺寸int winViewWidth = 0;int winViewHeight = 0;myView->Window()->Size(winViewWidth, winViewHeight);//设置矩形边界mRectBand->SetRectangle(myXmax, winViewHeight - myYmax, theEvent->pos().x(), winViewHeight - theEvent->pos().y());//更新显示if (myContext->IsDisplayed(mRectBand)){myContext->Redisplay(mRectBand, true);}else{myContext->Display(mRectBand, true);}myContext->SelectRectangle(Graphic3d_Vec2i(myXmax, myYmax), Graphic3d_Vec2i(theEvent->pos().x(), theEvent->pos().y()), myView);}else{//将鼠标位置传递到交互环境myContext->MoveTo(theEvent->pos().x(), theEvent->pos().y(), myView, Standard_Boolean(true));}
}
4.在鼠标释放事件中清空框选
void OccView::mouseReleaseEvent(QMouseEvent* theEvent)
{std::cout << myContext->IsDisplayed(mRectBand) << std::endl;if (myContext->IsDisplayed(mRectBand)){myContext->Remove(mRectBand, Standard_True);myView->Update();}//将鼠标位置传递到交互环境myContext->MoveTo(theEvent->pos().x(), theEvent->pos().y(), myView, Standard_Boolean(true));
}
效果图: