c++qtcomboboxsignals-slotsqstringlistmodel

Loading QStringList value received from signal slot


In my qt c++ application a QStringList is sent from one cpp file(MainWIndow) to another cpp file(Dialog) via signal and slots mechanism! I want to display the elements in the qtringList on a combo box in the Dialog.ui when the interface gets loaded(no button click)!

following is my code

    #include "dialog.h"
    #include "ui_dialog.h"

    Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
    {
    ui->setupUi(this);

    for(int i=0;i<subMessages.size();i++){
    ui->comboBox->addItem(subMessages[i]);

    }
    }

//slot which is used to get the qstringList
    void Dialog::receiveSubMessages(QStringList List){ 
    subMessages=List;

    }

The QStringList is received successfully through the slot(already verified).Though I used a for loop and tried display (as in the code) nothing was displayed on the combo box! How can I fix this issue?


Solution

  • In order to get a working code you need to place your for llop inside you slot:

    #include "dialog.h"
    #include "ui_dialog.h"
    
    Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
    {
        ui->setupUi(this);
    }
    
    //slot which is used to get the qstringList
    void Dialog::receiveSubMessages(QStringList List){ 
        ui->comboBox->addItems (List);
    }
    

    If you want to fill the comboBox with the contents of some QStringList upon Dialog construction then you should either pass this list as constructor argument:

    Dialog::Dialog(QStringList List, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
    {
        ui->setupUi(this); 
        ui->comboBox->addItems (List);
    }
    

    or call Dialog::receiveSubMessages() right after Dialog object construction:

    // somewhere in code, where you construct Dialog object
    // ...
    auto parent = SomeQWidgetDerivedClass (...);
    QStringList someStringList {
        "string 1",
        "string 2"
    };
    // ...
    auto dialog {new Dialog ()};
    
    dialog->receiveSubMessages (someStringList);
    // ...
    

    The code that you have provided will never allow you to achieve the desired result because your for loop that is supposed to fill the QComboBox is executed on your Dialog object creation. At that point your subMessages is empty. The slot that you have created is not called before the constructor - the slot is just a member function that can only be called after the object is created. You can only call a member function without an object if the function itself is static, in which case it is definitely not a slot.