Home > front end >  How to get QWidget from QGraphicsScene item?
How to get QWidget from QGraphicsScene item?

Time:02-15

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
}

CodePudding user response:

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();
        }
    }
}
  • Related