将项目添加到QGraphicsScene中的两个错误

时间:2016-07-14 08:46:07

标签: c++ qt

我正在尝试使用qt开发一个项目,但我在向场景中添加项目时遇到了两个问题! 我有一个包含我的背景对象的类,它在构造函数中获取指向我的场景的指针。

  1. 我尝试过" scene-> addItem(this)"将背景添加到场景中。但是,在运行项目时,报告该项目已添加到场景中!这是我调用addItem的唯一地方。

  2. 我也在尝试创建几个类的新对象并将它们放在QList中。添加它们时,这些项目根本不会出现在场景中!

  3. 这是班级:

    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 *)的对象。

1 个答案:

答案 0 :(得分:0)

我会这样做,没时间检查它是否编译等等。把它作为半答案 - 但它仍然可以帮助你..

你的问题:

  1. 在Test类中不包含场景 - 这是架构错误, 你可以用更高的逻辑在其他地方做到这一点..
  2. 还将列表保留在Test类之外..或者我可能不理解你的意图
  3. 总是在构造函数中调用parent构造函数..有各种原因 - 请注意,当你有一个参数时,它可以被正确转换并调用父构造函数等。也许这会导致你的构造函数中出现问题,这些函数有指针参数可能被传递给QObject construcor的场景(然后使用显式关键字 - 然后更加安全) - 这些东西很棘手......当你有多个继承时,我建议总是像我一样手动调用父构造函数 - 同时检查{{3 }}
  4. 为什么要从QObject继承?保持你的逻辑超出图形类..我认为有一种方法如何处理没有信号的鼠标点击事件(但我现在懒于搜索)。
  5. -

    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());        
    }