A couple of questions about slots.

  • I have a couple of questions regarding slots. My first question deals with arguments. Is is not possible for a slot to take more than one argument? Take the following code snippet as an example;

    @#ifndef LIGHT_H
    #define LIGHT_H

    #include <QObject>

    class Light : public QObject
    Q_PROPERTY(bool light READ light WRITE setLight NOTIFY LightChanged)
    explicit Light(QObject *parent = 0);

    enum eLight {
        FrontPorch = 0,
        Garage = 1,
        LivingRoom = 2,
        BathRoom = 3,
        Kitchen = 4
    bool light(enum eLight whichlight);

    void LightChanged(enum eLight whichLight, bool on);

    public slots:
    void setLight(enum eLight light, bool on);

    #endif // LIGHT_H@

    I would like to perform something very similar to the following;

    Light light;
    light.setLight(Garage, true); // turn light on
    bool on = light.light(Kitchen); // query status of light

    While I compile the code it reports the following error;

    C:\temp\build-tester-Desktop_Qt_5_2_1_MinGW_32bit-Debug\debug\moc_light.cpp:159: error: no matching function for call to 'Light::setLight(bool&)'
    case 0: setLight(reinterpret_cast< bool>(_v)); break;

    My second question is dealing with argument validation from within the slot. How do you report errors on failed validations? Are you to throw an exception or return an error code? All the examples I have found have void as the return type. Take the following code as an example, it takes a parameter and makes sure it is 1 - 100;

    void SomeClass::setValue(int value)
    if (value < 1 || value > 100)
    // do what?
    someclassvalue = value;
    emit ValueChanged(value);

    Any help would be greatly appreciated.

  • Well after reading the documentation on the property system it appears #1 is not possible

    "Property System":https://qt-project.org/doc/qt-4.8/properties.html

    bq. A WRITE accessor function is optional. It is for setting the property value. It must return void and must take exactly one argument, either of the property's type or a pointer or reference to that type. e.g., QWidget::enabled has the WRITE function QWidget::setEnabled(). Read-only properties do not need WRITE functions. e.g., QWidget::focus has no WRITE function.

    So what about question #2, how do return an error on validation an exception?

  • Moderators

    Hi, and welcome to the Qt Dev Net!

    Because slots can be invoked asynchronously, returning error codes or throwing exceptions won't always work.

    In your slot, you can emit a signal to notify your program that an error has occurred. "QMediaPlayer":http://qt-project.org/doc/qt-5/qmediaplayer.html#error-2 does this, for example. If your program doesn't need to do anything special to handle the error, you could also just log an error message (see qDebug())

Log in to reply

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