QObject: add a macro for conveniently setting the object name

This is a simplified port of KDTools' KDAB_SET_OBJECT_NAME.
It simply assigns the variable name as the objectName of
a QObject, uic-style. It uses a small helper function so
that it works on references as well as pointer variables.

  QLabel label;
  QLabel *pLabel = new QLabel();
  Q_SET_OBJECT_NAME(label);
  Q_SET_OBJECT_NAME(pLabel);

Change-Id: I25fec0c90f33249a3ea5d2dd622ab708019fd101
Reviewed-by: Sean Harmer <sean.harmer@kdab.com>
Reviewed-by: David Faure <faure@kde.org>
Reviewed-by: Stephen Kelly <stephen.kelly@kdab.com>
Reviewed-by: Lars Knoll <lars.knoll@nokia.com>
This commit is contained in:
Marc Mutz 2012-07-04 17:18:22 +02:00 committed by Qt by Nokia
parent 06e8682cb7
commit 0e8279b7bc
3 changed files with 27 additions and 8 deletions

View File

@ -4022,6 +4022,19 @@ QDebug operator<<(QDebug dbg, const QObject *o) {
be invoked using QMetaObject::invokeMethod().
*/
/*!
\macro Q_SET_OBJECT_NAME(Object)
\relates QObject
\since 5.0
This macro assigns \a Object the objectName "Object".
It doesn't matter whether \a Object is a pointer or not, the
macro figures that out by itself.
\sa QObject::objectName()
*/
/*!
\typedef QObjectList
\relates QObject

View File

@ -524,6 +524,12 @@ template <class T> inline const char * qobject_interface_iid()
Q_CORE_EXPORT QDebug operator<<(QDebug, const QObject *);
#endif
namespace QtPrivate {
inline QObject & deref_for_methodcall(QObject &o) { return o; }
inline QObject & deref_for_methodcall(QObject *o) { return *o; }
}
#define Q_SET_OBJECT_NAME(obj) QT_PREPEND_NAMESPACE(QtPrivate)::deref_for_methodcall(obj).setObjectName(QLatin1String(#obj))
QT_END_NAMESPACE
QT_END_HEADER

View File

@ -563,14 +563,14 @@ void tst_QObject::findChildren()
QTimer t121(&o12);
QTimer emptyname(&o);
o.setObjectName("o");
o1.setObjectName("o1");
o2.setObjectName("o2");
o11.setObjectName("o11");
o12.setObjectName("o12");
o111.setObjectName("o111");
t1.setObjectName("t1");
t121.setObjectName("t121");
Q_SET_OBJECT_NAME(o);
Q_SET_OBJECT_NAME(o1);
Q_SET_OBJECT_NAME(o2);
Q_SET_OBJECT_NAME(o11);
Q_SET_OBJECT_NAME(o12);
Q_SET_OBJECT_NAME(o111);
Q_SET_OBJECT_NAME(t1);
Q_SET_OBJECT_NAME(t121);
emptyname.setObjectName("");
QObject *op = 0;