page4
page4

Reputation: 125

How do I make a working volume slider in Qt?

I'm trying to make a volume slider that changes the volume of the player in QT but I can't get it to work.

This is a picture of my music player. Currently, when I slide the volume slider while music is playing, the volume does not change/update to the value of the slider.

enter image description here

These are snipets of the code I'm using for the volumeslider:

volumeSlider = new QSlider(Qt::Horizontal, this);
volumeSlider->setRange(0, 100);
volumeSlider->setFixedWidth(100);
volumeSlider->setValue(100);
player = new QMediaPlayer;

..

connect(volumeSlider, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int)));
connect(volumeSlider, SIGNAL(volumeChanged(int)), player, SLOT(setVolume(int)));

..

    int MainWindow::volume() const
{
    return volumeSlider->value();
}


void MainWindow::setVolume(int volume)
{
    player->setVolume(volume);
}

Upvotes: 0

Views: 4896

Answers (2)

Tay2510
Tay2510

Reputation: 5978

Eh...I mean just one line

connect(volumeSlider, SIGNAL(valueChanged(int)),player, SLOT(setVolume(int)));

and that's all you need to make it work.


Your original code:

connect(volumeSlider, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int)));
connect(volumeSlider, SIGNAL(volumeChanged(int)), player, SLOT(setVolume(int)));  
      //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error here

is wrong because there is no volumeChanged(int) signal in QSlider, and there should be some notification about failed connection from Qt Creator as you compiled the code (shown in the console of Qt Creator).

I guess the volumeChanged(int) is a custom signal defined in the main widget, and if you change the original code to

connect(volumeSlider, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int)));
connect(this, SIGNAL(volumeChanged(int)), player, SLOT(setVolume(int)));
     // ^^^^

and it should work because you connect A to B and then connect B to C, but it's verbose. Hence I asked you why not just connect A to C.

As for your last modification:

connect(volumeSlider, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int))); // Does nothing
connect(volumeSlider, SIGNAL(valueChanged(int)), player, SLOT(setVolume(int)));

It's like connect A to B, and connect A to C but only the connection of A to C works (mentioned above). The first connection is not necessary (since B is a SIGNAL)

Upvotes: 3

page4
page4

Reputation: 125

I'm dumb, it was as simple as changing:

connect(volumeSlider, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int)));
connect(volumeSlider, SIGNAL(volumeChanged(int)), player, SLOT(setVolume(int)));

to

connect(volumeSlider, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int)));
connect(volumeSlider, SIGNAL(valueChanged(int)), player, SLOT(setVolume(int)));

Thank you Tay2510: "Why not just connect valueChanged(int) to setVolume(int)? – Tay2510"

Upvotes: 0

Related Questions