QPainter 绘制不一致

QPainter not drawing consistently

本文关键字:不一致 绘制 QPainter      更新时间:2023-10-16

我正在编写一个用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);
}

发现问题。调用painter->translate(xOffset, yOffset)会导致画家出现问题,因为当我第一次打开窗户时,xOffsetyOffset未初始化,所以我的猜测是它们采用随机值,并且图形正在被转换为我看不到它的某个随机位置。我只是确保在构造函数中将偏移变量初始化为 0,这解决了问题。