我的drawingWidget.h中有QVector<QPoint>
m_顶点和QVector<QLine>
我目前正在尝试做一个简单的绘图工具,在那里我可以添加顶点和线。我设法在"MainWindow
"上绘制了多个顶点,但我真的不明白,如何在创建的顶点之间实现一条线。
基本上我已经创建了两个点,通过在第一个顶点上按鼠标左键,在第二个顶点上按下鼠标左键。。。它应该在它们之间创建一条线。
我该怎么做?
void DrawingWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.fillRect(event->rect(), Qt::blue);
painter.setBrush(Qt::black);
for(int i = 0; i < m_vertices.size() ; i++) {
painter.drawEllipse(m_vertices[i], 20, 20);
}
}
void DrawingWidget::mousePressEvent(QMouseEvent *event) {
if(m_state == ADD_VERTEX_SELECTED) {
if(event->button() == Qt::LeftButton) {
//m_x = event->x();
//m_y = event->y();
//update();
QPoint point = event->pos();
m_vertices.append(point);
update();
}
}
if(m_state == ADD_LINE_SELECTED) {
if(event->button() == Qt::LeftButton) {
QPoint Startpoint = event->x();
QPoint Endpoint = event->y();
}
}
}
您就快到了。为此,您需要使用QPainter::drawLine
,并从m_vertices
传递两个连续的鼠标QPoint
。
例如
void DrawingWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(event->rect(), Qt::blue);
painter.setPen(QPen(Qt::black, 3)); // width of the line
if(m_vertices.size() == 1) // for the first mouse click
painter.drawEllipse(m_vertices[0], 4, 4);
for(int i = 0; i < m_vertices.size()-1 ; i++)
{
const QPoint& point1 = m_vertices[i];
const QPoint& point2 = m_vertices[i+1];
// draw the mouse point
painter.drawEllipse(point1, 4, 4);
painter.drawEllipse(point2, 4, 4);
// draw the line
painter.drawLine(point1, point2);
}
}