[SOLVED] How to get QWidget from QGraphicsScene item?

Issue

I have added QTextEdit to QGraphicsScene.
How now to access the properties and methods of the widget?

QGraphicsScene scene;
QTextEdit *te=new QTextEdit();
scene.addWidget(te);

................................

foreach(auto item,scene.items()) {

    auto te=(QTextEdit*)item;
    auto isReadOnly=te->isReadOnly(); // Error
}

Solution

QGraphicsScene::addWidget returns a QGraphicsProxyWidget which, as its name suggests, acts as a proxy to the widget added (your QTextEdit in this case). So you can either save the proxy for use later…

QGraphicsScene scene;
auto *proxy = scene.addWidget(new QTextEdit);

or, when looping over items, use something like…

for (const auto *item: scene.items()) {
    if (const auto *proxy = dynamic_cast<const QGraphicsProxyWidget *>(item)) {
        if (const auto *te = dynamic_cast<const QTextEdit *>(proxy->widget())) {
            auto isReadOnly = te->isReadOnly();
        }
    }
}

Answered By – G.M.

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *