Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QComboBox connect

Tags:

qt

slot

qcombobox

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...!

like image 516
Jocala Avatar asked Dec 20 '22 07:12

Jocala


2 Answers

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))
);
like image 76
borisbn Avatar answered Dec 29 '22 00:12

borisbn


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);
}
like image 45
alediaferia Avatar answered Dec 29 '22 00:12

alediaferia