Important: Please read the Qt Code of Conduct -

[solved] QGraphicsItems from model?

  • Hello
    Is it possible to create QGraphicsItems from a model so that they would be added/deleted according to the model?
    I'd like to create software with a graphicsview, a listmodel and a "detail area" with some spinboxes and a combobox.

    The idea is that the listmodel would list all the graphicsviewitems (names, extracted from the model), the graphicsview naturally display the graphicsviewitems and the "detail area" would display information about the selected item (e.g. coordinates).

    My question is, can this be easily accomplished with a model architecture, or am I better of manipulating the separate fields manually? If it can be done with a model, any suggestions on how? The information related to the items are as follows:

    Name (QString)
    ID (int, possibly unnecessary)
    Coordinates (X,Y)
    Measurements (height, width)


  • It can be done using a Qt model (i.e. a subclass of QAbstractItemModel): it'll emit all the required signals when it changes, and you can use its API (rowCount, data, etc) to fetch and display the data. You can map the different values to roles or different columns of your model.

    That said, perhaps QML is a better and more robust choice?

  • ok. In that case it sounds like it might be easier for me to take the "traditional" item based way, as I already have most of this structure in place.

    One question though, if I use a listwidget, what's the best way of linking the items in the list to my "nodes"? I want each graphicsviewitem to be represented by one line in the list. It does not need to be the item itself only some reference with the restriction though that the name visible in the list might not be unique.


  • Yes, it can be done. You can make your QGraphicsView basically work as a QAbstractItemView. But it will be up to you to handle all that. I have build something like that in the past. The application had a tree view, a graphics view and a property editor all representing the same data store. They were all just different representations of the same thing.

    However, I am not sure that QAbstractItemModel is the right interface for all of this. In my case, I choose to give my data store a QAbstractItemModel interface, but that was not the only interface. It also supported an interface that made the property browser easy to implement, and an interface to support the graphics-view based representation.

Log in to reply