How to add QLabel to QGraphicsItem
Asked Answered
L

3

5

I have a QGraphicsItem that has text on it. I want this text to be editable, so that if the user double-clicks it, it will enter an edit mode. It seems like the easiest way to do this would be to change the text into a QLineEdit and let the user click away the focus or press enter when they're done.

How can I add a QLineEdit to a QGraphicsItem? I have subclassed the QGraphicsItem so I have access to its internals.

Lemos answered 15/8, 2013 at 1:45 Comment(0)
M
11

To add any QWidget based object to a QGraphicsScene, a QGraphicsProxyWidget is required.

When you call the function addWidget on QGraphicsScene, it embeds the widget in a QGraphicsProxyWidget and returns that QGraphicsProxyWidget back to the caller.

The QGraphicsProxyWidget forwards events to its widget and handles conversion between the different coordinate systems.

Now that you're looking at using a QLineEdit in the QGraphicsScene, you need to decide if you want to add it directly:

QGraphicsScene* pScene = new QGraphicsScene;
QLineEdit* pLineEdit = new QLineEdit("Some Text");

// add the widget - internally, the QGraphicsProxyWidget is created and returned
QGraphicsProxyWidget* pProxyWidget = pScene->AddWidget(pLineEdit);

Or just add it to your current QGraphicsItem. Here, you can either add it as a child of the QGraphicsItem:

MyQGraphicsItem* pMyItem = new MyQGraphicsItem;
QGraphicsProxyWidget* pMyProxy = new QGraphicsProxyWidget(pMyItem); // the proxy's parent is pMyItem
pMyProxy->setWidget(pLineEdit); // adding the QWidget based object to the proxy

Or you could add the QGraphicsProxyWidget as a member of your class and call its relevant functions, but adding it as a child is probably much simpler.

Marguerita answered 15/8, 2013 at 7:53 Comment(0)
S
5
QGraphicsTextItem::setTextInteractionFlags (Qt::TextInteractionFlags flags)

API can be used. But you need to create QGraphicsTextItem inside it.

Please check following link for details: Implementation details

Smog answered 15/8, 2013 at 3:16 Comment(2)
@Lemos QLineEdit is a QWidget, so if you want QLineEdit instead of QGraphicsTextItem . Then better go diffrent approach already answered by "mhcuervo".Smog
this was actually a good answer since most overlook this functionality, and adding QWidgets and the associated proxy items is a whole other can of worms that you might not want to get into if you are looking for simplicity, not to mention overall performance.Amadaamadas
K
2

You need to create a proxy widget by extending QGraphicsProxyWidget in the case you need some specific behavior or just use a QGraphicsProxyWidget. Take a look at the "Embedded Dialogs" example in your Qt SDK and the QGraphicsProxyWidget documentation. It has been there for a long time so it should be for your version. I hope this helps.

Kynan answered 15/8, 2013 at 2:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.