Important: Please read the Qt Code of Conduct -

Get widget from QTabWidget

  • Hi,

    I have created a "SectionsManager" class that publicly inherits from QTabWidget. I created a object of this class and a new tab:

    Section *section = new Section();
    addTab(section, section->getSectionName());

    "section" is an object of the Section class which inherits publicly from the Widget class. In the further part of the code I would like to get from the given tab about the index and extract the widget that I placed there earlier

    Section *section = ui->sectionManager->widget(index);

    however, it gets an error during compilation:
    "invalid conversion from 'QWidget' to 'Section'

    What could I do to fix it and be able to get from the given index of the tab the ptr of the object which I previously placed there

  • Section *section = qobject_cast<Section*>(ui->sectionManager->widget(index));

  • @Bonnie I did as you said and actually the code is compiling. However, I have a problem when I try use the methods of this object's class. The application is crashed.

    QString name = section->getSectionName();

    Do you know what could be the reason?

  • Probably because section equals nullptr.
    You should add some protection when you use the cast so that it won't crash.

    if(Section *section = qobject_cast<Section*>(ui->sectionManager->widget(index))) {
      QString name = section->getSectionName();

    Are you sure the result of ui->sectionManager->widget(index) is a Section?
    If section equals nullptr, that means it isn't.
    BTW, you can get the tab name by

    QString QTabWidget::tabText(int index) const

  • @Bonnie It's works, thanks

Log in to reply