简体   繁体   English

在QGraphicsView中滚动

[英]Scrolling in QGraphicsView

I have problem with scrolling in QGraphicsView. 我在QGraphicsView中滚动时遇到问题。

I've set scene rect in my QGraphicsView subclass: 我在我的QGraphicsView子类中设置了场景矩形:

MyQGraphicsView::MyQGraphicsView{
    setSceneRect(0,0,2000,2000)
}

And overloaded paintEvent: 并重载paintEvent:

void MyQGraphicsView::paintEvent(QPaintEvent *event){
    qDebug()<<"Paint event";
    QPainter painter(viewport());
    painter.setRenderHint(QPainter::Antialiasing);
    paint(painter);
}
void MyQGraphicsView::paint(QPainter &painter){
    painter.setPen(Qt::NoPen);
    painter.fillRect(QRect(0,0,200,200),Qt::gray);
    painter.fillRect(QRect(500,500,1000,100),Qt::green);
    painter.setPen(QPen(Qt::white,4,Qt::DashLine));
    painter.drawLine(QLine(0,35,200,35));
    painter.drawLine(QLine(0,165,200,165));
}

When I scroll the second rectangle is not visible. 当我滚动时,第二个矩形不可见。 When I resize window it is. 当我调整窗口大小时。 Also when scrolling rectangle is extending in wired way. 同样在滚动矩形以有线方式扩展时。

How should scrolling be implemened in this case? 在这种情况下应如何实现滚动? I've found several topics about scrolling in QGraphicsView but none solves my problem. 我发现了一些有关在QGraphicsView中滚动的主题,但没有一个解决我的问题。

QGraphicsView inherits QAbstractScrollArea . QGraphicsView继承QAbstractScrollArea So its content is displayed in its internal widget that can be obtained using viewport() . 因此,其内容显示在其内部小部件中,可以使用viewport()获得该小部件。 If you want to paint something and be able to scroll it, you need to attach an event filter to viewport widget and process its paintEvent, not view's event. 如果要绘制某些东西并能够滚动它,则需要将一个事件过滤器附加到视口小部件并处理其paintEvent,而不是视图的事件。

But you should not do this for QGraphicsView . 但是您不应该对QGraphicsView这样做。 You're trying to do something terribly wrong. 您正在尝试做严重的错误。 You should not reimplement QGraphicsView::paintEvent just to paint something! 您不应该只是为了绘画而重新实现QGraphicsView::paintEvent It totally devalues its advantages. 它完全贬低了它的优势。 You need to use QGraphicsScene to add something to the view. 您需要使用QGraphicsScene向视图中添加一些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM