我的 drawingWidget.h中有QVector<QPoint> m_vertices和QVector<QLine>。h

我目前正在尝试做一个简单的绘图工具,可以在其中添加顶点和线。我设法在我的“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 ,并从QPoint传递两个连续的鼠标m_vertices

例如

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);
  }
}

09-07 09:14