Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Connecting slider from one class to method in another



  • I am trying to connect a slider I have in my Window class (A) which contains a widget of my other class (B). I am struggling to understand how I can make it so if the slider is changed in A, I can call a function in class B that does something like this:

    A::A(){
    //constructor
    //create window
    ...
    Slider = new QSlider(Qt::Horizontal);
    window->addWidget(slider);
    //connect slider to slot from B sending slider value
    }

    B::doSomething(int value){
    //do something with value
    }

    How can I do this, which class would I need to include the slot in, would I need to call it on an instance etc


  • Lifetime Qt Champion

    Hi,

    B::soSomething shall be the slot.
    The connection happens between two instances not two classes.

    See the Signals and Slot chapter of Qt's documentation.



  • @John-Green said in Connecting slider from one class to method in another:

    Okay so I added the slot to B but it doesn't work, I added the Q_OBJECT macro but it can't find ClassB::doSomething because it tries to find ClassA::ClassB::doSomething. What do I need to change?
    Inside A's constructor
    QObject::connect(Slider, SIGNAL(valueChanged(int)), this, SLOT(ClassB::doSomething(int)));

    Inside Bs header file:
    Public Slots:
    void doSomething(int)

    Inside Bs cpp file:
    void B::doSomething(int number){
    //do something with number
    }


  • Lifetime Qt Champion

    The SLOT macro expects only the name of the slot. No class before.

    You should move to the new connection syntax. That will make the compilation fail if you don't create proper connection.


Log in to reply