简体   繁体   中英

Connect an array to a signal slot mechanism in Qt

I created a QSlider *x_slider[8] array and now I want to create a connect to a slot like this,

connect(x_slider[0], SIGNAL(valueChanged(int)), this, SLOT(slider_x(int)));

but as I don't want to create a slot to every slider in the x_slider array the int received in slider_x slot should be in this case a 0.

How can I do that?, in the code I present it receives the int from ValueChanged

You can connect every QSlider from yours array, and then in your slot slider_x you can find out, what slider sent signal via sender() function. http://apidocs.meego.com/1.2/qt4/qobject.html#sender

Just loop through your array, and pointer to object, returned by sender() equals to QSlider in an array will mean, that you found your indice of an array.

Use a QSignalMapper :

auto sigMap = new QSignalMapper( this );
for ( int i = 0; i < 8; ++i ) {
    x_slider[i] = new QSlider( this );
    connect( x_slider[i], SIGNAL( valueChanged( int ) ),
             sigMap, SLOT( map() ) );

    sigMap->setMapping( x_slider[i], i );
}
connect( sigMap, SIGNAL( mapped( int ) ),
         this, SLOT( slider_x( int ) ) );

void MyClass::slider_x( int i )
{
    int value = x_slider[i]->value();
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM