-1

How to convert string as qwidget in qt. Dynamically have to access.. Any other method is having to convert string to QWidget.

Sample code:

QWidget *widget1 = new QWidget();
QWidget *widget2 = new QWidget();

QPushButton *next = new QPushButton("next");
QPushButton *prev = new QPushButton("prev");

stack->addWidget(widget1);
stack->addWidget(widget2);

stack->setCurrentIndex(0);

QObject::connect(next, SIGNAL(clicked()), this, SLOT(NextBt()));

QObject::connect(prev, SIGNAL(clicked()), this, SLOT(PrevBt()));

void MainWindow::NextBt()
{

std::string str1 = "widget" + std::to_string(1);
QString str = str1.c_str();    // "widget1"

//How to implement QWidget object as conversion of String here.
//for dynamically i want to remove the already added widget.

stack->removeWidget(str);
str->deleteLater();
stack->setCurrentIndex(1);

}
Senthil Kumar
  • 562
  • 1
  • 6
  • 14

1 Answers1

1
QWidget *your_widget = parentWidget->findChild<QWidget *>("widget1");

if(your_widget != 0)
{
    //do whatever you want
}

See QObject::findChild():

Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. Omitting the name argument causes all object names to be matched...

Do not forget to set a parent for the widgets you want to find. It is also necessary set a name for the object. For example

QWidget *widget1 = new QWidget(this);
widget1->setObjectName("widget1");

You can check all the children of some widget using QObject::findChildren():

Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects...

You can also get access to objects' methods by strings, for example:

QMetaObject::invokeMethod(thread, "quit", // invoke the quit() method of QThread
                          Qt::QueuedConnection);

See QMetaObject::invokeMethod

Vladimir Bershov
  • 2,701
  • 2
  • 21
  • 51