我在尝试实现一个基本的游戏..。
我按键盘按钮,但我添加到我的QGraphicsPixmapItem QGraphicsScene不移动,我已经实现了一个keyPressedEvent函数.
当按下键时,我想移动像素映射项。
代码在下面..。
H(我的像素映射项的头文件)
class marioChar : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
bool flying;
explicit marioChar(QPixmap pic);
void keyPressEvent(QKeyEvent *event);
signals:
public slots:
};这是keypressEvent处理程序的实现:
void marioChar::keyPressEvent(QKeyEvent *event)
{
if(event->key()==Qt::Key_Right)
{
if(x()<380)
{
this->setPos(this->x()+20,this->y());
}
}
}
This is part of the game class where i add the pixmap item to the scene
game::game(int difficulty_Level)
{
set_Level(difficulty_Level);
set_Num_Of_Coins(0);
set_Score(0);
QGraphicsScene *scene = new QGraphicsScene();
header = new QGraphicsTextItem();
header->setZValue(1000);
timer = new QTimer();
time = new QTime();
time->start();
updateDisplay();
scene->addItem(header);
connect(timer,SIGNAL(timeout()),this,SLOT(updateDisplay()));
timer->start(500);
QGraphicsView *view = new QGraphicsView(scene);
scene->setSceneRect(0,0,1019,475);
QColor skyBlue;
skyBlue.setRgb(135,206,235);
view->setBackgroundBrush(QBrush(skyBlue));
QGraphicsRectItem *floor = new QGraphicsRectItem(0,460,1024,20);
floor->setBrush(Qt::black);
scene->addItem(floor);
player= new marioChar(QPixmap("MarioF.png"));
player->setPos(0,330);
player->setZValue(1003);
scene->addItem(player);
view->setFixedSize(1024,480);
view->show();
player->setFocus();
}提前感谢
发布于 2015-03-20 14:21:32
如果希望图形项侦听关键事件,则需要将QGraphicsItem::ItemIsFocusable标志设置为图形项。
从医生那里:
http://doc.qt.io/qt-5/qgraphicsitem.html#keyPressEvent
以及对QGraphicsItem::ItemIsFocusable标志的描述:
http://qt-project.org/doc/qt-4.8-snapshot/qgraphicsitem.html#GraphicsItemFlag-enum
发布于 2015-03-20 14:06:58
您的QGraphicsPixmapItem不应该继承QObject。您应该创建一个控制器来管理您的QGraphicsPixmapItem,并发出信号并处理游戏中所有QGraphicsPixmapItem的插槽。
发布于 2015-03-20 14:25:29
如前所述:“将QGraphicsItem::ItemIsFocusable标志设置为您的marioChar对象”
https://stackoverflow.com/questions/29168390
复制相似问题