[SOLVED] How to use signal to execute any function with arguments?



  • Suppose I have a QPropertyAnimator animating (moving), say, a button - slightly to the left over the course of 10 seconds.

    When the button reaches its destination on the other side of the window it should change its text to "banana" using the QLineEdit::setText() function.

    If the QLineEdit::setText() function is issued directly after the animation start;

    QPropertyAnimator *animator = new QPropertyAnimator(someButton, "pos");

    animator->setDuration(10000);
    animator->setStartValue(current position of the button);
    animator->setEndValue(current position of the button with x-100);
    animator->start();

    QLineEdit::setText(QString("Banana"));

    The text changes before it has the chance to start moving. Luckily, QPropertyAnimator emits a signal when the animation is completed - aptly titled finished().

    One would like to just be able to:

    connect(animator, SIGNAL(finished()), someButton, SLOT(setText("Banana")));

    But since you can't pass an argument to a slot that won't work.

    How do I change the text after the animation is complete without creating different "proxy" functions (slots) to do it without arguments? I've been told that C++11 can be used for this purpose. How would one be integrated?

    Kind regards,
    Oskar



  • I don't have a ready made solution for you, but your remark about c++11 got me thinking that maybe you should have a look at std::bind, something like:

    connect(animator, &QPropertyAnimator::finished, someButton, std::bind(&QPropertyAnimator::setText, animator, "Banana"))
    

  • Qt Champions 2016

    You could also

    add a function/slot to your main window
    like

    void Mainwin::WhatToDoonFinish() {
    ui->someButton->setText("Banana");
    }

    and then hook up the finished with that one
    connect(animator, SIGNAL(finished()), mainwindow, SLOT(WhatToDoonFinish()));

    Edit:
    Also you can have arguments but SetText is not a slot (as far as i know) and cannot be used as such.
    You could read about signal/slots here
    http://doc.qt.io/qt-5/signalsandslots.html
    It has example that use arguments.



  • Thanks for the responses!

    I managed to get it working by using the new QT connect() syntax in synergy with c++11 lambdas:

    connect(animator, &QPropertyAnimation::finished, [&] () {

    doSomething();

    });

    /Oskar


  • Qt Champions 2016

    @OskarPyke

    That is pretty cool.
    Looks a bit strange on first read when not used to lambdas that much :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.