【发布时间】:2020-08-18 07:07:14
【问题描述】:
我制作了一个简单的游戏来从其他矩形(MyRect 类)中拍摄矩形(Bullet 类)。我对'vtable for bullet'有错误未定义的引用。我已经写了与 Q_OBJECT 和 moc 相关的内容。我无法解决这个问题。
子弹.h
#ifndef BULLET_H
#define BULLET_H
#ifndef Q_MOC_RUN
#include <QGraphicsRectItem>
#include <QObject>
class Bullet: public QObject,public QGraphicsRectItem{
Q_OBJECT
public:
Bullet();
public slots:
void move();
};
#endif
#endif // BULLET_H
MyRect.h
#ifndef MYRECT_H
#define MYRECT_H
#include <QGraphicsRectItem>
class MyRect: public QGraphicsRectItem{
public:
void keyPressEvent(QKeyEvent* event);
};
#endif // MYRECT_H
子弹.cpp
#include "Bullet.h"
#include <QTimer>
Bullet::Bullet(){
setRect(0,0,10,50);
QTimer * timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(move()));
timer->start(50);
}
void Bullet::move(){
this->setPos(x(),y()-10);
}
main.cpp
#include <QApplication>
#include <QGraphicsScene>
#include "MyRect.h"
#include <QGraphicsView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene * scene = new QGraphicsScene();
MyRect * rect = new MyRect();
rect->setRect(0,0,100,100);
rect->setFlag(QGraphicsItem::ItemIsFocusable);
rect->setFocus();
scene->addItem(rect);
QGraphicsView * view = new QGraphicsView(scene);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->show();
return a.exec();
}
MyRect.cpp
#include "MyRect.h"
#include<QKeyEvent>
#include <QGraphicsScene>
#include "Bullet.h"
#include<QDebug>
void MyRect::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Left)
{
setPos(x()-10,y());
}
else if(event->key() == Qt::Key_Right)
{
setPos(x()+10,y());
}
else if(event->key() == Qt::Key_Up)
{
setPos(x(),y()-10);
}
else if(event->key() == Qt::Key_Down)
{
setPos(x(), y()+10);
}
else if(event->key() == Qt::Key_Space)
{
Bullet * bullet = new Bullet();
bullet->setPos(x(), y());
scene()->addItem(bullet);
}
}
我在Qt中写了一些类似的错误,但我仍然无法解决。非常感谢您的关注。
【问题讨论】:
-
qmake之后仍然出现错误? -
我没有改变 qmake。我定义了 q_moc_run。我没有错误,但我的矩形(项目符号)没有改变位置
-
我认为,那颗子弹虽然不是 MyRect,但我会 dd 图片(与子弹和 MyRect 不同)
-
不知道你为什么放
Q_MOC_RUN宏,删除它并测试,对我有用 -
最有可能:确保
Bullet.o包含在链接命令中。对 vtable 消息的未定义引用将胜过任何有关对Bullet的构造函数的未定义引用的消息。