qt中使用鼠标绘制直线图元的例子
时间: 2023-11-27 19:50:25 浏览: 165
Qt画线示例
以下是一个简单的示例,演示如何在Qt中使用鼠标绘制直线图:
```cpp
#include <QtGui>
#include <Widgets>
class Line : public QGraphicsLineItem
{
public:
Line(const QLineF& line) : QGraphicsLineItem(line) {}
QRectF boundingRect() const override { return pen().widthF() + 20.0 + QGraphicsLineItem::boundingRect(); }
QPainterPath shape() const override
{
QPainterPath path = QGraphicsLineItem::shape();
path.addRect(boundingRect());
return path;
}
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override
{
if (option->state & QStyle::State_Selected)
{
painter->setPen(QPen(option->palette.windowText(), 0, Qt::DotLine));
painter->drawRect(boundingRect());
}
QGraphicsLineItem::paint(painter, option, widget);
}
};
class GraphicsView : public QGraphicsView
{
public:
GraphicsView(QWidget* parent = nullptr) : QGraphicsView(parent), m_isDrawing(false), m_line(nullptr)
{
setRenderHint(QPainter::Antialiasing);
setDragMode(QGraphicsView::RubberBandDrag);
setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing);
setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
setSelectionMode(QGraphicsView::SingleSelection);
}
protected:
void mousePressEvent(QMouseEvent* event) override
{
if (event->button() == Qt::LeftButton)
{
m_startPos = mapToScene(event->pos());
m_isDrawing = true;
}
QGraphicsView::mousePressEvent(event);
}
void mouseMoveEvent(QMouseEvent* event) override
{
if (m_isDrawing)
{
if (!m_line)
{
m_line = new Line(QLineF(m_startPos, mapToScene(event->pos())));
scene()->addItem(m_line);
}
else
{
m_line->setLine(QLineF(m_startPos, mapToScene(event->pos())));
}
}
QGraphicsView::mouseMoveEvent(event);
}
void mouseReleaseEvent(QMouseEvent* event) override
{
if (event->button() == Qt::LeftButton && m_isDrawing)
{
m_isDrawing = false;
m_line = nullptr;
}
QGraphicsView::mouseReleaseEvent(event);
}
private:
bool m_isDrawing;
QPointF m_startPos;
Line* m_line;
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QGraphicsScene scene;
GraphicsView view(&scene);
view.setRenderHint(QPainter::Antialiasing);
view.setScene(&scene);
view.setDragMode(QGraphicsView::RubberBandDrag);
QGraphicsLineItem* line = new QGraphicsLineItem(QLineF(0.0, 0.0, 100.0, 100.0));
line->setPen(QPen(Qt::red, 2));
scene.addItem(line);
QGraphicsEllipseItem* ellipse = new QGraphicsEllipseItem(QRectF(0.0, 0.0, 100.0, 100.0));
ellipse->setPen(QPen(Qt::blue, 2));
ellipse->setBrush(QBrush(Qt::green));
scene.addItem(ellipse);
view.setSceneRect(-150, -150, 300, 300);
view.setFixedSize(300, 300);
view.show();
return app.exec();
}
```
该示例演示了如何使用QGraphicsView和QGraphicsScene来绘制直线。在鼠标按下时,记录起始位置,并在鼠标移动时绘制直线。在鼠标释放时,停止绘制。该示例还演示了如何添加其他类型的图元,如椭圆和直线。
阅读全文