Search code examples
c++qtsignals-slots

connecting signals and slots with different relations


First of all I'd say I'm a noob to GUI programming. I use Qt 5.4.

I came up with this code while watching voidRealms videos.

connect(ui->horizontalSlider,SIGNAL(sliderMoved(int)),ui->progressBar,SLOT(setValue(int)));

Obviously this connects slider movement with progressbar fill. This actually works like

progressbarfill <- slidermovement.

How can I make into a different relation? Like

progressbarfill <- (slidermovement)/2 or something like that.


Solution

  • You need to create new slot for that purpose. But in C++ 11 and Qt 5 style you can use lambdas! It is very comfortable for such short functions. In your case:

    connect(ui->horizontalSlider, &QSlider::sliderMoved, this, [this](int x) {
    this->ui->progressBar->setValue(x / 2);
    });