我的GUI中有一个标签,将图像显示为QPixmap
。我希望能够通过简单地单击图像上的任意位置以选择起点,然后单击图像的其他部分在其他位置创建第二个点,从而在图像上绘制一条连续的线。在放置第二个点后,这两个点应立即连接,我希望能够通过在图像上放置更多点来继续同一条线。
虽然我知道如何在a上绘制一些东西QPixmap
,但是我还是一个新手,我需要用它来获取点的坐标的鼠标事件确实使我困惑Qt
。
解决方案的任何示例将不胜感激。
我建议您QGraphicsView
用于此目的。使用我的代码片段,效果很好。
子类QGraphicsScene
:
#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H
#include <QGraphicsScene>
#include <QPoint>
#include <QMouseEvent>
class GraphicsScene : public QGraphicsScene
{
Q_OBJECT
public:
explicit GraphicsScene(QObject *parent = 0);
signals:
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
public slots:
private:
QPolygon pol;
};
#endif // GRAPHICSSCENE_H
.cpp文件:
#include "graphicsscene.h"
#include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
GraphicsScene::GraphicsScene(QObject *parent) :
QGraphicsScene(parent)
{
addPixmap(QPixmap("G:/2/qt.jpg"));//your pixmap here
}
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
//qDebug() << "in";
if (mouseEvent->button() == Qt::LeftButton)
{
QPoint pos = mouseEvent->scenePos().toPoint();
pol.append(pos);
if(pol.size() > 1)
{
QPainterPath myPath;
myPath.addPolygon(pol);
addPath(myPath,QPen(Qt::red,2));
}
}
}
用法:
#include "graphicsscene.h"
//...
GraphicsScene *scene = new GraphicsScene(this);
ui->graphicsView->setScene(scene);
ui->graphicsView->show();
结果:
如果要将新的像素图(或仅获取像素图)另存为图像,请使用以下代码:
QPixmap pixmap(ui->graphicsView->scene()->sceneRect().size().toSize());
QString filename("example.jpg");
QPainter painter( &pixmap );
painter.setRenderHint(QPainter::Antialiasing);
ui->graphicsView->scene()->render( &painter, pixmap.rect(),pixmap.rect(), Qt::KeepAspectRatio );
painter.end();
pixmap.save(filename);
有了它,render()
您还可以抓取场景的不同区域。
但是这段代码可以更好:我们创建并绘制相同的多边形。如果我们可以记住最后绘制的点,则可以逐行绘制(线的起点是最后一行的末端)。在这种情况下,我们不需要所有点,我们只需要最后一点。
正如我所承诺的(代码改进):仅提供其他变量QPoint last;
来代替,QPolygon pol;
并使用下一个代码:
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
//qDebug() << "in";
if (mouseEvent->button() == Qt::LeftButton)
{
QPoint pos = mouseEvent->scenePos().toPoint();
if(last.isNull())
{
last = pos;
}
else
{
addLine(QLine(last,pos),QPen(Qt::red,2));
last = pos;
}
}
}
如您所见,您仅存储最后一点,仅绘制最后一行。用户可以单击数千次,现在您无需存储这些不必要的点并进行此不必要的重绘。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句