球使用Qt

时间:2016-05-09 14:57:58

标签: c++ qt

我正在尝试创建一个简单的动画,这个动画在屏幕上徘徊,只是在墙上反弹。由于我对C ++很新,我在这个任务上遇到了一些问题。我也在使用Qt库。 球只是停留在同一个位置并来回移动一点奇怪,因为我创建了一个与我的graphicsView相同大小的SceneRect。

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsScene>
#include <QtWidgets>


float movement_x = 2.5;
float movement_y = 2.0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

void MainWindow::showEvent(QShowEvent *event){


    scene = new QGraphicsScene(this);

    scene -> setSceneRect(ui->graphicsView->geometry().x(),          ui->graphicsView->geometry().y(),
                      ui->graphicsView->geometry().width(), ui->graphicsView->geometry().height());
    ui->graphicsView->setScene(scene);
    QPen redpen(Qt::red);


    QBrush brush(Qt::green);
    //QBrush brush2(Qt::black);
    QPen mypen(Qt::blue);
    mypen.setWidth(7);


     ellipse = scene->addEllipse(100.0,100.0,20.0,20.0,mypen,brush);
     timer1 = startTimer(50);
     timer2 = startTimer(600);

}

void MainWindow::timerEvent(QTimerEvent *event){
    // check for radius
    if(ellipse->pos().x() >= scene->sceneRect().right() ||       ellipse->pos().x() <= scene->sceneRect().left()){ 
        movement_x = -movement_x;
     }
    if(ellipse->pos().y() >= scene->sceneRect().bottom() ||     ellipse->pos().y() <= scene->sceneRect().top()){
        movement_y = -movement_y;
     }
    ellipse->moveBy(movement_x, movement_y);

}

MainWindow::~MainWindow()
{
    delete ui;
}

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QGraphicsScene>

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();


protected:
    void showEvent(QShowEvent* event);
    void timerEvent(QTimerEvent* event);
private:
    Ui::MainWindow *ui;
    QGraphicsScene *scene;
    QGraphicsEllipseItem *ellipse;
 };

#endif // MAINWINDOW_H

main.cpp中:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.resize(800,600);
    w.show();

    return a.exec();
}

2 个答案:

答案 0 :(得分:1)

您应该从场景中映射椭圆位置以找到边界:

QPoint posOfEclps = ellipse->mapToScene(ellipse->pos());


if(posOfEclps.x() >= scene->sceneRect().right() || posOfEclps.x() <= scene->sceneRect().left())
{ 
    movement_x = -movement_x;
}
if(posOfEclps.y() >= scene->sceneRect().bottom() || posOfEclps.y() <= scene->sceneRect().top())
{
    movement_y = -movement_y;
}
ellipse->moveBy(movement_x, movement_y);

答案 1 :(得分:1)

pos的初始值为(0,0)。因此,您的更新会在两个值之间振荡。在addEllipse之后,您必须在场景rect中设置初始位置。例如

ellipse->setPos(100,100);