用qt写一个在图片上任意画有限条线,且在各条线起点和终点旁边分别显示像素坐标的代码,坐标的原点为图像的左上角,头文件和源文件分开
时间: 2023-07-14 22:12:12 浏览: 201
用qt写的画图工具
以下是一个简单的示例代码,可以实现在图片上绘制线条并显示坐标:
头文件 imageview.h:
```cpp
#ifndef IMAGEVIEW_H
#define IMAGEVIEW_H
#include <QWidget>
#include <QPixmap>
#include <QPoint>
#include <QVector>
class ImageView : public QWidget
{
Q_OBJECT
public:
explicit ImageView(QWidget *parent = nullptr);
void setImage(const QPixmap& image);
void addLine(const QPoint& start, const QPoint& end);
protected:
void paintEvent(QPaintEvent *event) override;
private:
QPixmap m_image;
QVector<QPoint> m_lines;
};
#endif // IMAGEVIEW_H
```
源文件 imageview.cpp:
```cpp
#include "imageview.h"
#include <QPainter>
#include <QMouseEvent>
ImageView::ImageView(QWidget *parent) :
QWidget(parent)
{
}
void ImageView::setImage(const QPixmap& image)
{
m_image = image;
update();
}
void ImageView::addLine(const QPoint& start, const QPoint& end)
{
m_lines.append(start);
m_lines.append(end);
update();
}
void ImageView::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
QPainter painter(this);
painter.drawPixmap(0, 0, m_image);
QPen pen(Qt::red);
pen.setWidth(2);
painter.setPen(pen);
QFont font;
font.setPointSize(8);
painter.setFont(font);
for (int i = 0; i < m_lines.size(); i += 2) {
QPoint start = m_lines.at(i);
QPoint end = m_lines.at(i + 1);
painter.drawLine(start, end);
painter.drawText(start.x(), start.y() - 5, QString("(%1, %2)").arg(start.x()).arg(start.y()));
painter.drawText(end.x(), end.y() - 5, QString("(%1, %2)").arg(end.x()).arg(end.y()));
}
}
```
使用时,首先创建一个 ImageView 对象,然后调用 setImage 方法设置要显示的图片。接着在鼠标按下和鼠标释放事件中添加线条,如下所示:
```cpp
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_startPoint = event->pos();
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_endPoint = event->pos();
m_imageView->addLine(m_startPoint, m_endPoint);
}
}
```
完整的示例代码可以参考以下链接:https://github.com/Qt-Widgets/ImageViewDemo
阅读全文