4

I need to call a function with currentIndex+1 when the currentIndex of a QComboBox changes. I'm struggling with the syntax this morning:

// call function readTables(int) when currentIndex changes.

connect(ui->deviceBox, SIGNAL(currentIndexChanged()),
   SLOT( readTables( ui->deviceBox->currentIndex()+1) );

error: expected ')' SLOT( readTables(ui->deviceBox->currentIndex()+1) );

Adding a closing ) won't work...!

Jocala
  • 243
  • 1
  • 4
  • 16
  • Write it as `connect(ui->deviceBox, SIGNAL(currentIndexChanged(int)), SLOT(readTables(int));`. The `readTables(int)` slot will be called with the current index as an argument. – vahancho Jan 21 '15 at 15:58
  • 1
    If you'll use Qt version 5+ and c++11, then you can write `connect(ui->deviceBox, SIGNAL(currentIndexChanged(int)), [this]( int idx ) { readTables( idx + 1 ); } );` – borisbn Jan 21 '15 at 16:00
  • 1
    I recommend you read the `Qt Signals and Slots` documentation: http://qt-project.org/doc/qt-4.8/signalsandslots.html – Iuliu Jan 21 '15 at 16:08

2 Answers2

10

First. If you can modify function readTables then you can just write:

connect(ui->deviceBox, SIGNAL(currentIndexChanged(int)), SLOT(readTables(int));

and in readTables

void MyClass::readTables( int idx ) {
    idx++;
    // do another stuff
}

Second: If you can use Qt 5+ and c++11, just write:

connect(ui->deviceBox, SIGNAL(currentIndexChanged(int)),
    [this]( int idx ) { readTables( idx + 1 ); }
);

Third: If you can't modify readTables and can't use c++11, write your own slot (say readTables_increment) like this:

void MyClass::readTables_increment( idx ) {
    readTables( idx + 1 );
}

and connect signal to it:

connect(ui->deviceBox, SIGNAL(currentIndexChanged(int)),
    SLOT(readTables_increment(int))
);
borisbn
  • 4,988
  • 25
  • 42
1

QComboBox::currentIndexChanged expects either a QString or a int as the single argument. You have 2 errors here:

  • you are not connecting to any existing signal since you specify currentIndexChanged() which does not exist
  • you are not passing a SLOT as the slot argument which requires the slot signature; rather, you are trying to pass an argument "on-the-fly" which is not something allowed.

@borisbn suggestion is pretty good if you are ok with using C++ lambdas. Otherwise you'll have to declare a new slot with an int argument:

void ThisClass::slotCurrentIndexChanged(int currentIndex) {
    ui->deviceBox->readTables(ui->deviceBox->currentIndex() + 1);
}
alediaferia
  • 2,537
  • 19
  • 22