C++ 如何使用点在QPixmap上绘制直线
我的GUI中有一个标签,它将图像显示为C++ 如何使用点在QPixmap上绘制直线,c++,qt,qpixmap,C++,Qt,Qpixmap,我的GUI中有一个标签,它将图像显示为QPixmap。我希望能够在我的图像上画一条连续的线,只需单击图像上的任意位置以选择起点,然后通过单击图像的其他部分在其他位置创建第二个点。两个点应该在放置第二个点后立即连接,我希望能够通过在图像上放置更多点来继续这条线 虽然我知道如何在QPixmap上绘制一些东西,但我需要使用鼠标事件来获取点的坐标,这让我非常困惑,因为我对Qt还是相当陌生的 任何解决方案的示例都将不胜感激。我建议您为此使用QGraphicsView。使用我的代码片段,它可以完美地工作 子
QPixmap
。我希望能够在我的图像上画一条连续的线,只需单击图像上的任意位置以选择起点,然后通过单击图像的其他部分在其他位置创建第二个点。两个点应该在放置第二个点后立即连接,我希望能够通过在图像上放置更多点来继续这条线
虽然我知道如何在QPixmap
上绘制一些东西,但我需要使用鼠标事件来获取点的坐标,这让我非常困惑,因为我对Qt
还是相当陌生的
任何解决方案的示例都将不胜感激。我建议您为此使用
QGraphicsView
。使用我的代码片段,它可以完美地工作
子类qgraphicscene
:
#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
结果:
如果要将新的pixmap(或仅获取pixmap)另存为图像,请使用以下代码:
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代码>而不是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;
}
}
}
void graphicscene::mousePressEvent(qgraphicscenemouseevent*mouseEvent)
{
//qDebug()按钮()==Qt::LeftButton)
{
QPoint pos=mouseEvent->scenePos().toPoint();
if(last.isNull())
{
last=pos;
}
其他的
{
addLine(QLine(last,pos),QPen(Qt::red,2));
last=pos;
}
}
}
如您所见,只存储最后一个点,只绘制最后一条线。用户可以点击上千次,现在您不需要存储这些不必要的点并进行不必要的重新绘制 为了回答上述问题,您可以添加代码以获取结果,作为QPixmap
。请查看我的编辑,我按照承诺添加了非常重要的改进。
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);
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;
}
}
}