【问题标题】:move QGraphicsView around QGraphicsScene在 QGraphicsScene 周围移动 QGraphicsView
【发布时间】:2018-02-27 17:59:40
【问题描述】:

我正在用 QT c++ 制作一个侧视图飙车游戏。我想从左到右移动我的场景周围的视图。我将场景设置为 3600x800,但我希望视图位于场景的最左侧而不是开始时的中心。当我在键盘上按 W 时,我希望视图向左移动 1 像素。我怎么做?我在网上找不到任何东西

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

【问题讨论】:

  • 我的解决方案有效吗?
  • 是的,谢谢!

标签: c++ qt


【解决方案1】:

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

  • 如果你想让它出现在左侧那么你必须使用horizontalScrollBar()GraphicsView来显示它,我们可以使用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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2011-06-26
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多