Detailed Description
The QObject class is the base class of all Qt objects.
QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect(). To avoid never ending notification loops you can temporarily block signals withblockSignals(). The protected functions connectNotify() and disconnectNotify() make it possible to track connections.
QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() orfindChildren().
Every object has an objectName() and its class name can be found via the corresponding metaObject() (seeQMetaObject::className()). You can determine whether the object's class inherits another class in the QObject inheritance hierarchy by using the inherits() function.
When an object is deleted, it emits a destroyed() signal. You can catch this signal to avoid dangling references to QObjects.
QObjects can receive events through event() and filter the events of other objects. See installEventFilter() andeventFilter() for details. A convenience handler, childEvent(), can be reimplemented to catch child events.
Events are delivered in the thread in which the object was created; see Thread Support in Qt and thread() for details. Note that event processing is not done at all for QObjects with no thread affinity (thread() returns zero). Use themoveToThread() function to change the thread affinity for an object and its children (the object cannot be moved if it has a parent).
Last but not least, QObject provides the basic timer support in Qt; see QTimer for high-level support for timers.
Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.
All Qt widgets inherit QObject. The convenience function isWidgetType() returns whether an object is actually a widget. It is much faster than qobject_cast<QWidget *>(obj) or obj->inherits("QWidget").
Some QObject functions, e.g. children(), return a QObjectList. QObjectList is a typedef for QList<QObject *>.
No copy constructor or assignment operator
QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.
The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.
Auto-Connection
Qt's meta-object system provides a mechanism to automatically connect signals and slots between QObject subclasses and their children. As long as objects are defined with suitable object names, and slots follow a simple naming convention, this connection can be performed at run-time by the QMetaObject::connectSlotsByName() function.
uic generates code that invokes this function to enable auto-connection to be performed between widgets on forms created with Qt Designer. More information about using auto-connection with Qt Designer is given in the Using a Designer UI File in Your Application section of the Qt Designer manual.
Dynamic Properties
From Qt 4.2, dynamic properties can be added to and removed from QObject instances at run-time. Dynamic properties do not need to be declared at compile-time, yet they provide the same advantages as static properties and are manipulated using the same API - using property() to read them and setProperty() to write them.
From Qt 4.3, dynamic properties are supported by Qt Designer, and both standard Qt widgets and user-created forms can be given dynamic properties.
Internationalization (i18n)
All QObject subclasses support Qt's translation features, making it possible to translate an application's user interface into different languages.
To make user-visible text translatable, it must be wrapped in calls to the tr() function. This is explained in detail in theWriting Source Code for Translation document.
See also QMetaObject, QPointer, QObjectCleanupHandler, Q_DISABLE_COPY(), and Object Trees & Ownership.
Property Documentation
objectName : QString
This property holds the name of this object.
You can find an object by name (and type) using findChild(). You can find a set of objects with findChildren().
qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
qPrintable(objectName()), newPrecision);
By default, this property contains an empty string.
Access functions:
QString | objectName() const |
void | setObjectName(const QString & name) |
Notifier signal:
void | objectNameChanged(const QString & objectName) |
See also metaObject() and QMetaObject::className().
Member Function Documentation
QObject::QObject(QObject * parent = 0)
Constructs an object with parent object parent.
The parent of an object may be viewed as the object's owner. For instance, a dialog box is the parent of the OK andCancel buttons it contains.
The destructor of a parent object destroys all child objects.
Setting parent to 0 constructs an object with no parent. If the object is a widget, it will become a top-level window.
See also parent(), findChild(), and findChildren().
QObject::~QObject() [virtual]
Destroys the object, deleting all its child objects.
All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to use deleteLater() rather than deleting a QObject subclass directly.
Warning: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash. We do not recommend holding pointers to child objects from outside the parent. If you still do, thedestroyed() signal gives you an opportunity to detect when an object is destroyed.
Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing. Use deleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.
See also deleteLater().
bool QObject::blockSignals(bool block)
If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). If block is false, no such blocking will occur.
The return value is the previous value of signalsBlocked().
Note that the destroyed() signal will be emitted even if the signals for this object have been blocked.
See also signalsBlocked().
void QObject::childEvent(QChildEvent * event) [virtual protected]
This event handler can be reimplemented in a subclass to receive child events. The event is passed in the eventparameter.
QEvent::ChildAdded and QEvent::ChildRemoved events are sent to objects when children are added or removed. In both cases you can only rely on the child being a QObject, or if isWidgetType() returns true, a QWidget. (This is because, in the ChildAdded case, the child is not yet fully constructed, and in the ChildRemoved case it might have been destructed already).
QEvent::ChildPolished events are sent to widgets when children are polished, or when polished children are added. If you receive a child polished event, the child's construction is usually completed. However, this is not guaranteed, and multiple polish events may be delivered during the execution of a widget's constructor.
For every child widget, you receive one ChildAdded event, zero or more ChildPolished events, and one ChildRemovedevent.
The ChildPolished event is omitted if a child is removed immediately after it is added. If a child is polished several times during construction and destruction, you may receive several child polished events for the same child, each time with a different virtual table.
See also event().
const QObjectList & QObject::children() const
Returns a list of child objects. The QObjectList class is defined in the <QObject> header file as the following:
typedef QList<QObject*> QObjectList;
The first child added is the first object in the list and the last child added is the last object in the list, i.e. new children are appended at the end.
Note that the list order changes when QWidget children are raised or lowered. A widget that is raised becomes the last object in the list, and a widget that is lowered becomes the first object in the list.
See also findChild(), findChildren(), parent(), and setParent().
QMetaObject::Connection QObject::connect(const QObject * sender, const char *signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection) [static]
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.
You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:
QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
label, SLOT(setNum(int)));
This example ensures that the label always displays the current scroll bar value. Note that the signal and slots parameters must not contain any variable names, only the type. E.g. the following would not work and return false:
// WRONG
QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
label, SLOT(setNum(int value)));
A signal can also be connected to another signal:
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget();
signals:
void buttonClicked();
private:
QPushButton *myButton;
};
MyWidget::MyWidget()
{
myButton = new QPushButton(this);
connect(myButton, SIGNAL(clicked()),
this, SIGNAL(buttonClicked()));
}
In this example, the MyWidget constructor relays a signal from a private member variable, and makes it available under a name that relates to MyWidget.
A signal can be connected to many slots and signals. Many signals can be connected to one slot.
If a signal is connected to several slots, the slots are activated in the same order in which the connections were made, when the signal is emitted.
The function returns a QMetaObject::Connection that represents a handle to a connection if it successfully connects the signal to the slot. The connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of either signal or method, or if their signatures aren't compatible. You can check if the handle is valid by casting it to a bool.
By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect() call. If you pass the Qt::UniqueConnection type, the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection.
The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message
QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)
call qRegisterMetaType() to register the data type before you establish the connection.
Note: This function is thread-safe.
See also disconnect(), sender(), qRegisterMetaType(), and Q_DECLARE_METATYPE().
QMetaObject::Connection QObject::connect(const QObject * sender, constQMetaMethod & signal, const QObject * receiver, const QMetaMethod & method,Qt::ConnectionType type = Qt::AutoConnection) [static]
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.
The Connection handle will be invalid if it cannot create the connection, for example, the parameters were invalid. You can check if the QMetaObject::Connection is valid by casting it to a bool.
This function works in the same way as connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type) but it uses QMetaMethod to specify signal and method.
This function was introduced in QtCore 4.8.
See also connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type).
QMetaObject::Connection QObject::connect(const QObject * sender, const char *signal, const char * method, Qt::ConnectionType type = Qt::AutoConnection) const
This function overloads connect().
Connects signal from the sender object to this object's method.
Equivalent to connect(sender, signal, this, method, type).
Every connection you make emits a signal, so duplicate connections emit two signals. You can break a connection usingdisconnect().
Note: This function is thread-safe.
See also disconnect().
QMetaObject::Connection QObject::connect(const QObject * sender,PointerToMemberFunction signal, const QObject * receiver,PointerToMemberFunction method, Qt::ConnectionType type) [static]
This function overloads connect().
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.
The signal must be a function declared as a signal in the header. The slot function can be any member function that can be connected to the signal. A slot can be connected to a given signal if the signal has at least as many arguments as the slot, and there is an implicit conversion between the types of the corresponding arguments in the signal and the slot.
Example:
QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
label, &QLabel::setText);
This example ensures that the label always displays the current line edit text.
A signal can be connected to many slots and signals. Many signals can be connected to one slot.
If a signal is connected to several slots, the slots are activated in the same order as the order the connection was made, when the signal is emitted
The function returns an handle to a connection if it successfully connects the signal to the slot. The Connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of signal (if it was not declared as a signal) You can check if the QMetaObject::Connection is valid by casting it to a bool.
By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect() call. If you pass the Qt::UniqueConnection type, the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection.
The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message
QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)
make sure to declare the argument type with Q_DECLARE_METATYPE
Note: This function is thread-safe.
QMetaObject::Connection QObject::connect(const QObject * sender,PointerToMemberFunction signal, Functor functor) [static]
This function overloads connect().
Creates a connection from signal in sender object to functor, and returns a handle to the connection
The signal must be a function declared as a signal in the header. The slot function can be any function or functor that can be connected to the signal. A function can be connected to a given signal if the signal as at least as many argument as the slot. A functor can be connected to a signal if they have exactly the same number of arguments. There must exist implicit conversion between the types of the corresponding arguments in the signal and the slot.
Example:
void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, someFunction);
If your compiler support C++11 lambda expressions, you can use them:
QByteArray page = ...;
QTcpSocket *socket = new QTcpSocket;
socket->connectToHost("qt-project.org", 80);
QObject::connect(socket, &QTcpSocket::connected, [=] () {
socket->write("GET " + page + "\r\n");
});
The connection will automatically disconnect if the sender is destroyed.
Note: This function is thread-safe.
void QObject::connectNotify(const QMetaMethod & signal) [virtual protected]
This virtual function is called when something has been connected to signal in this object.
If you want to compare signal with a specific signal, you can use QMetaMethod::fromSignal() as follows:
if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
// signal is valueChanged
}
Warning: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.
This function was introduced in QtCore 5.0.
See also connect() and disconnectNotify().
void QObject::customEvent(QEvent * event) [virtual protected]
This event handler can be reimplemented in a subclass to receive custom events. Custom events are user-defined events with a type value at least as large as the QEvent::User item of the QEvent::Type enum, and is typically a QEventsubclass. The event is passed in the event parameter.
void QObject::deleteLater() [slot]
Schedules this object for deletion.
The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.
Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.
Note: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.
See also destroyed() and QPointer.
void QObject::destroyed(QObject * obj = 0) [signal]
This signal is emitted immediately before the object obj is destroyed, and can not be blocked.
All the objects's children are destroyed immediately after this signal is emitted.
See also deleteLater() and QPointer.
bool QObject::disconnect(const QObject * sender, const char * signal, const QObject* receiver, const char * method) [static]
Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.
A signal-slot connection is removed when either of the objects involved are destroyed.
disconnect() is typically used in three ways, as the following examples demonstrate.
- Disconnect everything connected to an object's signals:
disconnect(myObject, 0, 0, 0);
equivalent to the non-static overloaded function
myObject->disconnect();
- Disconnect everything connected to a specific signal:
disconnect(myObject, SIGNAL(mySignal()), 0, 0);
equivalent to the non-static overloaded function
myObject->disconnect(SIGNAL(mySignal()));
- Disconnect a specific receiver:
disconnect(myObject, 0, myReceiver, 0);
equivalent to the non-static overloaded function
myObject->disconnect(myReceiver);
0 may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", respectively.
The sender may never be 0. (You cannot disconnect signals from more than one object in a single call.)
If signal is 0, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.
If receiver is 0, it disconnects anything connected to signal. If not, slots in objects other than receiver are not disconnected.
If method is 0, it disconnects anything that is connected to receiver. If not, only slots named method will be disconnected, and all other slots are left alone. The method must be 0 if receiver is left out, so you cannot disconnect a specifically-named slot on all objects.
Note: This function is thread-safe.
See also connect().
bool QObject::disconnect(const QObject * sender, const QMetaMethod & signal, constQObject * receiver, const QMetaMethod & method) [static]
Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.
This function provides the same possibilities like disconnect(const QObject *sender, const char *signal, const QObject*receiver, const char *method) but uses QMetaMethod to represent the signal and the method to be disconnected.
Additionally this function returnsfalse and no signals and slots disconnected if:
- signal is not a member of sender class or one of its parent classes.
- method is not a member of receiver class or one of its parent classes.
- signal instance represents not a signal.
QMetaMethod() may be used as wildcard in the meaning "any signal" or "any slot in receiving object". In the same way 0 can be used for receiver in the meaning "any receiving object". In this case method should also be QMetaMethod().sender parameter should be never 0.
This function was introduced in QtCore 4.8.
See also disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method).
bool QObject::disconnect(const QMetaObject::Connection & connection) [static]
Disconnect a connection.
If the connection is invalid or has already been disconnected, do nothing and return false.
See also connect().
bool QObject::disconnect(const char * signal = 0, const QObject * receiver = 0, constchar * method = 0) const
This function overloads disconnect().
Disconnects signal from method of receiver.
A signal-slot connection is removed when either of the objects involved are destroyed.
Note: This function is thread-safe.
bool QObject::disconnect(const QObject * receiver, const char * method = 0) const
This function overloads disconnect().
Disconnects all signals in this object from receiver's method.
A signal-slot connection is removed when either of the objects involved are destroyed.
bool QObject::disconnect(const QObject * sender, PointerToMemberFunction signal, const QObject * receiver, PointerToMemberFunction method) [static]
This function overloads diconnect().
Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.
A signal-slot connection is removed when either of the objects involved are destroyed.
disconnect() is typically used in three ways, as the following examples demonstrate.
- Disconnect everything connected to an object's signals:
disconnect(myObject, 0, 0, 0);
- Disconnect everything connected to a specific signal:
disconnect(myObject, &MyObject::mySignal(), 0, 0);
- Disconnect a specific receiver:
disconnect(myObject, 0, myReceiver, 0);
- Disconnect a connection from one specific signal to a specific slot:
QObject::disconnect(lineEdit, &QLineEdit::textChanged, label, &QLabel::setText);
0 may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", respectively.
The sender may never be 0. (You cannot disconnect signals from more than one object in a single call.)
If signal is 0, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.
If receiver is 0, it disconnects anything connected to signal. If not, slots in objects other than receiver are not disconnected.
If method is 0, it disconnects anything that is connected to receiver. If not, only slots named method will be disconnected, and all other slots are left alone. The method must be 0 if receiver is left out, so you cannot disconnect a specifically-named slot on all objects.
Note: It is not possible to use this overload to diconnect signals connected to functors or lambda expressions. That is because it is not possible to compare them. Instead, use the olverload that take a QMetaObject::Connection
Note: This function is thread-safe.
See also connect().
void QObject::disconnectNotify(const QMetaMethod & signal) [virtual protected]
This virtual function is called when something has been disconnected from signal in this object.
See connectNotify() for an example of how to compare signal with a specific signal.
If all signals were disconnected from this object (e.g., the signal argument to disconnect() was 0), disconnectNotify() is only called once, and the signal will be an invalid QMetaMethod (QMetaMethod::isValid() returns false).
Warning: This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.
This function was introduced in QtCore 5.0.
See also disconnect() and connectNotify().
void QObject::dumpObjectInfo()
Dumps information about signal connections, etc. for this object to the debug output.
This function is useful for debugging, but does nothing if the library has been compiled in release mode (i.e. without debugging information).
See also dumpObjectTree().
void QObject::dumpObjectTree()
Dumps a tree of children to the debug output.
This function is useful for debugging, but does nothing if the library has been compiled in release mode (i.e. without debugging information).
See also dumpObjectInfo().
QList<QByteArray> QObject::dynamicPropertyNames() const
Returns the names of all properties that were dynamically added to the object using setProperty().
This function was introduced in QtCore 4.2.
bool QObject::event(QEvent * e) [virtual]
This virtual function receives events to an object and should return true if the event e was recognized and processed.
The event() function can be reimplemented to customize the behavior of an object.
See also installEventFilter(), timerEvent(), QCoreApplication::sendEvent(), and QCoreApplication::postEvent().
bool QObject::eventFilter(QObject * watched, QEvent * event) [virtual]
Filters events if this object has been installed as an event filter for the watched object.
In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.
Example:
class MainWindow : public QMainWindow
{
public:
MainWindow();
protected:
bool eventFilter(QObject *obj, QEvent *ev);
private:
QTextEdit *textEdit;
};
MainWindow::MainWindow()
{
textEdit = new QTextEdit;
setCentralWidget(textEdit);
textEdit->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}
Notice in the example above that unhandled events are passed to the base class's eventFilter() function, since the base class might have reimplemented eventFilter() for its own internal purposes.
Warning: If you delete the receiver object in this function, be sure to return true. Otherwise, Qt will forward the event to the deleted object and the program might crash.
See also installEventFilter().
T QObject::findChild(const QString & name = QString(), Qt::FindChildOptions options= Qt::FindChildrenRecursively) const
Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. Omitting the name argument causes all object names to be matched. The search is performed recursively, unlessoptions specifies the option FindDirectChildrenOnly.
If there is more than one child matching the search, the most direct ancestor is returned. If there are several direct ancestors, it is undefined which one will be returned. In that case, findChildren() should be used.
This example returns a child QPushButton of parentWidget named "button1", even if the button isn't a direct child of the parent:
QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
This example returns a QListWidget child of parentWidget:
QListWidget *list = parentWidget->findChild<QListWidget *>();
This example returns a child QPushButton of parentWidget (its direct parent) named "button1":
QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildOnly);
This example returns a QListWidget child of parentWidget, its direct parent:
QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildOnly);
See also findChildren().
QList<T> QObject::findChildren(const QString & name = QString(),Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. Omitting the name argument causes all object names to be matched. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.
The following example shows how to find a list of child QWidgets of the specified parentWidget named widgetname:
QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");
This example returns all QPushButtons that are children of parentWidget:
QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();
This example returns all QPushButtons that are immediate children of parentWidget:
QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildOnly);
See also findChild().
QList<T> QObject::findChildren(const QRegExp & regExp, Qt::FindChildOptions options= Qt::FindChildrenRecursively) const
This function overloads findChildren().
Returns the children of this object that can be cast to type T and that have names matching the regular expressionregExp, or an empty list if there are no such objects. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.
QList<T> QObject::findChildren(const QRegularExpression & re, Qt::FindChildOptionsoptions = Qt::FindChildrenRecursively) const
This function overloads findChildren().
Returns the children of this object that can be cast to type T and that have names matching the regular expression re, or an empty list if there are no such objects. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.
This function was introduced in QtCore 5.0.
bool QObject::inherits(const char * className) const
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inheritsclassName; otherwise returns false.
A class is considered to inherit itself.
Example:
QTimer *timer = new QTimer; // QTimer inherits QObject
timer->inherits("QTimer"); // returns true
timer->inherits("QObject"); // returns true
timer->inherits("QAbstractButton"); // returns false
// QVBoxLayout inherits QObject and QLayoutItem
QVBoxLayout *layout = new QVBoxLayout;
layout->inherits("QObject"); // returns true
layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)
If you need to determine whether an object is an instance of a particular class for the purpose of casting it, consider using qobject_cast<Type *>(object) instead.
See also metaObject() and qobject_cast().
void QObject::installEventFilter(QObject * filterObj)
Installs an event filter filterObj on this object. For example:
monitoredObj->installEventFilter(filterObj);
An event filter is an object that receives all events that are sent to this object. The filter can either stop the event or forward it to this object. The event filter filterObj receives events via its eventFilter() function. The eventFilter() function must return true if the event should be filtered, (i.e. stopped); otherwise it must return false.
If multiple event filters are installed on a single object, the filter that was installed last is activated first.
Here's a KeyPressEater class that eats the key presses of its monitored objects:
class KeyPressEater : public QObject
{
Q_OBJECT
...
protected:
bool eventFilter(QObject *obj, QEvent *event);
};
bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug("Ate key press %d", keyEvent->key());
return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
And here's how to install it on two widgets:
KeyPressEater *keyPressEater = new KeyPressEater(this);
QPushButton *pushButton = new QPushButton(this);
QListView *listView = new QListView(this);
pushButton->installEventFilter(keyPressEater);
listView->installEventFilter(keyPressEater);
The QShortcut class, for example, uses this technique to intercept shortcut key presses.
Warning: If you delete the receiver object in your eventFilter() function, be sure to return true. If you return false, Qt sends the event to the deleted object and the program will crash.
Note that the filtering object must be in the same thread as this object. If filterObj is in a different thread, this function does nothing. If either filterObj or this object are moved to a different thread after calling this function, the event filter will not be called until both objects have the same thread affinity again (it is not removed).
See also removeEventFilter(), eventFilter(), and event().
bool QObject::isSignalConnected(const QMetaMethod & signal) const [protected]
Returns true if the signal is connected to at least one receiver, otherwise returns false.
signal must be a signal member of this object, otherwise the behaviour is undefined.
static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
if (isSignalConnected(valueChangedSignal)) {
QByteArray data;
data = get_the_value(); // expensive operation
emit valueChanged(data);
}
As the code snippet above illustrates, you can use this function to avoid emitting a signal that nobody listens to.
Warning: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.
This function was introduced in QtCore 5.0.
bool QObject::isWidgetType() const
Returns true if the object is a widget; otherwise returns false.
Calling this function is equivalent to calling inherits("QWidget"), except that it is much faster.
bool QObject::isWindowType() const
Returns true if the object is a window; otherwise returns false.
Calling this function is equivalent to calling inherits("QWindow"), except that it is much faster.
void QObject::killTimer(int id)
Kills the timer with timer identifier, id.
The timer identifier is returned by startTimer() when a timer event is started.
See also timerEvent() and startTimer().
const QMetaObject * QObject::metaObject() const [virtual]
Returns a pointer to the meta-object of this object.
A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have a meta-object.
The meta-object information is required by the signal/slot connection mechanism and the property system. Theinherits() function also makes use of the meta-object.
If you have no pointer to an actual object instance but still want to access the meta-object of a class, you can usestaticMetaObject.
Example:
QObject *obj = new QPushButton;
obj->metaObject()->className(); // returns "QPushButton"
QPushButton::staticMetaObject.className(); // returns "QPushButton"
See also staticMetaObject.
void QObject::moveToThread(QThread * targetThread)
Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.
To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives. For example:
myObject->moveToThread(QApplication::instance()->thread());
If targetThread is zero, all event processing for this object and its children stops.
Note that all active timers for the object will be reset. The timers are first stopped in the current thread and restarted (with the same interval) in the targetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.
A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in thetargetThread.
Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.
See also thread().
QObject * QObject::parent() const
Returns a pointer to the parent object.
See also setParent() and children().
QVariant QObject::property(const char * name) const
Returns the value of the object's name property.
If no such property exists, the returned variant is invalid.
Information about all available properties is provided through the metaObject() and dynamicPropertyNames().
See also setProperty(), QVariant::isValid(), metaObject(), and dynamicPropertyNames().
int QObject::receivers(const char * signal) const [protected]
Returns the number of receivers connected to the signal.
Since both slots and signals can be used as receivers for signals, and the same connections can be made many times, the number of receivers is the same as the number of connections made from this signal.
When calling this function, you can use the SIGNAL() macro to pass a specific signal:
if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
QByteArray data;
get_the_value(&data); // expensive operation
emit valueChanged(data);
}
Warning: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.
See also isSignalConnected().
void QObject::removeEventFilter(QObject * obj)
Removes an event filter object obj from this object. The request is ignored if such an event filter has not been installed.
All event filters for this object are automatically removed when this object is destroyed.
It is always safe to remove an event filter, even during event filter activation (i.e. from the eventFilter() function).
See also installEventFilter(), eventFilter(), and event().
QObject * QObject::sender() const [protected]
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. The pointer is valid only during the execution of the slot that calls this function from this object's thread context.
The pointer returned by this function becomes invalid if the sender is destroyed, or if the slot is disconnected from the sender's signal.
Warning: This function violates the object-oriented principle of modularity. However, getting access to the sender might be useful when many signals are connected to a single slot.
Warning: As mentioned above, the return value of this function is not valid when the slot is called via aQt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.
See also senderSignalIndex() and QSignalMapper.
int QObject::senderSignalIndex() const [protected]
Returns the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender(). If called outside of a slot activated by a signal, -1 is returned.
For signals with default parameters, this function will always return the index with all parameters, regardless of which was used with connect(). For example, the signal destroyed(QObject *obj = 0) will have two different indexes (with and without the parameter), but this function will always return the index with a parameter. This does not apply when overloading signals with different parameters.
Warning: This function violates the object-oriented principle of modularity. However, getting access to the signal index might be useful when many signals are connected to a single slot.
Warning: The return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.
This function was introduced in QtCore 4.8.
See also sender(), QMetaObject::indexOfSignal(), and QMetaObject::method().
void QObject::setParent(QObject * parent)
Makes the object a child of parent.
See also parent() and children().
bool QObject::setProperty(const char * name, const QVariant & value)
Sets the value of the object's name property to value.
If the property is defined in the class using Q_PROPERTY then true is returned on success and false otherwise. If the property is not defined using Q_PROPERTY, and therefore not listed in the meta-object, it is added as a dynamic property and false is returned.
Information about all available properties is provided through the metaObject() and dynamicPropertyNames().
Dynamic properties can be queried again using property() and can be removed by setting the property value to an invalid QVariant. Changing the value of a dynamic property causes a QDynamicPropertyChangeEvent to be sent to the object.
Note: Dynamic properties starting with "_q_" are reserved for internal purposes.
See also property(), metaObject(), and dynamicPropertyNames().
bool QObject::signalsBlocked() const
Returns true if signals are blocked; otherwise returns false.
Signals are not blocked by default.
See also blockSignals().
int QObject::startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer)
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.
A timer event will occur every interval milliseconds until killTimer() is called. If interval is 0, then the timer event occurs once every time there are no more window system events to process.
The virtual timerEvent() function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events.
If multiple timers are running, the QTimerEvent::timerId() can be used to find out which timer was activated.
Example:
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject(QObject *parent = 0);
protected:
void timerEvent(QTimerEvent *event);
};
MyObject::MyObject(QObject *parent)
: QObject(parent)
{
startTimer(50); // 50-millisecond timer
startTimer(1000); // 1-second timer
startTimer(60000); // 1-minute timer
}
void MyObject::timerEvent(QTimerEvent *event)
{
qDebug() << "Timer ID:" << event->timerId();
}
Note that QTimer's accuracy depends on the underlying operating system and hardware. The timerType argument allows you to customize the accuracy of the timer. See Qt::TimerType for information on the different timer types. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.
The QTimer class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also a QBasicTimer class that is more lightweight than QTimer and less clumsy than using timer IDs directly.
See also timerEvent(), killTimer(), and QTimer::singleShot().
QThread * QObject::thread() const
Returns the thread in which the object lives.
See also moveToThread().
void QObject::timerEvent(QTimerEvent * event) [virtual protected]
This event handler can be reimplemented in a subclass to receive timer events for the object.
QTimer provides a higher-level interface to the timer functionality, and also more general information about timers. The timer event is passed in the event parameter.
See also startTimer(), killTimer(), and event().
QString QObject::tr(const char * sourceText, const char * disambiguation = 0, int n = -1) [static]
Returns a translated version of sourceText, optionally based on a disambiguation string and value of n for strings containing plurals; otherwise returns sourceText itself if no appropriate translated string is available.
Example:
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
...
If the same sourceText is used in different roles within the same context, an additional identifying string may be passed in disambiguation (0 by default). In Qt 4.4 and earlier, this was the preferred way to pass comments to translators.
Example:
MyWindow::MyWindow()
{
QLabel *senderLabel = new QLabel(tr("Name:"));
QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
...
See Writing Source Code for Translation for a detailed description of Qt's translation mechanisms in general, and theDisambiguation section for information on disambiguation.
Warning: This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.
See also trUtf8(), QCoreApplication::translate(), and Internationalization with Qt.
Member Variable Documentation
const QMetaObject QObject::staticMetaObject
This variable stores the meta-object for the class.
A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every class that contains the Q_OBJECT macro will also have a meta-object.
The meta-object information is required by the signal/slot connection mechanism and the property system. Theinherits() function also makes use of the meta-object.
If you have a pointer to an object, you can use metaObject() to retrieve the meta-object associated with that object.
Example:
QPushButton::staticMetaObject.className(); // returns "QPushButton"
QObject *obj = new QPushButton;
obj->metaObject()->className(); // returns "QPushButton"
See also metaObject().
Related Non-Members
typedef QObjectList
QList<T> qFindChildren(const QObject * obj, const QRegExp & regExp)
This function overloads qFindChildren().
This function is equivalent to obj->findChildren<T>(regExp).
Note: This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also QObject::findChildren().
T qobject_cast(QObject * object)
Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.
The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.
A class is considered to inherit itself.
Example:
QObject *obj = new QTimer; // QTimer inherits QObject
QTimer *timer = qobject_cast<QTimer *>(obj);
// timer == (QObject *)obj
QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
// button == 0
The qobject_cast() function behaves similarly to the standard C++ dynamic_cast(), with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.
qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details.
Warning: If T isn't declared with the Q_OBJECT macro, this function's return value is undefined.
See also QObject::inherits().
Macro Documentation
Q_CLASSINFO( Name, Value)
This macro associates extra information to the class, which is available using QObject::metaObject(). Except for the ActiveQt extension, Qt doesn't use this information.
The extra information takes the form of a Name string and a Value literal string.
Example:
class MyClass : public QObject
{
Q_OBJECT
Q_CLASSINFO("Author", "Pierre Gendron")
Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")
public:
...
};
See also QMetaObject::classInfo().
Q_DISABLE_COPY( Class)
Disables the use of copy constructors and assignment operators for the given Class.
Instances of subclasses of QObject should not be thought of as values that can be copied or assigned, but as unique identities. This means that when you create your own subclass of QObject (director or indirect), you should not give it a copy constructor or an assignment operator. However, it may not enough to simply omit them from your class, because, if you mistakenly write some code that requires a copy constructor or an assignment operator (it's easy to do), your compiler will thoughtfully create it for you. You must do more.
The curious user will have seen that the Qt classes derived from QObject typically include this macro in a private section:
class MyClass : public QObject
{
private:
Q_DISABLE_COPY(MyClass)
};
It declares a copy constructor and an assignment operator in the private section, so that if you use them by mistake, the compiler will report an error.
class MyClass : public QObject
{
private:
MyClass(const MyClass &);
MyClass &operator=(const MyClass &);
};
But even this might not catch absolutely every case. You might be tempted to do something like this:
QWidget w = QWidget();
First of all, don't do that. Most compilers will generate code that uses the copy constructor, so the privacy violation error will be reported, but your C++ compiler is not required to generate code for this statement in a specific way. It could generate code using neither the copy constructor nor the assignment operator we made private. In that case, no error would be reported, but your application would probably crash when you called a member function of w.
Q_EMIT
Use this macro to replace the emit keyword for emitting signals, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.
The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.
Q_ENUMS(...)
This macro registers one or several enum types to the meta-object system.
For example:
class MyClass : public QObject
{
Q_OBJECT
Q_ENUMS(Priority)
public:
MyClass(QObject *parent = 0);
~MyClass();
enum Priority { High, Low, VeryHigh, VeryLow };
void setPriority(Priority priority);
Priority priority() const;
};
If you want to register an enum that is declared in another class, the enum must be fully qualified with the name of the class defining it. In addition, the class defining the enum has to inherit QObject as well as declare the enum using Q_ENUMS().
See also Qt's Property System.
Q_FLAGS(...)
This macro registers one or several flags types to the meta-object system. It is typically used in a class definition to declare that values of a given enum can be used as flags and combined using the bitwise OR operator.
For example, in QLibrary, the LoadHints flag is declared in the following way:
class QLibrary : public QObject
{
...
Q_FLAGS(LoadHint LoadHints)
...
The declaration of the flags themselves is performed in the public section of the QLibrary class itself, using theQ_DECLARE_FLAGS() macro:
...
public:
enum LoadHint {
ResolveAllSymbolsHint = 0x01,
ExportExternalSymbolsHint = 0x02,
LoadArchiveMemberHint = 0x04
};
Q_DECLARE_FLAGS(LoadHints, LoadHint)
...
Note: This macro takes care of registering individual flag values with the meta-object system, so it is unnecessary to use Q_ENUMS() in addition to this macro.
See also Qt's Property System.
Q_INTERFACES(...)
This macro tells Qt which interfaces the class implements. This is used when implementing plugins.
Example:
class BasicToolsPlugin : public QObject,
public BrushInterface,
public ShapeInterface,
public FilterInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.Examples.PlugAndPaint.BrushInterface" FILE "basictools.json")
Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)
public:
...
};
See the Plug & Paint Basic Tools example for details.
See also Q_DECLARE_INTERFACE(), Q_PLUGIN_METADATA(), and How to Create Qt Plugins.
Q_INVOKABLE
Apply this macro to definitions of member functions to allow them to be invoked via the meta-object system. The macro is written before the return type, as shown in the following example:
class Window : public QWidget
{
Q_OBJECT
public:
Window();
void normalMethod();
Q_INVOKABLE void invokableMethod();
};
The invokableMethod() function is marked up using Q_INVOKABLE, causing it to be registered with the meta-object system and enabling it to be invoked using QMetaObject::invokeMethod(). Since normalMethod() function is not registered in this way, it cannot be invoked using QMetaObject::invokeMethod().
Q_OBJECT
The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system.
For example:
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
Note: This macro requires the class to be a subclass of QObject. Use Q_GADGET instead of Q_OBJECT to enable the meta object system's support for enums in a class that is not a QObject subclass. Q_GADGET makes a class member,staticMetaObject, available. staticMetaObject is of type QMetaObject and provides access to the enums declared with Q_ENUMS. Q_GADGET is provided only for C++.
See also Meta-Object System, Signals and Slots, and Qt's Property System.
Q_PROPERTY(...)
This macro is used for declaring properties in classes that inherit QObject. Properties behave like class data members, but they have additional features accessible through the Meta-Object System.
Q_PROPERTY(type name
READ getFunction
[WRITE setFunction]
[RESET resetFunction]
[NOTIFY notifySignal]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool]
[CONSTANT]
[FINAL])
The property name and type and the READ function are required. The type can be any type supported by QVariant, or it can be a user-defined type. The other items are optional, but a WRITE function is common. The attributes default to true except USER, which defaults to false.
For example:
Q_PROPERTY(QString title READ title WRITE setTitle USER true)
For more details about how to use this macro, and a more detailed example of its use, see the discussion on Qt's Property System.
See also Qt's Property System.
Q_SET_OBJECT_NAME( Object)
This macro assigns Object the objectName "Object".
It doesn't matter whether Object is a pointer or not, the macro figures that out by itself.
This function was introduced in QtCore 5.0.
See also QObject::objectName().
Q_SIGNAL
This is an additional macro that allows you to mark a single function as a signal. It can be quite useful, especially when you use a 3rd-party source code parser which doesn't understand a signals or Q_SIGNALS groups.
Use this macro to replace the signals keyword in class declarations, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.
Q_SIGNALS
Use this macro to replace the signals keyword in class declarations, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.
Q_SLOT
This is an additional macro that allows you to mark a single function as a slot. It can be quite useful, especially when you use a 3rd-party source code parser which doesn't understand a slots or Q_SLOTS groups.
Use this macro to replace the slots keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.
The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.
Q_SLOTS
Use this macro to replace the slots keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.
The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.
QMetaObject Class
The QMetaObject class contains meta-information about Qt objects.More...
#include <QMetaObject>
Public Functions
QMetaClassInfo | classInfo(int index) const |
int | classInfoCount() const |
int | classInfoOffset() const |
const char * | className() const |
QMetaMethod | constructor(int index) const |
int | constructorCount() const |
QMetaEnum | enumerator(int index) const |
int | enumeratorCount() const |
int | enumeratorOffset() const |
int | indexOfClassInfo(const char * name) const |
int | indexOfConstructor(const char * constructor) const |
int | indexOfEnumerator(const char * name) const |
int | indexOfMethod(const char * method) const |
int | indexOfProperty(const char * name) const |
int | indexOfSignal(const char * signal) const |
int | indexOfSlot(const char * slot) const |
QMetaMethod | method(int index) const |
int | methodCount() const |
int | methodOffset() const |
QObject * | newInstance(QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) const |
QMetaProperty | property(int index) const |
int | propertyCount() const |
int | propertyOffset() const |
const QMetaObject * | superClass() const |
QMetaProperty | userProperty() const |
Static Public Members
bool | checkConnectArgs(const char * signal, const char * method) |
bool | checkConnectArgs(const QMetaMethod & signal, const QMetaMethod & method) |
void | connectSlotsByName(QObject * object) |
bool | invokeMethod(QObject * obj, const char * member, Qt::ConnectionType type, QGenericReturnArgumentret, QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) |
bool | invokeMethod(QObject * obj, const char * member, QGenericReturnArgument ret, QGenericArgumentval0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2= QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) |
bool | invokeMethod(QObject * obj, const char * member, Qt::ConnectionType type, QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) |
bool | invokeMethod(QObject * obj, const char * member, QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) |
QByteArray | normalizedSignature(const char * method) |
QByteArray | normalizedType(const char * type) |
Macros
QGenericArgument | Q_ARG( Type, const Type & value) |
QGenericReturnArgument | Q_RETURN_ARG( Type, Type & value) |
Detailed Description
The QMetaObject class contains meta-information about Qt objects.
The Qt Meta-Object System in Qt is responsible for the signals and slots inter-object communication mechanism, runtime type information, and the Qt property system. A single QMetaObject instance is created for each QObjectsubclass that is used in an application, and this instance stores all the meta-information for the QObject subclass. This object is available as QObject::metaObject().
This class is not normally required for application programming, but it is useful if you write meta-applications, such as scripting engines or GUI builders.
The functions you are most likely to find useful are these:
- className() returns the name of a class.
- superClass() returns the superclass's meta-object.
- method() and methodCount() provide information about a class's meta-methods (signals, slots and other invokablemember functions).
- enumerator() and enumeratorCount() and provide information about a class's enumerators.
- propertyCount() and property() provide information about a class's properties.
- constructor() and constructorCount() provide information about a class's meta-constructors.
The index functions indexOfConstructor(), indexOfMethod(), indexOfEnumerator(), and indexOfProperty() map names of constructors, member functions, enumerators, or properties to indexes in the meta-object. For example, Qt usesindexOfMethod() internally when you connect a signal to a slot.
Classes can also have a list of name--value pairs of additional class information, stored in QMetaClassInfo objects. The number of pairs is returned by classInfoCount(), single pairs are returned by classInfo(), and you can search for pairs with indexOfClassInfo().
See also QMetaClassInfo, QMetaEnum, QMetaMethod, QMetaProperty, QMetaType, and Meta-Object System.
Member Function Documentation
bool QMetaObject::checkConnectArgs(const char * signal, const char * method)[static]
Returns true if the signal and method arguments are compatible; otherwise returns false.
Both signal and method are expected to be normalized.
See also normalizedSignature().
bool QMetaObject::checkConnectArgs(const QMetaMethod & signal, constQMetaMethod & method) [static]
This is an overloaded function.
Returns true if the signal and method arguments are compatible; otherwise returns false.
This function was introduced in QtCore 5.0.
QMetaClassInfo QMetaObject::classInfo(int index) const
Returns the meta-data for the item of class information with the given index.
Example:
class MyClass : public QObject
{
Q_OBJECT
Q_CLASSINFO("author", "Sabrina Schweinsteiger")
Q_CLASSINFO("url", "http://doc.moosesoft.co.uk/1.0/")
public:
...
};
See also classInfoCount(), classInfoOffset(), and indexOfClassInfo().
int QMetaObject::classInfoCount() const
Returns the number of items of class information in this class.
See also classInfo(), classInfoOffset(), and indexOfClassInfo().
int QMetaObject::classInfoOffset() const
Returns the class information offset for this class; i.e. the index position of this class's first class information item.
If the class has no superclasses with class information, the offset is 0; otherwise the offset is the sum of all the class information items in the class's superclasses.
See also classInfo(), classInfoCount(), and indexOfClassInfo().
const char * QMetaObject::className() const
Returns the class name.
See also superClass().
void QMetaObject::connectSlotsByName(QObject * object) [static]
Searches recursively for all child objects of the given object, and connects matching signals from them to slots of objectthat follow the following form:
void on_<object name>_<signal name>(<signal parameters>);
Let's assume our object has a child object of type QPushButton with the object name button1. The slot to catch the button's clicked() signal would be:
void on_button1_clicked();
See also QObject::setObjectName().
QMetaMethod QMetaObject::constructor(int index) const
Returns the meta-data for the constructor with the given index.
This function was introduced in QtCore 4.5.
See also constructorCount() and newInstance().
int QMetaObject::constructorCount() const
Returns the number of constructors in this class.
This function was introduced in QtCore 4.5.
See also constructor() and indexOfConstructor().
QMetaEnum QMetaObject::enumerator(int index) const
Returns the meta-data for the enumerator with the given index.
See also enumeratorCount(), enumeratorOffset(), and indexOfEnumerator().
int QMetaObject::enumeratorCount() const
Returns the number of enumerators in this class.
See also enumerator(), enumeratorOffset(), and indexOfEnumerator().
int QMetaObject::enumeratorOffset() const
Returns the enumerator offset for this class; i.e. the index position of this class's first enumerator.
If the class has no superclasses with enumerators, the offset is 0; otherwise the offset is the sum of all the enumerators in the class's superclasses.
See also enumerator(), enumeratorCount(), and indexOfEnumerator().
int QMetaObject::indexOfClassInfo(const char * name) const
Finds class information item name and returns its index; otherwise returns -1.
See also classInfo(), classInfoCount(), and classInfoOffset().
int QMetaObject::indexOfConstructor(const char * constructor) const
Finds constructor and returns its index; otherwise returns -1.
Note that the constructor has to be in normalized form, as returned by normalizedSignature().
This function was introduced in QtCore 4.5.
See also constructor(), constructorCount(), and normalizedSignature().
int QMetaObject::indexOfEnumerator(const char * name) const
Finds enumerator name and returns its index; otherwise returns -1.
See also enumerator(), enumeratorCount(), and enumeratorOffset().
int QMetaObject::indexOfMethod(const char * method) const
Finds method and returns its index; otherwise returns -1.
Note that the method has to be in normalized form, as returned by normalizedSignature().
See also method(), methodCount(), methodOffset(), and normalizedSignature().
int QMetaObject::indexOfProperty(const char * name) const
Finds property name and returns its index; otherwise returns -1.
See also property(), propertyCount(), and propertyOffset().
int QMetaObject::indexOfSignal(const char * signal) const
Finds signal and returns its index; otherwise returns -1.
This is the same as indexOfMethod(), except that it will return -1 if the method exists but isn't a signal.
Note that the signal has to be in normalized form, as returned by normalizedSignature().
See also indexOfMethod(), normalizedSignature(), method(), methodCount(), and methodOffset().
int QMetaObject::indexOfSlot(const char * slot) const
Finds slot and returns its index; otherwise returns -1.
This is the same as indexOfMethod(), except that it will return -1 if the method exists but isn't a slot.
See also indexOfMethod(), method(), methodCount(), and methodOffset().
bool QMetaObject::invokeMethod(QObject * obj, const char * member,Qt::ConnectionType type, QGenericReturnArgument ret, QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(),QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(),QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(),QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) [static]
Invokes the member (a signal or a slot name) on the object obj. Returns true if the member could be invoked. Returns false if there is no such member or the parameters did not match.
The invocation can be either synchronous or asynchronous, depending on type:
- If type is Qt::DirectConnection, the member will be invoked immediately.
- If type is Qt::QueuedConnection, a QEvent will be sent and the member is invoked as soon as the application enters the main event loop.
- If type is Qt::BlockingQueuedConnection, the method will be invoked in the same way as for Qt::QueuedConnection, except that the current thread will block until the event is delivered. Using this connection type to communicate between objects in the same thread will lead to deadlocks.
- If type is Qt::AutoConnection, the member is invoked synchronously if obj lives in the same thread as the caller; otherwise it will invoke the member asynchronously.
The return value of the member function call is placed in ret. If the invocation is asynchronous, the return value cannot be evaluated. You can pass up to ten arguments (val0, val1, val2, val3, val4, val5, val6, val7, val8, and val9) to themember function.
QGenericArgument and QGenericReturnArgument are internal helper classes. Because signals and slots can be dynamically invoked, you must enclose the arguments using the Q_ARG() and Q_RETURN_ARG() macros. Q_ARG() takes a type name and a const reference of that type; Q_RETURN_ARG() takes a type name and a non-const reference.
You only need to pass the name of the signal or slot to this function, not the entire signature. For example, to asynchronously invoke the quit() slot on a QThread, use the following code:
QMetaObject::invokeMethod(thread, "quit",
Qt::QueuedConnection);
With asynchronous method invocations, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message
QMetaObject::invokeMethod: Unable to handle unregistered datatype 'MyType'
call qRegisterMetaType() to register the data type before you call invokeMethod().
To synchronously invoke the compute(QString, int, double) slot on some arbitrary object obj retrieve its return value:
QString retVal;
QMetaObject::invokeMethod(obj, "compute", Qt::DirectConnection,
Q_RETURN_ARG(QString, retVal),
Q_ARG(QString, "sqrt"),
Q_ARG(int, 42),
Q_ARG(double, 9.7));
If the "compute" slot does not take exactly one QString, one int and one double in the specified order, the call will fail.
See also Q_ARG(), Q_RETURN_ARG(), qRegisterMetaType(), and QMetaMethod::invoke().
bool QMetaObject::invokeMethod(QObject * obj, const char * member,QGenericReturnArgument ret, QGenericArgument val0 = QGenericArgument( 0 ),QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(),QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(),QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) [static]
This function overloads invokeMethod().
This overload always invokes the member using the connection type Qt::AutoConnection.
bool QMetaObject::invokeMethod(QObject * obj, const char * member,Qt::ConnectionType type, QGenericArgument val0 = QGenericArgument( 0 ),QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(),QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(),QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) [static]
This function overloads invokeMethod().
This overload can be used if the return value of the member is of no interest.
bool QMetaObject::invokeMethod(QObject * obj, const char * member,QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(),QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(),QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(),QGenericArgument val9 = QGenericArgument()) [static]
This function overloads invokeMethod().
This overload invokes the member using the connection type Qt::AutoConnection and ignores return values.
QMetaMethod QMetaObject::method(int index) const
Returns the meta-data for the method with the given index.
See also methodCount(), methodOffset(), and indexOfMethod().
int QMetaObject::methodCount() const
Returns the number of methods in this class, including the number of methods provided by each base class. These include signals and slots as well as normal member functions.
Use code like the following to obtain a QStringList containing the methods specific to a given class:
const QMetaObject* metaObject = obj->metaObject();
QStringList methods;
for(int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i)
methods << QString::fromLatin1(metaObject->method(i).methodSignature());
See also method(), methodOffset(), and indexOfMethod().
int QMetaObject::methodOffset() const
Returns the method offset for this class; i.e. the index position of this class's first member function.
The offset is the sum of all the methods in the class's superclasses (which is always positive since QObject has the deleteLater() slot and a destroyed() signal).
See also method(), methodCount(), and indexOfMethod().
QObject * QMetaObject::newInstance(QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(),QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(),QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument()) const
Constructs a new instance of this class. You can pass up to ten arguments (val0, val1, val2, val3, val4, val5, val6, val7,val8, and val9) to the constructor. Returns the new object, or 0 if no suitable constructor is available.
Note that only constructors that are declared with the Q_INVOKABLE modifier are made available through the meta-object system.
This function was introduced in QtCore 4.5.
See also Q_ARG() and constructor().
QByteArray QMetaObject::normalizedSignature(const char * method) [static]
Normalizes the signature of the given method.
Qt uses normalized signatures to decide whether two given signals and slots are compatible. Normalization reduces whitespace to a minimum, moves 'const' to the front where appropriate, removes 'const' from value types and replaces const references with values.
See also checkConnectArgs() and normalizedType().
QByteArray QMetaObject::normalizedType(const char * type) [static]
Normalizes a type.
See QMetaObject::normalizedSignature() for a description on how Qt normalizes.
Example:
QByteArray normType = QMetaObject::normalizedType(" int const *");
// normType is now "const int*"
This function was introduced in QtCore 4.2.
See also normalizedSignature().
QMetaProperty QMetaObject::property(int index) const
Returns the meta-data for the property with the given index. If no such property exists, a null QMetaProperty is returned.
See also propertyCount(), propertyOffset(), and indexOfProperty().
int QMetaObject::propertyCount() const
Returns the number of properties in this class, including the number of properties provided by each base class.
Use code like the following to obtain a QStringList containing the properties specific to a given class:
const QMetaObject* metaObject = obj->metaObject();
QStringList properties;
for(int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); ++i)
properties << QString::fromLatin1(metaObject->property(i).name());
See also property(), propertyOffset(), and indexOfProperty().
int QMetaObject::propertyOffset() const
Returns the property offset for this class; i.e. the index position of this class's first property.
The offset is the sum of all the properties in the class's superclasses (which is always positive since QObject has the name() property).
See also property(), propertyCount(), and indexOfProperty().
const QMetaObject * QMetaObject::superClass() const
Returns the meta-object of the superclass, or 0 if there is no such object.
See also className().
QMetaProperty QMetaObject::userProperty() const
Returns the property that has the USER flag set to true.
This function was introduced in QtCore 4.2.
See also QMetaProperty::isUser().
Macro Documentation
QGenericArgument Q_ARG( Type, const Type & value)
This macro takes a Type and a value of that type and returns a QGenericArgument object that can be passed toQMetaObject::invokeMethod().
See also Q_RETURN_ARG().
QGenericReturnArgument Q_RETURN_ARG( Type, Type & value)
This macro takes a Type and a non-const reference to a value of that type and returns a QGenericReturnArgumentobject that can be passed to QMetaObject::invokeMethod().
See also Q_ARG().