#include "mygi.h"#include "mygig.h"#include <QtWidgets>int main(int argc, char *argv[]){ QApplication a(argc, argv); QGraphicsScene scene; scene.setSceneRect(0, 0, 500, 500); MyGIG* group = new MyGIG(); for ( int i = 0; i < 4; i++ ) { MyGI* item = new MyGI(); item->setPos(i*100, 0); group->addToGroup(item); qDebug() << item; } group->setFlag(QGraphicsItem::ItemIsMovable); scene.addItem(group); QGraphicsView view(&scene); view.show(); return a.exec();}
#ifndef MYGI_H#define MYGI_H#include <QGraphicsItem>class MyGI : public QGraphicsItem { public: MyGI(); ~MyGI(); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);};#endif // MYGI_H
#include "mygi.h"#include "ui_mygi.h"#include <QPainter>MyGI::MyGI() {}MyGI::~MyGI() {}QRectF MyGI::boundingRect() const { return QRectF(0, 0, 100, 100);}void MyGI::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setPen(Qt::black); painter->drawRect(0, 0, 100, 100);}
#ifndef MYGIG_H#define MYGIG_H#include <QGraphicsItemGroup>class MyGIG : public QGraphicsItemGroup { public: MyGIG(); void mouseReleaseEvent(QGraphicsSceneMouseEvent * event);};#endif // MYGIG_H
#include "mygig.h"#include <qdebug.h>MyGIG::MyGIG() {}void MyGIG::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { QGraphicsItemGroup::mouseReleaseEvent(event); for ( QList<QGraphicsItem*>::iterator it = childItems().begin(); it != childItems().end(); ++it ) { qDebug() << (*it); (*it)->moveBy(pos().x(), pos().y()); // Segmentation fault } setPos(0, 0);}
void MyGIG::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { for ( QList<QGraphicsItem*>::iterator it = childItems().begin(); it != childItems().end(); ++it ) { qDebug() << (*it); (*it)->moveBy(pos().x(), pos().y()); // Segmentation fault } setPos(0, 0); QGraphicsItemGroup::mouseReleaseEvent(event);}
QList<QGraphicsItem*> list = childItems();for (QList<QGraphicsItem*>::iterator iter = list.begin(); iter != list.end(); iter++ ) { qDebug() << (*iter); (*iter)->moveBy(pos().x(), pos().y());}