【问题标题】:How can I show/hide background drawing on QGraphicsScene or QGraphicsView?如何在 QGraphicsScene 或 QGraphicsView 上显示/隐藏背景绘图?
【发布时间】:2015-06-02 14:57:55
【问题描述】:

我想在 QGraphicsScene 上绘制某些东西,但不是 QGraphicsItem(它会干扰QGraphicsItem 集合的处理)。

示例:场景边界矩形、网格

为此,我将覆盖drawBackground(QPainter *painter, const QRectF &rect)。 (我应该对场景进行子类化......)

void MyView::showHideBounds()
{
    m_showBackgroundBounds = !m_showBackgroundBounds;
    // can't triger an update ???
    update(); // neither does anything
    viewport()->update();
}

void MyView::drawBackground(QPainter *painter, const QRectF &rect)
{
    QPen pen;
    if(m_showBackgroundBounds)
        pen = QPen(QColor(0, 0, 0), 10, Qt::PenStyle(Qt::SolidLine));
    else
        pen = QPen(QColor(255, 255, 255), 10, Qt::PenStyle(Qt::SolidLine));

    painter->setPen(pen);
    painter->drawRect(QRect(QPoint(-scene()->sceneRect().size().toSize().width()/2,
                                   -scene()->sceneRect().size().toSize().height()/2),
                            scene()->sceneRect().size().toSize()));
}

我想要显示/隐藏边界矩形或网格的选项。

我唯一能想到的就是用背景画笔的颜色在它们上面画画?还有其他选择吗?

正如我在上面写的那样,它可以工作 - 除非我需要用户对项目(或缩放或其他场景更改操作)进行操作以触发刷新或调用更新...(函数 showHideBounds 没有' t - 不知道如何让它强制刷新)

我会从showHideBounds 函数调用drawBackground - 但我不知道如何获取painter

[另外,drawBackground 似乎是自动绘制的......我怎样才能给它它需要的rect 参数? (似乎如果我绘制 rect 它确实绘制了场景矩形,但我只看到右边缘和下边缘)]

【问题讨论】:

  • 这似乎不太合理。将每个可见对象添加为图形项要简单得多。如果它“干扰”某些处理,只需修复处理即可。例如,您可以添加一个表示您的项目集合的图形项目,并使其他项目成为其子项。
  • @PavelStrakhov 保存(渲染整个场景)和 fitInView(所有场景项目边界矩形)之类的函数会受到影响 - 重写它们以遍历所有项目以检查项目是否有父项或检查一个标志,也许会创建一个虚拟场景副本,会导致很大的性能影响......
  • 我不认为提到的问题是无法解决的。如果您不想在结果中看到不需要的项目,则可以在渲染时隐藏它们。使用QGraphicsItem::​childrenBoundingRect 可以有效地计算边界矩形。

标签: qt drawing qgraphicsscene


【解决方案1】:

为了重绘场景的特定部分,你可以调用

QGraphicsScene->invalidate(rect_to_redraw, Backgroundlayer)

请注意,如果drawBackground(*painter, rect) 绘制在矩形之外的区域,它不会自动更新。在这种情况下,必须使用适当的 rect 参数调用 invalidate。

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2014-11-16
    相关资源
    最近更新 更多