Qt Jambi Home

com.trolltech.qt.core
Class QObject

java.lang.Object
  extended by com.trolltech.qt.QSignalEmitter
      extended by com.trolltech.qt.QtJambiObject
          extended by com.trolltech.qt.core.QObject
All Implemented Interfaces:
QtJambiInterface
Direct Known Subclasses:
QAbstractEventDispatcher, QAbstractItemDelegate, QAbstractItemModel, QAbstractTextDocumentLayout, QAction, QActionGroup, QButtonGroup, QClipboard, QCompleter, QCoreApplication, QDataWidgetMapper, QDrag, QEventLoop, QFileSystemWatcher, QFtp, QGraphicsItemAnimation, QGraphicsScene, QGraphicsSvgItem, QGraphicsTextItem, QHttp, QInputContext, QIODevice, QItemSelectionModel, QLayout, QMimeData, QMovie, QSessionManager, QSettings, QShortcut, QSignalMapper, QSocketNotifier, QSound, QSqlDriver, QStyle, QSvgRenderer, QSyntaxHighlighter, QSystemTrayIcon, QTcpServer, QTextDocument, QTextObject, QTimeLine, QTimer, QTranslator, QUndoGroup, QUndoStack, QValidator, QWidget

public class QObject
extends QtJambiObject

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 with blockSignals. 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() or findChildren().

Every object has an objectName and its class name can be found via the corresponding metaObject() (see QMetaObject::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 and eventFilter 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 the moveToThread 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 *>.

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 Component 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.

See Also:
QMetaObject, QPointer, QObjectCleanupHandler, Object Trees and Object Ownership

Nested Class Summary
 
Nested classes/interfaces inherited from class com.trolltech.qt.QSignalEmitter
QSignalEmitter.AbstractSignal, QSignalEmitter.Signal0, QSignalEmitter.Signal1<A>, QSignalEmitter.Signal2<A,B>, QSignalEmitter.Signal3<A,B,C>, QSignalEmitter.Signal4<A,B,C,D>, QSignalEmitter.Signal5<A,B,C,D,E>, QSignalEmitter.Signal6<A,B,C,D,E,F>, QSignalEmitter.Signal7<A,B,C,D,E,F,G>, QSignalEmitter.Signal8<A,B,C,D,E,F,G,H>, QSignalEmitter.Signal9<A,B,C,D,E,F,G,H,I>
 
Constructor Summary
QObject()
          Equivalent to QObject(0).
QObject(QObject parent)
          Constructs an object with parent object parent.
 
Method Summary
 boolean blockSignals(boolean b)
          If b is true, signals emitted by this object are blocked (i.e., emitted signals disappear into hyperspace).
protected  void childEvent(QChildEvent arg__1)
          This event handler can be reimplemented in a subclass to receive child events.
 java.util.List<QObject> children()
          Returns a list of child objects.
 void connectSlotsByName()
          Searches recursively for all child objects of the given object, and connects matching signals from them to slots of object that follow the following form.
protected  void customEvent(QEvent arg__1)
          This event handler can be reimplemented in a subclass to receive custom events.
 void disposeLater()
          Schedules this object for deletion.
 void dumpObjectInfo()
          Dumps information about signal connections, etc. for this object to the debug output.
 void dumpObjectTree()
          Dumps a tree of children to the debug output.
 java.util.List<QByteArray> dynamicPropertyNames()
          Returns the names of all properties that were dynamically added to the object using setProperty().
 boolean event(QEvent arg__1)
          This virtual function receives events to an object and should return true if the event arg__1 was recognized and processed.
 boolean eventFilter(QObject arg__1, QEvent arg__2)
          Filters events if this object has been installed as an event filter for the arg__1 object.
 QObject findChild()
          Returns a child of this object, or 0 if there is no such object.
 QObject findChild(java.lang.Class<?> cl)
          Returns the child of this object that is an instance of cl.
 QObject findChild(java.lang.Class<?> cl, java.lang.String name)
          Returns the child of this object that is an instance of cl, and has the specified name.
 java.util.List<QObject> findChildren()
          Returns all children of this QObject, or an empty list if it has no children.
 java.util.List<QObject> findChildren(java.lang.Class<?> cl)
          Returns all children of this object which are instances of class cl, or an empty list if there are no such objects.
 java.util.List<QObject> findChildren(java.lang.Class<?> cl, QRegExp name)
          Returns all children of this object which are instances of class cl with a name that matches name, or an empty list if there are no such objects.
 java.util.List<QObject> findChildren(java.lang.Class<?> cl, java.lang.String name)
          Returns all children of this object which are instances of class cl with specified name, or an empty list if there are no such objects.
static QObject fromNativePointer(QNativePointer nativePointer)
          This function returns the QObject instance pointed to by nativePointer
 void installEventFilter(QObject arg__1)
          Installs an event filter arg__1 on this object.
 boolean isWidgetType()
          Returns true if the object is a widget; otherwise returns false.
 void killTimer(int id)
          Kills the timer with timer identifier, id.
 void moveToThread(java.lang.Thread thread)
          Changes the thread affinity for this object and its children.
 java.lang.String objectName()
          Returns the name of this object.
 QObject parent()
          Returns a pointer to the parent object.
 java.lang.Object property(java.lang.String name)
          Returns the value of the object's name property.
 void removeEventFilter(QObject arg__1)
          Removes an event filter object arg__1 from this object.
 void setObjectName(java.lang.String name)
          Sets the name of this object to name.
 void setParent(QObject arg__1)
          Makes the object a child of arg__1.
 void setProperty(java.lang.String name, java.lang.Object value)
          Sets the value of the object's name property to value.
 boolean signalsBlocked()
          Returns true if signals are blocked; otherwise returns false.
 int startTimer(int interval)
          Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.
 java.lang.Thread thread()
          Returns the thread in which the object lives.
protected  void timerEvent(QTimerEvent arg__1)
          This event handler can be reimplemented in a subclass to receive timer events for the object.
 
Methods inherited from class com.trolltech.qt.QtJambiObject
dispose, disposed, finalize, reassignNativeResources, tr, tr, tr
 
Methods inherited from class com.trolltech.qt.QSignalEmitter
disconnect, disconnect, signalSender
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface com.trolltech.qt.QtJambiInterface
disableGarbageCollection, nativeId, nativePointer, reenableGarbageCollection, setJavaOwnership
 

Constructor Detail

QObject

public QObject()

Equivalent to QObject(0).


QObject

public QObject(QObject parent)

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 and Cancel 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, findChildren
Method Detail

blockSignals

public final boolean blockSignals(boolean b)

If b is true, signals emitted by this object are blocked (i.e., emitted signals disappear into hyperspace). If b 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.

Overrides:
blockSignals in class QSignalEmitter
See Also:
signalsBlocked

children

public final java.util.List<QObject> children()

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, setParent

disposeLater

public final void disposeLater()

Schedules this object for deletion.

The object will be deleted when control returns to the event loop.

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, QPointer

dumpObjectInfo

public final void 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

dumpObjectTree

public final void 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

dynamicPropertyNames

public final java.util.List<QByteArray> dynamicPropertyNames()

Returns the names of all properties that were dynamically added to the object using setProperty().


installEventFilter

public final void installEventFilter(QObject arg__1)

Installs an event filter arg__1 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 arg__1 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.

See Also:
removeEventFilter, eventFilter, event

isWidgetType

public final boolean isWidgetType()

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.


killTimer

public final void 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, startTimer

moveToThread

public final void moveToThread(java.lang.Thread thread)

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 thread.

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 thread 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 thread. 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 the thread.

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

objectName

public final java.lang.String objectName()

Returns 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);

See Also:
setObjectName, metaObject, QMetaObject::className

parent

public final QObject parent()

Returns a pointer to the parent object.

See Also:
setParent, children

removeEventFilter

public final void removeEventFilter(QObject arg__1)

Removes an event filter object arg__1 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, event

setObjectName

public final void setObjectName(java.lang.String name)

Sets the name of this object to name.

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);

See Also:
objectName, metaObject, QMetaObject::className

setParent

public final void setParent(QObject arg__1)

Makes the object a child of arg__1.

See Also:
parent, QWidget::setParent

signalsBlocked

public final boolean signalsBlocked()

Returns true if signals are blocked; otherwise returns false.

Signals are not blocked by default.

Overrides:
signalsBlocked in class QSignalEmitter
See Also:
blockSignals

startTimer

public final int startTimer(int interval)

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. 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, QTimer::singleShot

thread

public final java.lang.Thread thread()

Returns the thread in which the object lives.

Overrides:
thread in class QSignalEmitter
See Also:
moveToThread

childEvent

protected void childEvent(QChildEvent arg__1)

This event handler can be reimplemented in a subclass to receive child events. The event is passed in the arg__1 parameter.

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.

For every child widget, you receive one ChildAdded event, zero or more ChildPolished events, and one ChildRemoved event.

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

customEvent

protected void customEvent(QEvent arg__1)

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 QEvent subclass. The event is passed in the arg__1 parameter.

See Also:
event, QEvent

event

public boolean event(QEvent arg__1)

This virtual function receives events to an object and should return true if the event arg__1 was recognized and processed.

The event function can be reimplemented to customize the behavior of an object.

See Also:
installEventFilter, timerEvent, QApplication::sendEvent, QApplication::postEvent, QWidget::event

eventFilter

public boolean eventFilter(QObject arg__1,
                           QEvent arg__2)

Filters events if this object has been installed as an event filter for the arg__1 object.

In your reimplementation of this function, if you want to filter the arg__2 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

timerEvent

protected void timerEvent(QTimerEvent arg__1)

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 arg__1 parameter.

See Also:
startTimer, killTimer, event

fromNativePointer

public static QObject fromNativePointer(QNativePointer nativePointer)
This function returns the QObject instance pointed to by nativePointer

Parameters:
nativePointer - the QNativePointer of which object should be returned.

findChildren

public java.util.List<QObject> findChildren()
Returns all children of this QObject, or an empty list if it has no children.


findChildren

public java.util.List<QObject> findChildren(java.lang.Class<?> cl)
Returns all children of this object which are instances of class cl, or an empty list if there are no such objects. The search is performed recursively.


findChildren

public java.util.List<QObject> findChildren(java.lang.Class<?> cl,
                                            java.lang.String name)
Returns all children of this object which are instances of class cl with specified name, or an empty list if there are no such objects. The search is performed recursively.


findChildren

public java.util.List<QObject> findChildren(java.lang.Class<?> cl,
                                            QRegExp name)
Returns all children of this object which are instances of class cl with a name that matches name, or an empty list if there are no such objects. The search is performed recursively.


findChild

public QObject findChild()
Returns a child of this object, or 0 if there is no such object. 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.


findChild

public QObject findChild(java.lang.Class<?> cl)
Returns the child of this object that is an instance of cl.

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.


findChild

public QObject findChild(java.lang.Class<?> cl,
                         java.lang.String name)
Returns the child of this object that is an instance of cl, and has the specified name.

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.


setProperty

public void setProperty(java.lang.String name,
                        java.lang.Object 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.


property

public java.lang.Object property(java.lang.String name)
Returns the value of the object's name property.

If no such property exists, the returned object is invalid.

Information about all available properties is provided through the metaObject() and dynamicPropertyNames().


connectSlotsByName

public void connectSlotsByName()
Searches recursively for all child objects of the given object, and connects matching signals from them to slots of object that follow the following form.

void on__();

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()


Qt Jambi Home