Search code examples
c++qtcomboboxsignals-slotsqspinbox

How to create a Qt Combobox


Hi would like to populate a QCombobox with a number of items which equals a variable set in a QSpinBox

When varying the QSpinbox value to N , then the combobox should show the same number of options numbered from 0 to N.

Is it possible to do it with a QObject::connect


Solution

  • You can use the signal QSpinBox::valueChanged ( int i ).

    Implement your own class which derives from QComboBox and create a slot which has the same signature as the signal.

    Something like:

    public Q_SLOTS:
    on_setItemsFromSpinBox( int i );
    

    Then you can connect the signal to the slot.

    connect( m_spinbox,
             SIGNAL(valueChanged(int)),
             m_my_combobox,
             SLOT(on_setItemsFromSpinBox(int)) );
    

    In the slot you clear the combobox (QComboBox::clear ()) and then use a loop in which you create as many items as specified by the integer you received in your slot from your signal.