【发布时间】:2017-05-25 16:23:06
【问题描述】:
我正在编写一个用 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);
}
【问题讨论】:
-
除非有大量代码,否则请展示完整的
GraphWidget::drawNode和GraphWidget::paintEvent实现——或至少所有相关部分。 -
对不起-我刚刚添加了所有相关的绘画功能!希望这有助于更多,谢谢。我正在使用 Graphviz,以防您想知道 Agnode_t 和 Agedge_t 对象。它们来自 Graphviz 库。
-
不确定这是问题的一部分,但是...您在左侧、右侧和中间泄漏
QPainters。为什么要在堆上分配QPainter。摆脱painter成员,只使用QPainter painter(this)。然后,您还可以删除对QPainter::begin/end/save/restore的调用。 -
感谢您的输入 - 我已修复此问题,并且行为仍然相同(尽管现在代码更简洁更好)。