How Can I get the Current Text of a QComboBox in QGridLayout?

1

At the moment I have a create Slot that is called when a button is pressed. The Slot function needs to get all the data from the ComboBoxes in the QGridLayout above it. In the items above not all them have QComboBoxes. Some of them are QLineEdit and others are QLabel. My QgridLayout is called ui.testgridLayout.

for (int i = 0; i < ui.testgridLayout->rowCount(); i++)
{
    for (int j = 0; j < ui.testgridLayout->columnCount(); j++)
    {
        QLayoutItem *item= ui.testgridLayout->itemAtPosition(i, j);
        if (item) {
            if (strcmp(item->widget()->metaObject()->className(), "QComboBox")==0) {
                QString objName= item->widget()->objectName();
                QComboBox* cb =ui.testgridLayout->findChild<QComboBox*>(objName);
                string text = cb->currentText().toLocal8Bit().constData();
            }
        }
     }
  }

At the moment this returns Unhandled exception at 0x00007FFB107DCC8A (Qt5Widgets.dll) in ConfigFileCreation.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Any help or suggestions would be appreciated.

c++
qt
qcombobox
qgridlayout
asked on Stack Overflow Feb 6, 2020 by BDD • edited Feb 6, 2020 by BDD

1 Answer

1

The problem is that you are thinking that the widgets placed in the layout are children of the layout but no, those widgets are children of the widget where the layout was established, so in your code "cb" is a null pointer causing the problem. The solution is to cast and verify that the pointer is valid:

for (int i = 0; i < ui.testgridLayout->rowCount(); i++){
    for (int j = 0; j < ui.testgridLayout->columnCount(); j++){
        if (QLayoutItem *item= ui.testgridLayout->itemAtPosition(i, j)) {
            if (QComboBox* cb  = qobject_cast<QComboBox*>(item->widget())) {
                string text = cb->currentText().toLocal8Bit().constData();
            }
        }
    }
}
answered on Stack Overflow Feb 6, 2020 by eyllanesc

User contributions licensed under CC BY-SA 3.0