void ImageWidget::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); QPainter painter(this); painter.drawImage(rect(), m_image, m_image.rect()); painter.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap)); // 设置画笔颜色、宽度和样式 foreach (const QLine &line, m_lines) { painter.drawLine(line); painter.drawText(line.p1() + QPoint(5, -5), QString("(%1,%2)").arg(line.x1()).arg(line.y1())); // 显示起点坐标 painter.drawText(line.p2() + QPoint(5, -5), QString("(%1,%2)").arg(line.x2()).arg(line.y2())); // 显示终点坐标 } // 绘制当前正在绘制的线 if (m_isDrawing) { painter.drawLine(m_startPoint, m_endPoint); } } void ImageWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { if (!m_isDrawing) { m_startPoint = event->pos(); m_endPoint = event->pos(); m_isDrawing = true; } else { m_endPoint = event->pos(); m_isDrawing = false; m_lines.append(QLine(m_startPoint, m_endPoint)); update(); // 刷新窗口 } } }改进这段代码,使得第一条线的起点不是默认的原点,而是鼠标按下的点
时间: 2023-06-26 11:06:29 浏览: 228
可以在mousePressEvent函数中对m_startPoint进行赋值,将其赋值为鼠标按下的点即可。
修改后的代码如下:
void ImageWidget::paintEvent(QPaintEvent *event) {
QWidget::paintEvent(event);
QPainter painter(this);
painter.drawImage(rect(), m_image, m_image.rect());
painter.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap));
foreach (const QLine &line, m_lines) {
painter.drawLine(line);
painter.drawText(line.p1() + QPoint(5, -5), QString("(%1,%2)").arg(line.x1()).arg(line.y1()));
painter.drawText(line.p2() + QPoint(5, -5), QString("(%1,%2)").arg(line.x2()).arg(line.y2()));
}
if (m_isDrawing) {
painter.drawLine(m_startPoint, m_endPoint);
}
}
void ImageWidget::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
if (!m_isDrawing) {
m_startPoint = event->pos(); // 修改起点坐标
m_endPoint = event->pos();
m_isDrawing = true;
}
else {
m_endPoint = event->pos();
m_isDrawing = false;
m_lines.append(QLine(m_startPoint, m_endPoint));
update();
}
}
}
阅读全文