PDA

View Full Version : Qml QGrapicsObject type in QGraphicsScene



pkj
9th January 2013, 15:49
In Qt4.8 we can use to Qml to create QGraphicsObject as described in the documentation as :qml-integration.html#adding-qml-widgets-to-a-qgraphicsscene


QGraphicsScene* scene = myExistingGraphicsScene();
QDeclarativeEngine *engine = new QDeclarativeEngine;
QDeclarativeComponent component(engine, QUrl::fromLocalFile("myqml.qml"));
QGraphicsObject *object =
qobject_cast<QGraphicsObject *>(component.create());
scene->addItem(object);

I want the type() of QGraphicsItem in the QGraphicsObject i get from the factory function of QDeclarativeComponent to be set to something different from the default 'User' set in QGraphicsItem.
As described in the docs here qgraphicsitem.html#type I need to subclass the QgraphicsItem.
If I go ahead and do something like


class QmlObject : public QGraphicsObject{
Q_OBJECT
public:
enum {Type = TypeMyType;}//TypeMyType = UserType+1;
int type() const { return Type; }
QmlObject ();
}

QmlObject :: QmlObject () : QGraphicsObject()
{
QGraphicsScene* scene = myExistingGraphicsScene();
QDeclarativeEngine *engine = new QDeclarativeEngine;
QDeclarativeComponent component(engine, QUrl::fromLocalFile("myqml.qml"));
QGraphicsObject *object =
qobject_cast<QGraphicsObject *>(component.create());
scene->addItem(object);
//DEAD END HERE, can't change the embedded QGraphicsObject already initialized.
}

So if I go ahead by this route, since QObject is not copyable by Q_DISABLE_COPY, there is no way left for me to subclass it. And if I can't subclass it, I can't set the type of QGraphicsItem to something other than User.
AnyIdea how to go ahead and set the type of the QGraphicsItem?

wysota
9th January 2013, 16:39
You are trying to do something weird. The docs you mention are related to something completely different, there is no subclassing there. It is possible to do what you want but in a different way -- subclass QGraphicsObject to return your new type, then create a QML component using QDeclarativeEngine instance, then cast the resulting object to QGraphicsObject or QDeclarativeItem and set it as a child of your custom graphics object. Then just make sure the child always occupies the whole area of its parent (you can use QGraphicsLayout for this).

pkj
10th January 2013, 12:00
cast the resulting object to QGraphicsObject or QDeclarativeItem and set it as a child of your custom graphics object. Then just make sure the child always occupies the whole area of its parent (you can use QGraphicsLayout for this).
QGraphicsLayout only work for items which inherit QGraphicsLayoutItem. QGraphicsWidget does that. But not QDeclarativeItem. So I cannot use QGraphicsLayout. Is there another way in which the wrapper object for the QDeclarativeItem has a layout?

wysota
10th January 2013, 14:20
Then monitor the size yourself and resize the child when the parent changes size.