Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Disabling narrowing conversions in signal/slot connections


class Sender : public QObject
{
    Q_OBJECT
signals:
    void signalWithInt(int i);
    void signalWithDouble(double d);
    void signalWithQString(QString s);
};

class Receiver : public QObject
{
    Q_OBJECT
public slots:
    void slotWithInt(int i);
    void slotWithDouble(double d);
    void slotWithQString(QString s);
    void slotWithQVariant(QVariant v);
};

Sender *s = new Sender;
Receiver *r = new Receiver;

connect(s, &Sender::signalWithInt,
        r, &Receiver::slotWithInt);        // works

connect(s, &Sender::signalWithDouble,
        r, &Receiver::slotWithDouble);     // works

connect(s, &Sender::signalWithQString,
        r, &Receiver::slotWithQString);    // works

connect(s, &Sender::signalWithInt,
        r, &Receiver::slotWithQString);   // does not compile

connect(s, &Sender::signalWithQString,
        r, &Receiver::slotWithInt);       // does not compile

connect(s, &Sender::signalWithDouble,
        r, &Receiver::slotWithQString);   // does not compile

connect(s, &Sender::signalWithQString,
        r, &Receiver::slotWithDouble);    // does not compile

connect(s, SIGNAL(signalWithInt(int)),
        r, SLOT(slotWithQString(QString)));  // compiles, fails at runtime

// using int -> double
connect(s, &Sender::signalWithInt,
        r, &Receiver::slotWithDouble);    // compiles and works as expected

// using the implicit QVariant(QString) ctor
connect(s, &Sender::signalWithQString,
        r, &Receiver::slotWithQVariant);  // compiles and works as expected

// double -> int conversion
connect(s, &Sender::signalWithDouble,
        r, &Receiver::slotWithInt);    // compiles and "works"

double d = 3.14;
int i = d;

double d = 3.14;
int i{d};

DEFINES += QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
# ... other DEFINES for your project ...

// under QT_NO_NARROWING_CONVERSIONS_IN_CONNECT defined

connect(s, &Sender::signalWithDouble,
        r, &Receiver::slotWithInt);    // does not compile!

About KDAB


2 Comments

12 - Apr - 2017

Tomaz Canabrava

12 - Apr - 2017

Giuseppe D'Angelo

GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer

Learn Modern C++

Learn more