0
votes

I'm making a side view drag racing game in QT c++. I want to move my view around my scene from left to right. I have the scene set to 3600x800, but i want the view the be at the far left of my scene not at the center at the start. When i press W on my keyboard I want the view to move to the left for 1px. How do I do that? I can't find anything online

scene=new QGraphicsScene(this);
view = new QGraphicsView;
scene->setSceneRect(0,0,3600,800);
view->setScene(scene);
1
Did my solution work?eyllanesc
yes, it did thanks!Janez Potočnik

1 Answers

0
votes

You will never find something so particular on the internet, you should look for each part separately:

  • If you want it to appear on the left side then you must use horizontalScrollBar() of the GraphicsView when it is displayed, we can do that with the showEvent method.

  • if you want to do an action when you press any key you could overwrite the keyPressEvent method.

  • To move the sceneRect() you must make a copy, move it and set it again.


#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();
}