QPainter没有持续绘制

时间:2017-05-25 16:23:07

标签: c++ qt qpainter

我正在编写一个用Qt绘制图形的GUI。我的画家表现出一些不一致性:在编译之后,它只绘制了大约50%的时间来运行完全相同的二进制文件。我确实调用了QPainter的begin(),并且我还确保在调用函数时,我传递给绘图函数(如drawEllipse()的参数被初始化并具有有效值。

下面是相关代码(注意参数painter已经初始化,并且在此函数之前调用了begin()):

void GraphWidget::paintEvent(QPaintEvent *event) {
  QWidget::paintEvent(event);
  this->painter = new QPainter(this);
  painter->setRenderHint(QPainter::Antialiasing);
  // draw graph itself
  painter->translate(xOffset, yOffset);
  painter->scale(graphScale, graphScale);
  paintGraph(painter);
}

void GraphWidget::paintGraph() {
  if (this->graph) {
    // Iterate thought all edges and draw them
    for (Agnode_t *node = agfstnode(graph); node;
         node = agnxtnode(graph, node)) {
      for (Agedge_t *edge = agfstout(graph, node); edge;
           edge = agnxtout(graph, edge)) {
        drawEdge(edge);
      }
    }
    // Iterate through all nodes and draw them
    for (Agnode_t *node = agfstnode(graph); node;
         node = agnxtnode(graph, node)) {
      drawNode(node);
    }
  }
}

void GraphWidget::drawNode(Agnode_t *node) {

  ...

  //Height and width of node, in pixels.
  float scaleWidth = width * this->logicalDpiX();
  float scaleHeight = height * this->logicalDpiY();

  std::cout << "Drawing individual node. x = " << x << ". scaleWidth = " << scaleWidth << ". y = " << y << ". ScaleHeight = " << scaleHeight << "\n";
  //Actual node painting takes place here.
  painter->drawEllipse(x - scaleWidth / 2, y - scaleHeight / 2, scaleWidth, scaleHeight);

  ...

}

void GraphWidget::drawEdge(Agedge_t *edge) {
  // retrieve the position attribute and parse it
  float lastx, lasty, x, y;
  getNodePos(agtail(edge), lastx, lasty);
  auto spline_list = ED_spl(edge)->list;
  for (int i = 0; i < spline_list->size; i++) {
    x = spline_list->list[i].x;
    y = spline_list->list[i].y;
    painter->drawLine(lastx, lasty, x, y);
    lastx = x;
    lasty = y;
  }
  getNodePos(aghead(edge), x, y);
  painter->drawLine(lastx, lasty, x, y);
}

1 个答案:

答案 0 :(得分:0)

发现问题。调用painter->translate(xOffset, yOffset)导致画家问题,因为当我第一次打开窗口时,xOffsetyOffset未初始化,所以我的猜测是他们采用了随机值,图表被翻译成一些随机点在那里,我无法看到它。我只是确保在构造函数中将偏移量变量初始化为0,这解决了问题。