一、目的
用户可以自己框选图像区域检测区域
转载:https://blog.csdn.net/xiaolong1126626497/article/details/119636560
二、实现原理
利用QT鼠标事件和绘图事件。
鼠标事件主要:
virtual void paintEvent(QPaintEvent *event);
//截取鼠标事件绘制窗口位置. 因为标题栏隐藏后.窗口是无法拖动的。
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
三、详细代码
代码继承QLable
void Label::mouseReleaseEvent(QMouseEvent * event)
{
isPressedWidget = false; // 鼠标松开时,置为false
QRect rect(m_startPT, m_endPT);
qDebug() << "选择的范围:" << rect;
}
void Label::mousePressEvent(QMouseEvent * event)
{
m_endPT = m_startPT = event->pos();
isPressedWidget = true; // 当前鼠标按下的即是QWidget而非界面上布局的其它控件
}
void Label::mouseMoveEvent(QMouseEvent * event)
{
QPoint tmp_pos = event->pos();
if (abs(tmp_pos.x() - m_startPT.x()) > 0 || abs(tmp_pos.y() - m_startPT.y()) > 0)// if the mouse's point has changed.Then record the end point.
{
m_endPT = event->pos();
}
this->update();
}
void Label::paintEvent(QPaintEvent *event)
{
QLabel::paintEvent(event);
CalPosOutput *imgporc_out;
int img_width;
int img_height;
if (m_endPT.x() < 0 || m_endPT.x() > this->geometry().width() || m_endPT.y() < 0 || m_endPT.y() > this->geometry().height())
m_endPT = m_startPT;
qDebug() << this->geometry().x() << this->geometry().y() << this->geometry().width() << this->geometry().height();
qDebug() << m_startPT.x() << m_startPT.y() << m_endPT.x() << m_endPT.y();
//if(end)
//绘制样式
QStyleOption opt;
opt.initFrom(this);
QPainter painter(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);//绘制样式
if (isPressedWidget)
{
//定义画笔
QPen pen;
pen.setWidth(1);
pen.setColor(QColor("#00B0AE"));
pen.setStyle(Qt::SolidLine);
painter.setPen(pen);
//创建画刷
QBrush brush;
brush.setColor(QColor("#00B0AE"));
brush.setStyle(Qt::NoBrush);
painter.setBrush(brush);
}
#if 1
//QPainter painter(this);
if ((0 == Rectangle_w) || (0 == Rectangle_h))
{
img_width = this->width();
img_height = this->height();
}
else
{
img_width = Rectangle_w;
img_height = Rectangle_h;
}
painter.setPen(QPen(Qt::green, 1, Qt::SolidLine, Qt::RoundCap));
if ((0 == Rectangle_w) || (0 == Rectangle_h))
{
img_width = this->width();
img_height = this->height();
}
else
{
img_width = Rectangle_w;
img_height = Rectangle_h;
}
if (m_startPT != m_endPT)
{
QRect tempRt(m_startPT, m_endPT);
painter.drawRect(tempRt);
}
//painter.drawRect(QRect(img_width / 2 - 1 - m_boxWidth / 2, img_height / 2 - 1 - m_boxHeight / 2, m_boxWidth, m_boxHeight));
//绘制检测物体轮廓
imgporc_out = &WorkThread::imgproc_para_out;
float x = imgporc_out->rrect.center.x * (img_width / 2592.0);//按缩放比例调整位置
float y = imgporc_out->rrect.center.y * (img_height / 1944.0);
float width = imgporc_out->rrect.size.width * (img_width / 2592.0);
float height = imgporc_out->rrect.size.height * (img_height / 1944.0);
float angel = imgporc_out->rrect.angle;
QRect rect(x, y, width, height);
//旋转重绘
rotateAndPaintRect(&painter, rect, angel);
#endif
}
四、效果
连接相机实测可行,最后项目结束会发一个全部演示视频