情况:我Dialog
在 Qt 中有一堂课,我在上面画了一个正方形的栅格。正方形在MySquare
类中实现(MySquare:QGraphicsItem)。
问题:我想向 Dialog 槽发出信号,setTarget()
表明单击了一个正方形(显然我想给它一些关于该正方形的信息,例如稍后它的 x 和 y 坐标)。但是我得到一个“未定义的引用MySquare::targetChanged()
”错误。我一直在寻找解决方案,但没有找到任何解决方案;有人有想法吗?
编辑:我在 MySquare 中添加了一个 Q_OBJECT 宏,但是错误并没有消失,我得到一个额外的“'未定义引用' vtable for MySquare()
'错误
对话框.h
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public slots:
void setTarget();
private:
Ui::Dialog *ui;
QGraphicsScene *scene;
};
对话框.cpp
Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
MySquare *item;
item = new MySquare(30,30,30,30);
QObject::connect(item,SIGNAL(targetChanged()),this,SLOT(setTarget()));
}
void Dialog::setTarget(){
qDebug() << "signal recieved" << endl;
}
mysquare.h
#include <QGraphicsItem>
#include <QPainter>
#include <QDebug>
#include <QKeyEvent>
#include <QObject>
class MySquare : public QGraphicsItem, public QObject
{
Q_OBJECT
public:
MySquare(int x,int y,int h, int w);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
int x,y,h,w;
signals:
void targetChanged();
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
};
mysquare.cpp
#include "mysquare.h"
#include <QGraphicsSceneDragDropEvent>
#include <QWidget>
MySquare::MySquare(int _x,int _y, int _w, int _h)
{
setAcceptDrops(true);
color=Qt::red;
color_pressed = Qt::green;
x = _x;
y = _y;
w = _w;
h = _h;
}
QRectF MySquare::boundingRect() const
{
return QRectF(x,y,w,h);
}
void MySquare::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rec = boundingRect();
QBrush brush(color);
if (Pressed){
brush.setColor(color);
} else {
brush.setColor(color_pressed);
}
painter->fillRect(rec,brush);
painter->drawRect(rec);
}
void MySquare::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Pressed=true;
update();
QGraphicsItem::mousePressEvent(event);
emit targetChanged();
}
void MySquare::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Pressed=false;
update();
QGraphicsItem::mouseReleaseEvent(event);
qDebug() << "mouse Released";
}
void MySquare::mouseMoveEvent(QGraphicsSceneMouseEvent *event){
qDebug() << "mouse Moved";
QDrag *drag = new QDrag(event->widget());
QMimeData *mime = new QMimeData;
drag->setMimeData(mime);
drag->exec();
}
void MySquare::keyPressEvent(QKeyEvent *event){
//out of bounds check?
int x = pos().x();
int y = pos().y();
QGraphicsItem::keyPressEvent(event);
}