How can I call a function when item in combobox changed?
Asked Answered
I

4

14
connect(ui->ComboBox,SIGNAL(currentIndexChanged()),this,SLOT(switchcall()));

in qt, combobox items i have none,server,client.when i select one of this it should call switchcall function.in this function i want to perform task depending upon choice in combobox.how to do it??

Imprudent answered 13/12, 2012 at 8:27 Comment(0)
T
22

You haven't put the args in the SIGNAL/SLOT statements.

connect(ui->ComboBox,SIGNAL(currentIndexChanged(const QString&)),
        this,SLOT(switchcall(const QString&)));

Alternatively you can use the item index, using the overloaded signal.

Tableland answered 13/12, 2012 at 8:34 Comment(2)
I don't see this overload, but there is a currentTextChanged signal in Qt 6.3Haiti
@Haiti this answer is almost 10 years old... doc.qt.io/archives/qt-4.8/qcombobox.html#currentIndex-propTableland
T
6

To get the index from QComboBox change event of QComboBox item use:

connect(ui->comboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(indexChanged(int)));

in mainwindow.h:

private slots:
    void indexChanged(int index);

in mainwindow.cpp:

void MainWindow::indexChanged(int index)
{
    // Do something here on ComboBox index change
}
Tripartition answered 2/9, 2019 at 6:57 Comment(0)
S
3

Based on the Qt documentations the QOverload<T>::of() helper function can be used to specify which overloaded signal you're using,

connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
    [=](int index){ /* ... */ });

Using this convenient helper there is no need to use the old SIGNAL() and SLOT() syntax.

Sola answered 6/9, 2020 at 3:47 Comment(0)
S
3

Use autoconnect:

void on_ComboBox_currentIndexChanged(int index);

Autoconnect template:

on_<control_name>_<signal_name>(<signal params>)
Styliform answered 22/4, 2021 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.