我使用的是在Qt GUI中继承QMainWindow的类,以及另一个处理游戏逻辑的类。
代码的目的是将UI元素放置在窗口中的特定位置(以及根据需要移动它们。)但是,我遇到了问题。如果我增加窗口的大小,Y轴会比窗口大,并将对象置于折叠下方。
game.h
#ifndef GAME_H
#define GAME_H
#include "util.h"
#include "myrect.h"
class Game: public QObject
{
Q_OBJECT
TheColony * TC;
public:
Game(TheColony * ThC);
QRect getBoard(){ return QRect(0,0,TC->geometry().width(),TC->geometry().height()); }
private slots:
virtual void periodic();
protected:
QGraphicsScene * scene;
QGraphicsView * view;
MyRect * player;
QTimer * periodic_timer;
};
#endif // GAME_H
game.cpp
#include "game.h"
Game::Game(TheColony * ThC)
: TC(ThC){
//prepare the scene and view
scene = new QGraphicsScene(getBoard(),TC);
view = new QGraphicsView(scene);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setGeometry(getBoard());
view->show();
TC->setCentralWidget(view);
//setup the player's position and size
player = new MyRect(QRect((view->width()/2) - 50,view->height() - 100,100,100));
player->setFlag(QGraphicsItem::ItemIsFocusable);
scene->addItem(player);
player->setFocus();
//timer used to trigger periodic checks.
periodic_timer = new QTimer();
connect(periodic_timer,SIGNAL(timeout()),this,SLOT(periodic()));
periodic_timer->start(500);
}
void Game::periodic(){
static int tcHeight = getBoard().height();
if(tcHeight != getBoard().height()){
view->setGeometry(getBoard());
player->setRect(player->rect().x(), getBoard().height() - 100,100,100);
tcHeight = getBoard().height();
}
}
答案 0 :(得分:0)
由不和谐的freqlabs解决(谁没有堆栈溢出帐户。)
我没有更新QGraphicsScene的rect;
scene->setSceneRect(getBoard());
这使得场景的坐标空间不正确,导致对象被错误翻译。我误解了Qt究竟是如何使用坐标的,我没有意识到它使用了矩阵平移的实际坐标空间。