Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a QT C++ program. I have 3 forms that each have combo boxes to lookup customers. I have code for each form to populate the combo boxes. I want to reuse that code and put it own my own class. The problem is I cant access the combo box on the 3 separate forms. Can I pass the ui combo box to my class?
Posted

1 solution

This can be done passing the address of the combo box as pointer or reference.

Example:
void Customers::initComboBox(QComboBox *cb)
{
    // Optionally clear existing items
    cb.clear();
    for (int i = 0; i < m_itemCount; i++)
    {
        // Create the item string
        QString str = buildItemString(i);
        cb->addItem(str);
    }
}


Then call this from the constructors of the dialogs containing a customer combo box:
SomeDialog::SomeDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SomeDialog)
{
    ui->setupUi(this);

    Customers customers;
    // Assuming Customers has read in data in the constructor.
    // If not, call function to load data here:
    //customers.loadData();
    customers.initComboBox(ui->customerComboBox);
}


There is another solution by deriving a class from QComboBox that provides a setup function whith a parameter to your customer data and populates the box. Then change the dialog members to this type (using QtCreator or manually in the dialog header files) and call the setup function in the dialog contructors passing the Customers class.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900