围绕QgraphicsScene移动QGraphicsView

move QGraphicsView around QGraphicsScene

本文关键字:QGraphicsView 移动 QgraphicsScene 围绕      更新时间:2023-10-16

我正在qt c 中制作侧视图拖动赛车游戏。我想将我的视野从左至右移动。我将场景设置为3600x800,但我希望视图在我场景的最左边,而不是一开始就位于中心。当我在键盘上按W时,我希望视图向左移动1px。我怎么做?我在网上找不到任何东西

scene=new QGraphicsScene(this);
view = new QGraphicsView;
scene->setSceneRect(0,0,3600,800);
view->setScene(scene);

您永远不会在互联网上找到如此特殊的东西,您应该分别寻找每个部分:

  • 如果您希望它出现在左侧,则必须在显示GraphicsViewhorizontalScrollBar()时使用showEvent方法。

  • 如果在按任何键时要执行操作,则可以覆盖keyPressEvent方法。

  • 要移动sceneRect(),您必须制作副本,将其移动并再次设置。


#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QKeyEvent>
#include <QScrollBar>
class GraphicsView: public QGraphicsView{
public:
    using QGraphicsView::QGraphicsView;
protected:
    void keyPressEvent(QKeyEvent *event){
        if(event->key() == Qt::Key_W){
            if(scene()){
                QRectF rect = scene()->sceneRect();
                rect.translate(1, 0);
                scene()->setSceneRect(rect);
            }
        }
    }
    void showEvent(QShowEvent *event){
        QGraphicsView::showEvent(event);
        if(isVisible()){
            horizontalScrollBar()->setValue(0);
        }
    }
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    GraphicsView view;
    scene.setSceneRect(0,0,3600,800);
    view.setScene(&scene);
    scene.addRect(0, 200, 400, 400, Qt::NoPen, Qt::red);
    view.show();
    return a.exec();
}