gpt4 book ai didi

c++ - Qt 捕捉按下的键

转载 作者:太空狗 更新时间:2023-10-29 23:34:07 24 4
gpt4 key购买 nike

我想写原始的蛇。我有程序绘制随机线条的窗口。

但我想不出如何捕获按下的键来改变画线的方向。

enter image description here

class QUpdatingPathIte : public QGraphicsPathItem
{
void advance(int phase)
{

if (phase == 0)
return;

int x,y;
int w,a,s,d;

char c;
//
// HOW TO MAKE THIS HERE? (i had done early in console application)
// but i can't do this in GUI , what should i do?

scanf("%c",&c);
if (c=='w')
{ x=-20; y=0; }
else if (c=='s')
{ x=20; y=0; }
else if (c=='a')
{ x=0; y=-20; }
else if(c=='d')
{ x=0; y=20; }

QPainterPath p = path();
p.lineTo(x, y);
setPath(p);
}
};

#include <QtGui/QApplication>
#include "dialog.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene s;
QGraphicsView v(&s);

QUpdatingPathIte item;
item.setPen(QPen(QColor("black")));
s.addItem(&item);
v.show();

QTimer *timer = new QTimer(&s);
timer->connect(timer, SIGNAL(timeout()), &s, SLOT(advance()));
timer->start(500);

return a.exec();
}

最佳答案

QGraphicsView继承自QWidget,因为它继承自QAbstractScrollArea。您应该创建一个 QGraphicsView 的自定义子类,并只覆盖函数 keyPressEvent()。示例:

class SnakeView : public QGraphicsView
{
protected:
keyPressEvent(QKeyEvent *e)
{
// Do something

// Otherwise pass to the graphics view
QGraphicsView::keyPressEvent(e)
}
};

然后创建一个 SnakeView 对象而不是创建一个 QGraphicsView 对象。

关于c++ - Qt 捕捉按下的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com