New Signal Slot Syntax: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
[[Category:Developing_Qt::Qt Planning::Qt Public Roadmap]]<br />[toc align_right="yes" depth="3"]
[[Category:Developing_Qt::Qt Planning::Qt Public Roadmap]]
[toc align_right="yes" depth="3"]


= New Signal Slot Syntax in Qt 5 =
= New Signal Slot Syntax in Qt 5 =


This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt5.<br />* "Blog entry introducing it":http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html<br />* "How it works":http://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html (implementation details)
This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt5.
* "Blog entry introducing it":http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html
* "How it works":http://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html (implementation details)


'''Note''': This is in addition to the old string-based syntax which remains valid.
'''Note''': This is in addition to the old string-based syntax which remains valid.
Line 19: Line 22:
Qt5 will continue to support the "old string-based syntax":http://doc.qt.nokia.com/latest/qobject.html#connect for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget)
Qt5 will continue to support the "old string-based syntax":http://doc.qt.nokia.com/latest/qobject.html#connect for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget)


<code><br />connect(sender, SIGNAL (valueChanged(QString,QString)),<br /> receiver, SLOT (updateValue(QString)) );<br /></code>
<code>
connect(sender, SIGNAL (valueChanged(QString,QString)),
receiver, SLOT (updateValue(QString)) );
</code>


=== New: connecting to QObject member ===
=== New: connecting to QObject member ===
Line 25: Line 31:
Here's a new way to connect two QObjects and pass non-string objects:
Here's a new way to connect two QObjects and pass non-string objects:


<code><br />connect(sender, &amp;Sender::valueChanged,<br /> receiver, &amp;Receiver::updateValue );<br /></code>
<code>
connect(sender, &amp;Sender::valueChanged,
receiver, &amp;Receiver::updateValue );
</code>


==== pros ====
==== pros ====
Line 44: Line 53:
The new syntax can even connect to functions, not just QObjects:
The new syntax can even connect to functions, not just QObjects:


<code><br />connect(sender, &amp;Sender::valueChanged, someFunction);<br /></code>
<code>
connect(sender, &amp;Sender::valueChanged, someFunction);
</code>


==== pro ====
==== pro ====
Line 50: Line 61:
* can be used with tr1::bind
* can be used with tr1::bind
* can be used with c+''11 lambda expressions
* can be used with c+''11 lambda expressions
<br /><code><br />connect(sender, &amp;Sender::valueChanged,<br /> tr1::bind(receiver, &amp;Receiver::updateValue, "senderValue", tr1::placeholder::_1) );
<br />connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {<br /> receiver->updateValue("senderValue", newValue);<br /> } );<br /></code>
<br />h4. cons
<br />* There is no automatic disconnection when the 'receiver' is destroyed
<br />h2. Disconnecting in Qt5
<br />As you might expect, there are some changes in how connections can be terminated in Qt5, too.
<br />h3. Old way
<br />You can disconnect in the old way (using SIGNAL, SLOT) but only if
<br />* you connected using the old way, or<br />* if you want to disconnect all the slots from a given signal using wild card character
<br />h3. Symetric to the function pointer one
<br /><code><br />disconnect(sender, &amp;Sender::valueChanged,<br /> receiver, &amp;Receiver::updateValue );
<br /></code>
<br />Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card)<br />In particular, does not work with static function, functors or lambda functions.
<br />h3. New way using QMetaObject::Connection
<br /><code><br />QMetaObject::Connection m_connection;<br />//…<br />m_connection = QObject::connect(…);<br />//…<br />QObject::disconnect(m_connection);<br /></code>
<br />Works in all cases, including lambda functions or functors.


<br />h2. Asynchronous made easier.
<code>
<br />With C11 it is possible to keep the code inline
connect(sender, &amp;Sender::valueChanged,
tr1::bind(receiver, &amp;Receiver::updateValue, "senderValue", tr1::placeholder::_1) );


<br /><code><br />void doYourStuff(const QByteArray &amp;page)<br />{<br /> QTcpSocket '''socket = new QTcpSocket;<br /> socket->connectToHost("qt.nokia.com", 80);<br /> QObject::connect(socket, &amp;QTcpSocket::connected, [socket, page] () {<br /> socket->write(QByteArray("GET " + page + ""));<br /> });<br /> QObject::connect(socket, &amp;QTcpSocket::readyRead, [socket] () {<br /> qDebug()<< "GOT DATA "<< socket->readAll();<br /> });<br /> QObject::connect(socket, &amp;QTcpSocket::disconnected, [socket] () {<br /> qDebug()<< "DISCONNECTED ";<br /> socket->deleteLater();<br /> });
connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {
<br /> QObject::connect(socket, static_cast<void (QTcpSocket::''')(QAbstractSocket::SocketError)>(&amp;QAbstractSocket::error), [socket] (QAbstractSocket::SocketError) {<br /> qDebug()<< "ERROR " << socket->errorString();<br /> socket->deleteLater();<br /> });<br />}<br /></code>
receiver->updateValue("senderValue", newValue);
<br />Here's a QDialog without re-entering the eventloop, and keeping the code where it belongs:
} );
<br /><code><br />void Doc::saveDocument() {<br /> QFileDialog '''dlg = new QFileDialog();<br /> dlg->open();<br /> QObject::connect(dlg, &amp;QDialog::finished, [dlg, this](int result) {<br /> if (result) {<br /> QFile file(dlg->selectedFiles().first());<br /> // …<br /> }<br /> dlg->deleteLater();<br /> });
</code>
<br />}<br /></code>
<br />Another example using "QHttpServer":http://blog.nikhilmarathe.me/2011/02/qhttpserver-web-apps-in-qt.html : http://pastebin.com/pfbTMqUm


h4. cons


<br />h2. Error reporting
* There is no automatic disconnection when the 'receiver' is destroyed
<br />Tested with GCC.
 
<br />Fortunately, IDEs like Qt Creator simplifies the function naming
h2. Disconnecting in Qt5
<br />h3. forgot Q_OBJECT
 
<br /><code><br />#include <QtCore/QtCore><br />class Goo : public QObject {<br /> Goo() {<br /> connect(this, &amp;Goo::someSignal, this, &amp;QObject::deleteLater);<br /> }<br />signals:<br /> void someSignal();<br />};<br /></code>
As you might expect, there are some changes in how connections can be terminated in Qt5, too.
<br /><code><br />qobject.h: In member function 'void QObject::qt_check_for_QOBJECT_macro(const T&amp;amp;) const [with T = Goo]':<br />qobject.h:535:9: instantiated from 'static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void'''>::Type QObject::connect(const typename QtPrivate::FunctionPointer<Func>::Object*, Func1, const typename QtPrivate::FunctionPointer<Func2>::Object*, Func2, Qt::ConnectionType) [with Func1 = void (Goo::''')(), Func2 = void (QObject::''')(), typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type = void*, typename QtPrivate::FunctionPointer<Func>::Object = Goo, typename QtPrivate::FunctionPointer<Func2>::Object = QObject]'<br />main.cc:4:68: instantiated from here<br />qobject.h:353:5: error: void value not ignored as it ought to be<br />make: '''* [main.o] Error 1<br /></code>
 
<br />h3. Type mismatch
h3. Old way
<br /><code>
 
<br />#include <QtCore/QtCore><br />class Goo : public QObject {<br />Q_OBJECT<br />public:<br /> Goo() {<br /> connect(this, &amp;Goo::someSignal, this, &amp;Goo::someSlot1); //error<br /> connect(this, &amp;Goo::someSignal, this, &amp;Goo::someSlot2); //works<br /> }<br />signals:<br /> void someSignal(QString);<br />public:<br /> void someSlot1(int);<br /> void someSlot2(QVariant);<br />};<br /></code>
You can disconnect in the old way (using SIGNAL, SLOT) but only if
<br /><code><br />qobject.h: In static member function 'static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type QObject::connect(const typename QtPrivate::FunctionPointer<Func>::Object*, Func1, const typename QtPrivate::FunctionPointer<Func2>::Object*, Func2, Qt::ConnectionType) [with Func1 = void (Goo::''')(QString), Func2 = void (Goo::''')(int), typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type = void*, typename QtPrivate::FunctionPointer<Func>::Object = Goo, typename QtPrivate::FunctionPointer<Func2>::Object = Goo]':<br />main.cc:6:62: instantiated from here<br />qobject.h:538:163: error: no type named 'IncompatibleSignalSlotArguments' in 'struct QtPrivate::CheckCompatibleArguments<QtPrivate::List<QString, void>, QtPrivate::List<int, void>, true>'<br />qobject.h: In static member function 'static void QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::call(QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::Function, Obj*, void''') [with Args = QtPrivate::List<QString, void>, Obj = Goo, Ret = void, Arg1 = int, QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::Function = void (Goo::''')(int)]':<br />qobject.h:501:13: instantiated from 'void QObject::QSlotObject<Func, Args>::call(QObject*, void*''') [with Func = void (Goo::''')(int), Args = QtPrivate::List<QString, void>, QObject = QObject]'<br />main.cc:14:2: instantiated from here<br />qobject.h:109:13: error: cannot convert 'QtPrivate::RemoveRef<QString>::Type' to 'int' in argument passing<br />make: ''''''* [main.o] Error 1<br /></code>
 
<br />h2. Open Questions
* you connected using the old way, or
<br />h3. Default arguments in slot
* if you want to disconnect all the slots from a given signal using wild card character
<br />if you have code like this:
 
<br /><code><br />class A : public QObject { Q_OBJECT<br /> public slots:<br /> void someSlot(int foo = 0);<br />};<br /></code>
h3. Symetric to the function pointer one
<br />The old method allows you to connect that slot to a signal that does not have arguments.<br />But I cannot know with template code if a function has default arguments or not.<br />So this feature is disabled.
 
<br />There was an implementation that falls back to the old method if there are more arguments in the slot than in the signal.<br />This however is quite inconsistent, since the old method does not perform type-checking or type conversion. It was removed from the patch that has been merged.
<code>
<br />h3. Overload
disconnect(sender, &amp;Sender::valueChanged,
<br />As you might see in the example, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting.
receiver, &amp;Receiver::updateValue );
<br />Some macro could help (with c11 or ''typeof'' extensions)
 
<br />The best thing is probably to recommend not to overload signals or slots …
</code>
<br />… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.
 
<br />h3. Disconnect
Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card)
<br />Should QMetaObject::Connection have a disconnect() function?
In particular, does not work with static function, functors or lambda functions.
<br />The other problem is that there is no automatic disconnection for some object in the closure if we use the syntax that take a closure.<br />One could add a list of object in the disconnection, or a new function like QMetaObject::Connection::require
 
<br /><code><br />auto c = connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {<br /> receiver->updateValue("senderValue", newValue);<br /> } , QList<QObject> { receiver } ); // solution 1<br />c.require(receiver); // solution 2<br /></code>
h3. New way using QMetaObject::Connection
<br />h3. Callbacks
 
<br />Function such as QHostInfo::lookupHost or QTimer::singleShot or QFileDialog::open take a QObject receiver and char* slot.<br />This do not work for the new method.<br />If one wants to do callback c''+ way, one should use std::function (or tr1)<br />But we cannot use STL types in our ABI, so a QFunction should be done to copy std::function.<br />This is anyway irrelevant for QObject connections.
<code>
QMetaObject::Connection m_connection;
//…
m_connection = QObject::connect(…);
//…
QObject::disconnect(m_connection);
</code>
 
Works in all cases, including lambda functions or functors.
 
 
h2. Asynchronous made easier.
 
With C11 it is possible to keep the code inline
 
 
<code>
void doYourStuff(const QByteArray &amp;page)
{
QTcpSocket '''socket = new QTcpSocket;
socket->connectToHost("qt.nokia.com", 80);
QObject::connect(socket, &amp;QTcpSocket::connected, [socket, page] () {
socket->write(QByteArray("GET " + page + ""));
});
QObject::connect(socket, &amp;QTcpSocket::readyRead, [socket] () {
qDebug()<< "GOT DATA "<< socket->readAll();
});
QObject::connect(socket, &amp;QTcpSocket::disconnected, [socket] () {
qDebug()<< "DISCONNECTED ";
socket->deleteLater();
});
 
QObject::connect(socket, static_cast<void (QTcpSocket::''')(QAbstractSocket::SocketError)>(&amp;QAbstractSocket::error), [socket] (QAbstractSocket::SocketError) {
qDebug()<< "ERROR " << socket->errorString();
socket->deleteLater();
});
}
</code>
 
Here's a QDialog without re-entering the eventloop, and keeping the code where it belongs:
 
<code>
void Doc::saveDocument() {
QFileDialog '''dlg = new QFileDialog();
dlg->open();
QObject::connect(dlg, &amp;QDialog::finished, [dlg, this](int result) {
if (result) {
QFile file(dlg->selectedFiles().first());
//
}
dlg->deleteLater();
});
 
}
</code>
 
Another example using "QHttpServer":http://blog.nikhilmarathe.me/2011/02/qhttpserver-web-apps-in-qt.html : http://pastebin.com/pfbTMqUm
 
 
 
h2. Error reporting
 
Tested with GCC.
 
Fortunately, IDEs like Qt Creator simplifies the function naming
 
h3. forgot Q_OBJECT
 
<code>
#include <QtCore/QtCore>
class Goo : public QObject {
Goo() {
connect(this, &amp;Goo::someSignal, this, &amp;QObject::deleteLater);
}
signals:
void someSignal();
};
</code>
 
<code>
qobject.h: In member function 'void QObject::qt_check_for_QOBJECT_macro(const T&amp;amp;) const [with T = Goo]':
qobject.h:535:9: instantiated from 'static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void'''>::Type QObject::connect(const typename QtPrivate::FunctionPointer<Func>::Object*, Func1, const typename QtPrivate::FunctionPointer<Func2>::Object*, Func2, Qt::ConnectionType) [with Func1 = void (Goo::''')(), Func2 = void (QObject::''')(), typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type = void*, typename QtPrivate::FunctionPointer<Func>::Object = Goo, typename QtPrivate::FunctionPointer<Func2>::Object = QObject]'
main.cc:4:68: instantiated from here
qobject.h:353:5: error: void value not ignored as it ought to be
make: '''* [main.o] Error 1
</code>
 
h3. Type mismatch
 
<code>
 
#include <QtCore/QtCore>
class Goo : public QObject {
Q_OBJECT
public:
Goo() {
connect(this, &amp;Goo::someSignal, this, &amp;Goo::someSlot1); //error
connect(this, &amp;Goo::someSignal, this, &amp;Goo::someSlot2); //works
}
signals:
void someSignal(QString);
public:
void someSlot1(int);
void someSlot2(QVariant);
};
</code>
 
<code>
qobject.h: In static member function 'static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type QObject::connect(const typename QtPrivate::FunctionPointer<Func>::Object*, Func1, const typename QtPrivate::FunctionPointer<Func2>::Object*, Func2, Qt::ConnectionType) [with Func1 = void (Goo::''')(QString), Func2 = void (Goo::''')(int), typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type = void*, typename QtPrivate::FunctionPointer<Func>::Object = Goo, typename QtPrivate::FunctionPointer<Func2>::Object = Goo]':
main.cc:6:62: instantiated from here
qobject.h:538:163: error: no type named 'IncompatibleSignalSlotArguments' in 'struct QtPrivate::CheckCompatibleArguments<QtPrivate::List<QString, void>, QtPrivate::List<int, void>, true>'
qobject.h: In static member function 'static void QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::call(QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::Function, Obj*, void''') [with Args = QtPrivate::List<QString, void>, Obj = Goo, Ret = void, Arg1 = int, QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::Function = void (Goo::''')(int)]':
qobject.h:501:13: instantiated from 'void QObject::QSlotObject<Func, Args>::call(QObject*, void*''') [with Func = void (Goo::''')(int), Args = QtPrivate::List<QString, void>, QObject = QObject]'
main.cc:14:2: instantiated from here
qobject.h:109:13: error: cannot convert 'QtPrivate::RemoveRef<QString>::Type' to 'int' in argument passing
make: ''''''* [main.o] Error 1
</code>
 
h2. Open Questions
 
h3. Default arguments in slot
 
if you have code like this:
 
<code>
class A : public QObject { Q_OBJECT
public slots:
void someSlot(int foo = 0);
};
</code>
 
The old method allows you to connect that slot to a signal that does not have arguments.
But I cannot know with template code if a function has default arguments or not.
So this feature is disabled.
 
There was an implementation that falls back to the old method if there are more arguments in the slot than in the signal.
This however is quite inconsistent, since the old method does not perform type-checking or type conversion. It was removed from the patch that has been merged.
 
h3. Overload
 
As you might see in the example, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting.
 
Some macro could help (with c11 or ''typeof'' extensions)
 
The best thing is probably to recommend not to overload signals or slots …
 
… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.
 
h3. Disconnect
 
Should QMetaObject::Connection have a disconnect() function?
 
The other problem is that there is no automatic disconnection for some object in the closure if we use the syntax that take a closure.
One could add a list of object in the disconnection, or a new function like QMetaObject::Connection::require
 
<code>
auto c = connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {
receiver->updateValue("senderValue", newValue);
} , QList<QObject> { receiver } ); // solution 1
c.require(receiver); // solution 2
</code>
 
h3. Callbacks
 
Function such as QHostInfo::lookupHost or QTimer::singleShot or QFileDialog::open take a QObject receiver and char* slot.
This do not work for the new method.
If one wants to do callback c''+ way, one should use std::function (or tr1)
But we cannot use STL types in our ABI, so a QFunction should be done to copy std::function.
This is anyway irrelevant for QObject connections.


== History ==
== History ==

Revision as of 08:34, 25 February 2015

[toc align_right="yes" depth="3"]

New Signal Slot Syntax in Qt 5

This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt5.

Note: This is in addition to the old string-based syntax which remains valid.

Status

  • Already merged in qtbase/master

Connecting in Qt5

There will be several ways to connect a signal in Qt5.

Old syntax

Qt5 will continue to support the "old string-based syntax":http://doc.qt.nokia.com/latest/qobject.html#connect for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget)

connect(sender, SIGNAL (valueChanged(QString,QString)),
 receiver, SLOT (updateValue(QString)) );

New: connecting to QObject member

Here's a new way to connect two QObjects and pass non-string objects:

connect(sender, &amp;Sender::valueChanged,
 receiver, &amp;Receiver::updateValue );

pros

  • Compile time check of the existence of the signals and slot, of the types, or if the Q_OBJECT is missing.
  • Argument can be by typedefs or with different namespace specifier, and it works.
  • Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)
  • It is possible to connect to any member function of QObject, not only slots.

cons

  • More complicated syntax? (you need to specify the type of your object)
  • Very complicated syntax in cases of overloads?
  • Default arguments in slot is not supported anymore.

New: connecting to simple function

The new syntax can even connect to functions, not just QObjects:

connect(sender, &amp;Sender::valueChanged, someFunction);

pro

  • can be used with tr1::bind
  • can be used with c+11 lambda expressions
connect(sender, &amp;Sender::valueChanged,
 tr1::bind(receiver, &amp;Receiver::updateValue, "senderValue", tr1::placeholder::_1) );

connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {
 receiver->updateValue("senderValue", newValue);
 } );

h4. cons

  • There is no automatic disconnection when the 'receiver' is destroyed

h2. Disconnecting in Qt5

As you might expect, there are some changes in how connections can be terminated in Qt5, too.

h3. Old way

You can disconnect in the old way (using SIGNAL, SLOT) but only if

  • you connected using the old way, or
  • if you want to disconnect all the slots from a given signal using wild card character

h3. Symetric to the function pointer one

disconnect(sender, &amp;Sender::valueChanged,
 receiver, &amp;Receiver::updateValue );

Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card) In particular, does not work with static function, functors or lambda functions.

h3. New way using QMetaObject::Connection

QMetaObject::Connection m_connection;
//…
m_connection = QObject::connect();
//…
QObject::disconnect(m_connection);

Works in all cases, including lambda functions or functors.


h2. Asynchronous made easier.

With C11 it is possible to keep the code inline


void doYourStuff(const QByteArray &amp;page)
{
 QTcpSocket '''socket = new QTcpSocket;
 socket->connectToHost("qt.nokia.com", 80);
 QObject::connect(socket, &amp;QTcpSocket::connected, [socket, page] () {
 socket->write(QByteArray("GET " + page + ""));
 });
 QObject::connect(socket, &amp;QTcpSocket::readyRead, [socket] () {
 qDebug()<< "GOT DATA "<< socket->readAll();
 });
 QObject::connect(socket, &amp;QTcpSocket::disconnected, [socket] () {
 qDebug()<< "DISCONNECTED ";
 socket->deleteLater();
 });

 QObject::connect(socket, static_cast<void (QTcpSocket::''')(QAbstractSocket::SocketError)>(&amp;QAbstractSocket::error), [socket] (QAbstractSocket::SocketError) {
 qDebug()<< "ERROR " << socket->errorString();
 socket->deleteLater();
 });
}

Here's a QDialog without re-entering the eventloop, and keeping the code where it belongs:

void Doc::saveDocument() {
 QFileDialog '''dlg = new QFileDialog();
 dlg->open();
 QObject::connect(dlg, &amp;QDialog::finished, [dlg, this](int result) {
 if (result) {
 QFile file(dlg->selectedFiles().first());
 // …
 }
 dlg->deleteLater();
 });

}

Another example using "QHttpServer":http://blog.nikhilmarathe.me/2011/02/qhttpserver-web-apps-in-qt.html : http://pastebin.com/pfbTMqUm


h2. Error reporting

Tested with GCC.

Fortunately, IDEs like Qt Creator simplifies the function naming

h3. forgot Q_OBJECT

#include <QtCore/QtCore>
class Goo : public QObject {
 Goo() {
 connect(this, &amp;Goo::someSignal, this, &amp;QObject::deleteLater);
 }
signals:
 void someSignal();
};
qobject.h: In member function 'void QObject::qt_check_for_QOBJECT_macro(const T&amp;amp;) const [with T = Goo]':
qobject.h:535:9: instantiated from 'static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void'''>::Type QObject::connect(const typename QtPrivate::FunctionPointer<Func>::Object*, Func1, const typename QtPrivate::FunctionPointer<Func2>::Object*, Func2, Qt::ConnectionType) [with Func1 = void (Goo::''')(), Func2 = void (QObject::''')(), typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type = void*, typename QtPrivate::FunctionPointer<Func>::Object = Goo, typename QtPrivate::FunctionPointer<Func2>::Object = QObject]'
main.cc:4:68: instantiated from here
qobject.h:353:5: error: void value not ignored as it ought to be
make: '''* [main.o] Error 1

h3. Type mismatch

#include <QtCore/QtCore>
class Goo : public QObject {
Q_OBJECT
public:
 Goo() {
 connect(this, &amp;Goo::someSignal, this, &amp;Goo::someSlot1); //error
 connect(this, &amp;Goo::someSignal, this, &amp;Goo::someSlot2); //works
 }
signals:
 void someSignal(QString);
public:
 void someSlot1(int);
 void someSlot2(QVariant);
};
qobject.h: In static member function 'static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type QObject::connect(const typename QtPrivate::FunctionPointer<Func>::Object*, Func1, const typename QtPrivate::FunctionPointer<Func2>::Object*, Func2, Qt::ConnectionType) [with Func1 = void (Goo::''')(QString), Func2 = void (Goo::''')(int), typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer<Func>::ArgumentCount) >= (int)(QtPrivate::FunctionPointer<Func2>::ArgumentCount)), void*>::Type = void*, typename QtPrivate::FunctionPointer<Func>::Object = Goo, typename QtPrivate::FunctionPointer<Func2>::Object = Goo]':
main.cc:6:62: instantiated from here
qobject.h:538:163: error: no type named 'IncompatibleSignalSlotArguments' in 'struct QtPrivate::CheckCompatibleArguments<QtPrivate::List<QString, void>, QtPrivate::List<int, void>, true>'
qobject.h: In static member function 'static void QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::call(QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::Function, Obj*, void''') [with Args = QtPrivate::List<QString, void>, Obj = Goo, Ret = void, Arg1 = int, QtPrivate::FunctionPointer<Ret (Obj::''')(Arg1)>::Function = void (Goo::''')(int)]':
qobject.h:501:13: instantiated from 'void QObject::QSlotObject<Func, Args>::call(QObject*, void*''') [with Func = void (Goo::''')(int), Args = QtPrivate::List<QString, void>, QObject = QObject]'
main.cc:14:2: instantiated from here
qobject.h:109:13: error: cannot convert 'QtPrivate::RemoveRef<QString>::Type' to 'int' in argument passing
make: ''''''* [main.o] Error 1

h2. Open Questions

h3. Default arguments in slot

if you have code like this:

class A : public QObject { Q_OBJECT
 public slots:
 void someSlot(int foo = 0);
};

The old method allows you to connect that slot to a signal that does not have arguments. But I cannot know with template code if a function has default arguments or not. So this feature is disabled.

There was an implementation that falls back to the old method if there are more arguments in the slot than in the signal. This however is quite inconsistent, since the old method does not perform type-checking or type conversion. It was removed from the patch that has been merged.

h3. Overload

As you might see in the example, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting.

Some macro could help (with c11 or typeof extensions)

The best thing is probably to recommend not to overload signals or slots …

… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.

h3. Disconnect

Should QMetaObject::Connection have a disconnect() function?

The other problem is that there is no automatic disconnection for some object in the closure if we use the syntax that take a closure. One could add a list of object in the disconnection, or a new function like QMetaObject::Connection::require

auto c = connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {
 receiver->updateValue("senderValue", newValue);
 } , QList<QObject> { receiver } ); // solution 1
c.require(receiver); // solution 2

h3. Callbacks

Function such as QHostInfo::lookupHost or QTimer::singleShot or QFileDialog::open take a QObject receiver and char* slot. This do not work for the new method. If one wants to do callback c+ way, one should use std::function (or tr1) But we cannot use STL types in our ABI, so a QFunction should be done to copy std::function. This is anyway irrelevant for QObject connections.

History