我正在尝试实施基本游戏......
我按键盘按钮,但我添加到QGraphicsScene的QGraphicsPixmapItem 我没有动,我已经实现了一个keyPressedEvent函数......
我想在按下某个键时移动像素图项目。
代码在下面......
marioChar.h(我的pixmap项目的头文件)
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();
}
提前致谢
答案 0 :(得分:2)
如果您希望它监听关键事件,您需要将QGraphicsItem::ItemIsFocusable
标志设置为图形项目。
来自文档:
QGraphicsItem::ItemIsFocusable
标志的描述:
答案 1 :(得分:0)
您的QGraphicsPixmapItem
不应继承QObject
。您应该创建一个管理QGraphicsPixmapItem
的控制器,并发出信号并处理游戏中所有QGraphicsPixmapItem
的插槽。
答案 2 :(得分:0)
正如thuga所说: &#34;将QGraphicsItem :: ItemIsFocusable标志设置为marioChar对象&#34;