我正在尝试使用qt开发一个项目,但我在向场景中添加项目时遇到了两个问题! 我有一个包含我的背景对象的类,它在构造函数中获取指向我的场景的指针。
我尝试过" scene-> addItem(this)"将背景添加到场景中。但是,在运行项目时,报告该项目已添加到场景中!这是我调用addItem的唯一地方。
我也在尝试创建几个类的新对象并将它们放在QList中。添加它们时,这些项目根本不会出现在场景中!
这是班级:
class Test : public QObject, public QGraphicsPixmapItem{
Q_OBJECT
public:
Test(QGraphicsScene *s){
scene = s;
setPixmap(QPixmap("a.jpg"));
setPos(0, 0);
scene->addItem(this);
}
void mousePressEvent(QGraphicsSceneMouseEvent *event){
list.push_back(new A(QPixmap("b.png")));
scene->addItem(list.back());
}
private:
QGraphicsScene *scene;
}
P.S。 A是继承B的类,它本身继承了公共QObject和公共QGraphicsPixmapItem。该列表还包含一些来自类型(B *)的对象。
答案 0 :(得分:0)
我会这样做,没时间检查它是否编译等等。把它作为半答案 - 但它仍然可以帮助你..
你的问题:
-
class Test : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
Test(QObject *qparent = 0, QGraphicsItem *parent = 0)
: QObject(qparent)
, QGraphicsPixmapItem(parent) {
setPixmap(QPixmap("a.jpg"));
setPos(0, 0);
}
void mousePressEvent(QGraphicsSceneMouseEvent *event) {
emit mousePressed();
}
signals:
void mousePressed();
}
然后在你的窗口类的某个地方:
WindowClass(etc) : Parent(etc) { //constructor
QGraphicsScene *scene = new ....;
Test *test = new Test(this, 0);//can be better, lazy to think of the details
connect(test, SIGNAL(mousePressed()), this, SLOT(on_testMousePressed());
scene->addItem(test);
}
void on_testMousePressed() {
list.push_back(new A(QPixmap("b.png")));
scene->addItem(list.back());
}