
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQObject class is the base class of all Qt objects.More...
Note: All functions in this class arereentrant, butconnect(),connect(),disconnect(), anddisconnect() are alsothread-safe.
| QObject(QObject * parent = 0) | |
| virtual | ~QObject() |
| bool | blockSignals(bool block) |
| const QObjectList & | children() const |
| bool | connect(const QObject * sender, const char * signal, const char * method, Qt::ConnectionType type = Qt::AutoConnection) const |
| bool | disconnect(const char * signal = 0, const QObject * receiver = 0, const char * method = 0) |
| bool | disconnect(const QObject * receiver, const char * method = 0) |
| void | dumpObjectInfo() |
| void | dumpObjectTree() |
| QList<QByteArray> | dynamicPropertyNames() const |
| virtual bool | event(QEvent * e) |
| virtual bool | eventFilter(QObject * watched, QEvent * event) |
| T | findChild(const QString & name = QString()) const |
| QList<T> | findChildren(const QString & name = QString()) const |
| QList<T> | findChildren(const QRegExp & regExp) const |
| bool | inherits(const char * className) const |
| void | installEventFilter(QObject * filterObj) |
| bool | isWidgetType() const |
| void | killTimer(int id) |
| virtual const QMetaObject * | metaObject() const |
| void | moveToThread(QThread * targetThread) |
| QString | objectName() const |
| QObject * | parent() const |
| QVariant | property(const char * name) const |
| void | removeEventFilter(QObject * obj) |
| void | setObjectName(const QString & name) |
| void | setParent(QObject * parent) |
| bool | setProperty(const char * name, const QVariant & value) |
| bool | signalsBlocked() const |
| int | startTimer(int interval) |
| QThread * | thread() const |
| void | deleteLater() |
| void | destroyed(QObject * obj = 0) |
| bool | connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection) |
| bool | connect(const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method, Qt::ConnectionType type = Qt::AutoConnection) |
| bool | disconnect(const QObject * sender, const char * signal, const QObject * receiver, const char * method) |
| bool | disconnect(const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method) |
| const QMetaObject | staticMetaObject |
| QString | tr(const char * sourceText, const char * disambiguation = 0, int n = -1) |
| QString | trUtf8(const char * sourceText, const char * disambiguation = 0, int n = -1) |
| virtual void | childEvent(QChildEvent * event) |
| virtual void | connectNotify(const char * signal) |
| virtual void | customEvent(QEvent * event) |
| virtual void | disconnectNotify(const char * signal) |
| int | receivers(const char * signal) const |
| QObject * | sender() const |
| int | senderSignalIndex() const |
| virtual void | timerEvent(QTimerEvent * event) |
| typedef | QObjectList |
| QList<T> | qFindChildren(const QObject * obj, const QRegExp & regExp) |
| T | qobject_cast(QObject * object) |
| Q_CLASSINFO( Name, Value) | |
| Q_DISABLE_COPY( Class) | |
| Q_EMIT | |
| Q_ENUMS(...) | |
| Q_FLAGS(...) | |
| Q_INTERFACES(...) | |
| Q_INVOKABLE | |
| Q_OBJECT | |
| Q_PROPERTY(...) | |
| Q_SIGNAL | |
| Q_SIGNALS | |
| Q_SLOT | |
| Q_SLOTS |
TheQObject class is the base class of all Qt objects.
QObject is the heart of the QtObject Model. The central feature in this model is a very powerful mechanism for seamless object communication calledsignals and slots. You can connect a signal to a slot withconnect() and destroy the connection withdisconnect(). To avoid never ending notification loops you can temporarily block signals withblockSignals(). The protected functionsconnectNotify() anddisconnectNotify() make it possible to track connections.
QObjects organize themselves inobject trees. When you create aQObject with another object as parent, the object will automatically add itself to the parent'schildren() 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 usingfindChild() orfindChildren().
Every object has anobjectName() and its class name can be found via the correspondingmetaObject() (seeQMetaObject::className()). You can determine whether the object's class inherits another class in theQObject inheritance hierarchy by using theinherits() function.
When an object is deleted, it emits adestroyed() signal. You can catch this signal to avoid dangling references toQObjects.
QObjects can receive events throughevent() and filter the events of other objects. SeeinstallEventFilter() andeventFilter() for details. A convenience handler,childEvent(), can be reimplemented to catch child events.
Last but not least,QObject provides the basic timer support in Qt; seeQTimer for high-level support for timers.
Notice that theQ_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run theMeta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses ofQObject 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 inheritQObject. The convenience functionisWidgetType() returns whether an object is actually a widget. It is much faster thanqobject_cast<QWidget *>(obj) orobj->inherits("QWidget").
SomeQObject functions, e.g.children(), return aQObjectList.QObjectList is a typedef forQList<QObject *>.
AQObject instance is said to have athread affinity, or that itlives in a certain thread. When aQObject receives aqueued signal or aposted event, the slot or event handler will run in the thread that the object lives in.
Note:If aQObject has no thread affinity (that is, ifthread() returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.
By default, aQObject lives in the thread in which it is created. An object's thread affinity can be queried usingthread() and changed usingmoveToThread().
AllQObjects must live in the same thread as their parent. Consequently:
Note:AQObject's member variablesdo not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child'sconstructor, or by callingsetParent(). Without this step, the object's member variables will remain in the old thread whenmoveToThread() is called.
QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in aprivate section with the macroQ_DISABLE_COPY(). In fact, all Qt classes derived fromQObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion onIdentity vs Value on the QtObject Model page.
The main consequence is that you should use pointers toQObject (or to yourQObject subclass) where you might otherwise be tempted to use yourQObject subclass as a value. For example, without a copy constructor, you can't use a subclass ofQObject as the value to be stored in one of the container classes. You must store pointers.
Qt's meta-object system provides a mechanism to automatically connect signals and slots betweenQObject 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 theQMetaObject::connectSlotsByName() function.
uic generates code that invokes this function to enable auto-connection to be performed between widgets on forms created withQt Designer. More information about using auto-connection withQt Designer is given in theUsing a Designer UI File in Your Application section of theQt Designer manual.
From Qt 4.2, dynamic properties can be added to and removed fromQObject 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 - usingproperty() to read them andsetProperty() to write them.
From Qt 4.3, dynamic properties are supported byQt Designer, and both standard Qt widgets and user-created forms can be given dynamic properties.
AllQObject 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 thetr() function. This is explained in detail in theWriting Source Code for Translation document.
See alsoQMetaObject,QPointer,QObjectCleanupHandler,Q_DISABLE_COPY(), andObject Trees & Ownership.
This property holds the name of this object.
You can find an object by name (and type) usingfindChild(). You can find a set of objects withfindChildren().
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) |
See alsometaObject() andQMetaObject::className().
Constructs an object with parent objectparent.
The parent of an object may be viewed as the object's owner. For instance, adialog box is the parent of theOK andCancel buttons it contains.
The destructor of a parent object destroys all child objects.
Settingparent to 0 constructs an object with no parent. If the object is a widget, it will become a top-level window.
See alsoparent(),findChild(), andfindChildren().
[virtual]QObject::~QObject()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 usedeleteLater() rather than deleting aQObject 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 aQObject while pending events are waiting to be delivered can cause a crash. You must not delete theQObject directly if it exists in a different thread than the one currently executing. UsedeleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.
See alsodeleteLater().
Ifblock is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). Ifblock is false, no such blocking will occur.
The return value is the previous value ofsignalsBlocked().
Note that thedestroyed() signal will be emitted even if the signals for this object have been blocked.
See alsosignalsBlocked().
[virtual protected]void QObject::childEvent(QChildEvent * event)This event handler can be reimplemented in a subclass to receive child events. The event is passed in theevent parameter.
QEvent::ChildAdded andQEvent::ChildRemoved events are sent to objects when children are added or removed. In both cases you can only rely on the child being aQObject, or ifisWidgetType() returns true, aQWidget. (This is because, in theChildAdded case, the child is not yet fully constructed, and in theChildRemoved 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 oneChildAdded event, zero or moreChildPolished events, and oneChildRemoved event.
TheChildPolished 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 alsoevent().
Returns a list of child objects. TheQObjectList class is defined in the<QObject> header file as the following:
typedefQList<QObject*>QObjectList;
The first child added is thefirst object in the list and the last child added is thelast object in the list, i.e. new children are appended at the end.
Note that the list order changes whenQWidget children areraised orlowered. 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 alsofindChild(),findChildren(),parent(), andsetParent().
[static]bool QObject::connect(constQObject * sender, constchar * signal, constQObject * receiver, constchar * method,Qt::ConnectionType type = Qt::AutoConnection)Creates a connection of the giventype from thesignal in thesender object to themethod in thereceiver object. Returns true if the connection succeeds; otherwise returns false.
You must use theSIGNAL() andSLOT() macros when specifying thesignal and themethod, for example:
QLabel*label=newQLabel;QScrollBar*scrollBar=newQScrollBar;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:
// WRONGQObject::connect(scrollBar, SIGNAL(valueChanged(int value)), label, SLOT(setNum(int value)));
A signal can also be connected to another signal:
class MyWidget :publicQWidget{ Q_OBJECTpublic: MyWidget();signals:void buttonClicked();private:QPushButton*myButton;};MyWidget::MyWidget(){ myButton=newQPushButton(this); connect(myButton, SIGNAL(clicked()),this, SIGNAL(buttonClicked()));}
In this example, theMyWidget constructor relays a signal from a private member variable, and makes it available under a name that relates toMyWidget.
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 true if it successfully connects the signal to the slot. It will return false if it cannot create the connection, for example, ifQObject is unable to verify the existence of eithersignal ormethod, or if their signatures aren't compatible.
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 singledisconnect() call. If you pass theQt::UniqueConnectiontype, 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 false.
The optionaltype 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 registeredusingqRegisterMetaType().)
callqRegisterMetaType() to register the data type before you establish the connection.
Note: This function isthread-safe.
See alsodisconnect(),sender(),qRegisterMetaType(), andQ_DECLARE_METATYPE().
[static]bool QObject::connect(constQObject * sender, constQMetaMethod & signal, constQObject * receiver, constQMetaMethod & method,Qt::ConnectionType type = Qt::AutoConnection)Creates a connection of the giventype from thesignal in thesender object to themethod in thereceiver object. Returns true if the connection succeeds; otherwise returns false.
This function works in the same way as connect(constQObject *sender, const char *signal, constQObject *receiver, const char *method,Qt::ConnectionType type) but it usesQMetaMethod to specify signal and method.
This function was introduced in Qt 4.8.
See alsoconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type).
This function overloadsconnect().
Connectssignal from thesender object to this object'smethod.
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 isthread-safe.
See alsodisconnect().
[virtual protected]void QObject::connectNotify(constchar * signal)This virtual function is called when something has been connected tosignal in this object.
If you want to comparesignal with a specific signal, useQLatin1String and theSIGNAL() macro as follows:
if (QLatin1String(signal)== SIGNAL(valueChanged(int))) {// signal is valueChanged(int)}
If the signal contains multiple parameters or parameters that contain spaces, callQMetaObject::normalizedSignature() on the result of theSIGNAL() macro.
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 alsoconnect() anddisconnectNotify().
[virtual protected]void QObject::customEvent(QEvent * event)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 theQEvent::User item of theQEvent::Type enum, and is typically aQEvent subclass. The event is passed in theevent parameter.
[slot]void QObject::deleteLater()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 beforeQCoreApplication::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) willnot 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 alsodestroyed() andQPointer.
[signal]void QObject::destroyed(QObject * obj = 0)This signal is emitted immediately before the objectobj is destroyed, and can not be blocked.
All the objects's children are destroyed immediately after this signal is emitted.
See alsodeleteLater() andQPointer.
[static]bool QObject::disconnect(constQObject * sender, constchar * signal, constQObject * receiver, constchar * method)Disconnectssignal in objectsender frommethod in objectreceiver. 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(myObject,0,0,0);
equivalent to the non-static overloaded function
myObject->disconnect();
disconnect(myObject, SIGNAL(mySignal()),0,0);
equivalent to the non-static overloaded function
myObject->disconnect(SIGNAL(mySignal()));
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.
Thesender may never be 0. (You cannot disconnect signals from more than one object in a single call.)
Ifsignal is 0, it disconnectsreceiver andmethod from any signal. If not, only the specified signal is disconnected.
Ifreceiver is 0, it disconnects anything connected tosignal. If not, slots in objects other thanreceiver are not disconnected.
Ifmethod is 0, it disconnects anything that is connected toreceiver. If not, only slots namedmethod will be disconnected, and all other slots are left alone. Themethod must be 0 ifreceiver is left out, so you cannot disconnect a specifically-named slot on all objects.
Note: This function isthread-safe.
See alsoconnect().
[static]bool QObject::disconnect(constQObject * sender, constQMetaMethod & signal, constQObject * receiver, constQMetaMethod & method)Disconnectssignal in objectsender frommethod in objectreceiver. Returns true if the connection is successfully broken; otherwise returns false.
This function provides the same possibilities like disconnect(constQObject *sender, const char *signal, constQObject *receiver, const char *method) but usesQMetaMethod to represent the signal and the method to be disconnected.
Additionally this function returnsfalse and no signals and slots disconnected if:
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 forreceiver 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 Qt 4.8.
See alsodisconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method).
This function overloadsdisconnect().
Disconnectssignal frommethod ofreceiver.
A signal-slot connection is removed when either of the objects involved are destroyed.
Note: This function isthread-safe.
This function overloadsdisconnect().
Disconnects all signals in this object fromreceiver'smethod.
A signal-slot connection is removed when either of the objects involved are destroyed.
[virtual protected]void QObject::disconnectNotify(constchar * signal)This virtual function is called when something has been disconnected fromsignal in this object.
SeeconnectNotify() for an example of how to comparesignal with a specific signal.
Warning: This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.
See alsodisconnect() andconnectNotify().
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 alsodumpObjectTree().
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 alsodumpObjectInfo().
Returns the names of all properties that were dynamically added to the object usingsetProperty().
This function was introduced in Qt 4.2.
[virtual]bool QObject::event(QEvent * e)This virtual function receives events to an object and should return true if the evente was recognized and processed.
The event() function can be reimplemented to customize the behavior of an object.
See alsoinstallEventFilter(),timerEvent(),QApplication::sendEvent(),QApplication::postEvent(), andQWidget::event().
[virtual]bool QObject::eventFilter(QObject * watched,QEvent * event)Filters events if this object has been installed as an event filter for thewatched object.
In your reimplementation of this function, if you want to filter theevent out, i.e. stop it being handled further, return true; otherwise return false.
Example:
class MainWindow :publicQMainWindow{public: MainWindow();protected: bool eventFilter(QObject*obj,QEvent*ev);private:QTextEdit*textEdit;};MainWindow::MainWindow(){ textEdit=newQTextEdit; 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();returntrue; }else {returnfalse; } }else {// pass the event on to the parent classreturnQMainWindow::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 alsoinstallEventFilter().
Returns the child of this object that can be cast into type T and that is calledname, or 0 if there is no such object. Omitting thename argument causes all object names to be matched. The search is performed recursively.
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 childQPushButton ofparentWidget named"button1":
QPushButton*button= parentWidget->findChild<QPushButton*>("button1");
This example returns aQListWidget child ofparentWidget:
QListWidget*list= parentWidget->findChild<QListWidget*>();
See alsofindChildren().
Returns all children of this object with the givenname that can be cast to type T, or an empty list if there are no such objects. Omitting thename argument causes all object names to be matched. The search is performed recursively.
The following example shows how to find a list of childQWidgets of the specifiedparentWidget namedwidgetname:
This example returns allQPushButtons that are children ofparentWidget:
QList<QPushButton*> allPButtons= parentWidget.findChildren<QPushButton*>();
See alsofindChild().
This function overloadsfindChildren().
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.
Returns true if this object is an instance of a class that inheritsclassName or aQObject subclass that inheritsclassName; otherwise returns false.
A class is considered to inherit itself.
Example:
QTimer*timer=newQTimer;// QTimer inherits QObjecttimer->inherits("QTimer");// returns truetimer->inherits("QObject");// returns truetimer->inherits("QAbstractButton");// returns false// QVBoxLayout inherits QObject and QLayoutItemQVBoxLayout*layout=newQVBoxLayout;layout->inherits("QObject");// returns truelayout->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 usingqobject_cast<Type *>(object) instead.
See alsometaObject() andqobject_cast().
Installs an event filterfilterObj 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 filterfilterObj receives events via itseventFilter() function. TheeventFilter() 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 aKeyPressEater class that eats the key presses of its monitored objects:
class KeyPressEater :publicQObject{ 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());returntrue; }else {// standard event processingreturnQObject::eventFilter(obj, event); }}
And here's how to install it on two widgets:
KeyPressEater*keyPressEater=new KeyPressEater(this);QPushButton*pushButton=newQPushButton(this);QListView*listView=newQListView(this);pushButton->installEventFilter(keyPressEater);listView->installEventFilter(keyPressEater);
TheQShortcut class, for example, uses this technique to intercept shortcut key presses.
Warning: If you delete the receiver object in youreventFilter() 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. IffilterObj is in a different thread, this function does nothing. If eitherfilterObj 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 isnot removed).
See alsoremoveEventFilter(),eventFilter(), andevent().
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.
Kills the timer with timer identifier,id.
The timer identifier is returned bystartTimer() when a timer event is started.
See alsotimerEvent() andstartTimer().
[virtual]constQMetaObject * QObject::metaObject() constReturns a pointer to the meta-object of this object.
A meta-object contains information about a class that inheritsQObject, e.g. class name, superclass name, properties, signals and slots. EveryQObject subclass that contains theQ_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=newQPushButton;obj->metaObject()->className();// returns "QPushButton"QPushButton::staticMetaObject.className();// returns "QPushButton"
See alsostaticMetaObject.
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 thetargetThread.
To move an object to the main thread, useQApplication::instance() to retrieve a pointer to the current application, and then useQApplication::thread() to retrieve the thread in which the application lives. For example:
myObject->moveToThread(QApplication::instance()->thread());
IftargetThread 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 thetargetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.
AQEvent::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 isnot 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 alsothread().
Returns a pointer to the parent object.
See alsosetParent() andchildren().
Returns the value of the object'sname property.
If no such property exists, the returned variant is invalid.
Information about all available properties is provided through themetaObject() anddynamicPropertyNames().
See alsosetProperty(),QVariant::isValid(),metaObject(), anddynamicPropertyNames().
[protected]int QObject::receivers(constchar * signal) constReturns the number of receivers connected to thesignal.
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 theSIGNAL() macro to pass a specific signal:
if (receivers(SIGNAL(valueChanged(QByteArray)))>0) {QByteArray data; get_the_value(&data);// expensive operationemit 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.
Removes an event filter objectobj 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 theeventFilter() function).
See alsoinstallEventFilter(),eventFilter(), andevent().
[protected]QObject * QObject::sender() constReturns 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 alsosenderSignalIndex() andQSignalMapper.
[protected]int QObject::senderSignalIndex() constReturns the meta-method index of the signal that called the currently executing slot, which is a member of the class returned bysender(). 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 withconnect(). For example, the signaldestroyed(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 aQt::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 Qt 4.8.
See alsosender(),QMetaObject::indexOfSignal(), andQMetaObject::method().
Makes the object a child ofparent.
See alsoparent() andQWidget::setParent().
Sets the value of the object'sname property tovalue.
If the property is defined in the class usingQ_PROPERTY then true is returned on success and false otherwise. If the property is not defined usingQ_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 themetaObject() anddynamicPropertyNames().
Dynamic properties can be queried again usingproperty() and can be removed by setting the property value to an invalidQVariant. Changing the value of a dynamic property causes aQDynamicPropertyChangeEvent to be sent to the object.
Note: Dynamic properties starting with "_q_" are reserved for internal purposes.
See alsoproperty(),metaObject(), anddynamicPropertyNames().
Returns true if signals are blocked; otherwise returns false.
Signals are not blocked by default.
See alsoblockSignals().
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.
A timer event will occur everyinterval milliseconds untilkillTimer() is called. Ifinterval is 0, then the timer event occurs once every time there are no more window system events to process.
The virtualtimerEvent() function is called with theQTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events.
If multiple timers are running, theQTimerEvent::timerId() can be used to find out which timer was activated.
Example:
class MyObject :publicQObject{ Q_OBJECTpublic: 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 thatQTimer's accuracy depends on the underlying operating system and hardware. 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.
TheQTimer class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also aQBasicTimer class that is more lightweight thanQTimer and less clumsy than using timer IDs directly.
See alsotimerEvent(),killTimer(), andQTimer::singleShot().
Returns the thread in which the object lives.
See alsomoveToThread().
[virtual protected]void QObject::timerEvent(QTimerEvent * event)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 theevent parameter.
See alsostartTimer(),killTimer(), andevent().
[static]QString QObject::tr(constchar * sourceText, constchar * disambiguation = 0,int n = -1)Returns a translated version ofsourceText, optionally based on adisambiguation string and value ofn for strings containing plurals; otherwise returnssourceText itself if no appropriate translated string is available.
Example:
void MainWindow::createMenus(){ fileMenu= menuBar()->addMenu(tr("&File")); ...
If the samesourceText is used in different roles within the same context, an additional identifying string may be passed indisambiguation (0 by default). In Qt 4.4 and earlier, this was the preferred way to pass comments to translators.
Example:
MyWindow::MyWindow(){QLabel*senderLabel=newQLabel(tr("Name:"));QLabel*recipientLabel=newQLabel(tr("Name:","recipient")); ...
SeeWriting 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 installedbefore 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 alsotrUtf8(),QApplication::translate(),QTextCodec::setCodecForTr(), andInternationalization with Qt.
[static]QString QObject::trUtf8(constchar * sourceText, constchar * disambiguation = 0,int n = -1)Returns a translated version ofsourceText, orQString::fromUtf8(sourceText) if there is no appropriate version. It is otherwise identical to tr(sourceText,disambiguation,n).
Note that using the Utf8 variants of the translation functions is not required ifCODECFORTR is already set to UTF-8 in the qmake project file andQTextCodec::setCodecForTr("UTF-8") is used.
Warning: This method is reentrant only if all translators are installedbefore calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.
Warning: For portability reasons, we recommend that you use escape sequences for specifying non-ASCII characters in string literals to trUtf8(). For example:
label->setText(tr("F\374r \310lise"));
See alsotr(),QApplication::translate(), andInternationalization with Qt.
This variable stores the meta-object for the class.
A meta-object contains information about a class that inheritsQObject, e.g. class name, superclass name, properties, signals and slots. Every class that contains theQ_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 usemetaObject() to retrieve the meta-object associated with that object.
Example:
QPushButton::staticMetaObject.className();// returns "QPushButton"QObject*obj=newQPushButton;obj->metaObject()->className();// returns "QPushButton"
See alsometaObject().
This function overloads qFindChildren().
This function is equivalent toobj->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 alsoQObject::findChildren().
Returns the givenobject cast to type T if the object is of type T (or of a subclass); otherwise returns 0. Ifobject is 0 then it will also return 0.
The class T must inherit (directly or indirectly)QObject and be declared with theQ_OBJECT macro.
A class is considered to inherit itself.
Example:
QObject*obj=newQTimer;// QTimer inherits QObjectQTimer*timer= qobject_cast<QTimer*>(obj);// timer == (QObject *)objQAbstractButton*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 thePlug & Paint example for details.
Warning: If T isn't declared with theQ_OBJECT macro, this function's return value is undefined.
See alsoQObject::inherits().
This macro associates extra information to the class, which is available usingQObject::metaObject(). Except for theActiveQt extension, Qt doesn't use this information.
The extra information takes the form of aName string and aValue literal string.
Example:
class MyClass :publicQObject{ Q_OBJECT Q_CLASSINFO("Author","Pierre Gendron") Q_CLASSINFO("URL","http://www.my-organization.qc.ca")public:...};
See alsoQMetaObject::classInfo().
Disables the use of copy constructors and assignment operators for the givenClass.
Instances of subclasses ofQObject 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 ofQObject (director or indirect), you shouldnot 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 fromQObject typically include this macro in a private section:
class MyClass :publicQObject{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 :publicQObject{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:
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 usingneither the copy constructornor 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 ofw.
Use this macro to replace theemit keyword for emitting signals, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used whenno_keywords is specified with theCONFIG variable in the.pro file, but it can be used even whenno_keywords isnot specified.
This macro registers one or several enum types to the meta-object system.
For example:
class MyClass :publicQObject{ 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 classdefining the enum has to inheritQObject as well as declare the enum using Q_ENUMS().
See alsoQt's Property System.
This macro registers one or severalflags 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, inQLibrary, theLoadHints flag is declared in the following way:
The declaration of the flags themselves is performed in the public section of theQLibrary 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 useQ_ENUMS() in addition to this macro.
See alsoQt's Property System.
This macro tells Qt which interfaces the class implements. This is used when implementing plugins.
Example:
class BasicToolsPlugin :publicQObject,public BrushInterface,public ShapeInterface,public FilterInterface{ Q_OBJECT Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)public: ...};
See thePlug & Paint Basic Tools example for details.
See alsoQ_DECLARE_INTERFACE(),Q_EXPORT_PLUGIN2(), andHow to Create Qt Plugins.
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 :publicQWidget{ Q_OBJECTpublic: Window();void normalMethod(); Q_INVOKABLEvoid invokableMethod();};
TheinvokableMethod() function is marked up using Q_INVOKABLE, causing it to be registered with the meta-object system and enabling it to be invoked usingQMetaObject::invokeMethod(). SincenormalMethod() function is not registered in this way, it cannot be invoked usingQMetaObject::invokeMethod().
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 :publicQObject{ Q_OBJECTpublic: Counter() { m_value=0; }int value()const {return m_value; }publicslots:void setValue(int value);signals:void valueChanged(int newValue);private:int m_value;};
Note:This macro requires the class to be a subclass ofQObject. Use Q_GADGET instead of Q_OBJECT to enable the meta object system's support for enums in a class that is not aQObject subclass. Q_GADGET makes a class member,staticMetaObject, available.staticMetaObject is of typeQMetaObject and provides access to the enums declared withQ_ENUMS. Q_GADGET is provided only for C++.
See alsoMeta-Object System,Signals and Slots, andQt's Property System.
This macro is used for declaring properties in classes that inheritQObject. Properties behave like class data members, but they have additional features accessible through theMeta-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 theREAD function are required. The type can be any type supported byQVariant, or it can be a user-defined type. The other items are optional, but aWRITE function is common. The attributes default to true exceptUSER, which defaults to false.
For example:
Q_PROPERTY(QString title READ title WRITE setTitle USERtrue)
For more details about how to use this macro, and a more detailed example of its use, see the discussion onQt's Property System.
See alsoQt's Property System.
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 asignals orQ_SIGNALS groups.
Use this macro to replace thesignals keyword in class declarations, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used whenno_keywords is specified with theCONFIG variable in the.pro file, but it can be used even whenno_keywords isnot specified.
Use this macro to replace thesignals keyword in class declarations, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used whenno_keywords is specified with theCONFIG variable in the.pro file, but it can be used even whenno_keywords isnot specified.
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 aslots orQ_SLOTS groups.
Use this macro to replace theslots keyword in class declarations, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used whenno_keywords is specified with theCONFIG variable in the.pro file, but it can be used even whenno_keywords isnot specified.
Use this macro to replace theslots keyword in class declarations, when you want to use Qt Signals and Slots with a3rd party signal/slot mechanism.
The macro is normally used whenno_keywords is specified with theCONFIG variable in the.pro file, but it can be used even whenno_keywords isnot specified.
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.