Описание класса QObject [Модуль QtCore]
Класс QObject - это базовый класс для всех объектов Qt. Далее...
#include <QObject> От него наследуются Phonon::AudioOutput, Phonon::BackendCapabilities::Notifier, Phonon::Effect, Phonon::GlobalConfig, Phonon::MediaController, Phonon::MediaObject, Q3Accel, Q3Action, Q3Canvas, Q3Dns, Q3DragObject, Q3EditorFactory, Q3FileIconProvider, Q3NetworkOperation, Q3NetworkProtocol, Q3Process, Q3ServerSocket, Q3Signal, Q3SqlForm, Q3StyleSheet, Q3UrlOperator, Q3WhatsThis, QAbstractEventDispatcher, QAbstractItemDelegate, QAbstractItemModel, QAbstractMessageHandler, QAbstractTextDocumentLayout, QAbstractUriResolver, QAccessibleBridgePlugin, QAccessiblePlugin, QAction, QActionGroup, QAssistantClient, QButtonGroup, QClipboard, QCompleter, QCoreApplication, QDataWidgetMapper, QDBusAbstractAdaptor, QDBusAbstractInterface, QDBusServer, QDesignerFormEditorInterface, QDesignerFormWindowManagerInterface, QDrag, QEventLoop, QExtensionFactory, QExtensionManager, QFileSystemWatcher, QFtp, QFutureWatcher, QGraphicsItemAnimation, QGraphicsScene, QGraphicsSvgItem, QGraphicsTextItem, QGraphicsWidget, QHelpEngineCore, QHelpSearchEngine, QHttp, QIconEnginePlugin, QIconEnginePluginV2, QImageIOPlugin, QInputContext, QInputContextPlugin, QIODevice, QItemSelectionModel, QLayout, QLibrary, QLocalServer, QMimeData, QMovie, QNetworkAccessManager, QNetworkCookieJar, QObjectCleanupHandler, QPictureFormatPlugin, QPluginLoader, QScriptEngine, QScriptExtensionPlugin, QSessionManager, QSettings, QSharedMemory, QShortcut, QSignalMapper, QSignalSpy, QSocketNotifier, QSound, QSqlDriver, QSqlDriverPlugin, QStyle, QStylePlugin, QSvgRenderer, QSyntaxHighlighter, QSystemTrayIcon, QTcpServer, QTextCodecPlugin, QTextDocument, QTextObject, QThread, QThreadPool, QTimeLine, QTimer, QTranslator, QUiLoader, QUndoGroup, QUndoStack, QValidator, QWebFrame, QWebHistoryInterface, QWebPage, QWebPluginFactory, and QWidget.
Замечание: Все функции в этом классе реентерабельны, за исключением connect(), connect(), disconnect(), и disconnect().
Свойства
Открытые функции
Открытые слоты
Сигналы
Статические открытые члены
- bool connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection )
- bool disconnect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method )
- const QMetaObject staticMetaObject
- QString tr ( const char * sourceText, const char * comment = 0, int n = -1 )
- QString trUtf8 ( const char * sourceText, const char * comment = 0, int n = -1 )
Защищенные функции
Связанные нечлены класса
Макросы
Подробное описание
Класс QObject - это базовый класс для всех объектов Qt.
QObject - это сердце объектной модели Qt. Главная особенность в этой модели - это очень мощный механизм для связи объектов, называемый сигналами и слотами. Вы можете соединить сигнал со слотом с помощью connect () и разъединить с помощью disconnect (). Во избежание возникновения замкнутых циклов вызовов можно временно блокировать сигналы с помощью blockSignals(). Защищенные функции connectNotify () и disconnectNotify () позволяют отслеживать соединения.
Сам QObject устроен в виде дерева объектов. Когда вы создаете QObject с другим объектом в качестве родителя, то объект автоматически добавит себя в список children() - дочерних объектов. Родитель становится владельцем свои дочерних объектов, т.е. он автоматически удалит своих детей в своём деструкторе. Вы можете найти (дочерний) объект по имени и, необязательно, по типу используя функции findChild() или findChildren().
Каждый объект имеет objectName - имя объекта, а имя его класса можно найти через соответствующую функцию metaObject() (смотрите функцию QMetaObject::className()). Вы можете определить унаследован ли класс от другого класса, в иерархии наследования QObject, используя функцию inherits().
Когда объект удалён, он посылает сигнал destroyed(). Вы можете перехватить этот сигнал, чтобы избежать повисших ссылок на QObject'ы.
QObject'ы могут принимать события от других объектов через event() и фильтр событий. Для получения подробной информации смотрите installEventFilter() и eventFilter(). Вспомогательный обработчик - childEvent(), может быть переопределён, чтобы перехватывать события дочерних объектов.
События доставляются в поток, в котором объект был создан; Для получения подробной информации смотрите Поддержка потоков в Qt и функцию thread(). Заметьте, что обработка событий для QObject'ов не принадлежащих потоку вообще не осуществляется (thread() вернёт нуль). Используйте функцию moveToThread() для изменения принадлежности объекта и его дочерних объектов к потоку (объект не может быть перемещён, если у него есть родитель).
Последнее, но не менее важное, QObject предоставляет базовую поддержку таймера в Qt; информацию о высокоуровневой поддержке таймеров смотрите QTimer.
Обратите внимание, что макрос Q_OBJECT является обязательным для любого объекта, реализующим сигналы, слоты и свойства. Вам также необходимо запустить Мета-объектный компилятор (Meta Object Compiler) для исходного файла. Мы настоятельно рекомендуем использовать этот макрос во всех подклассах QObject независимо от того, действительно ли они используют сигналы, слоты и свойства, так как в противном случае некоторые функции могут вести себя неправильно.
Все виджеты Qt унаследованы от QObject. Вспомогательная функция isWidgetType() возвращает, действительно ли объект является виджетом. Она работает намного быстрее, чем qobject_cast<QWidget *>(obj) или obj->inherits("QWidget").
Некоторые функции QObject, например, children(), возвращают QObjectList. QObjectList - это typedef для QList<QObject *>.
Нет конструктора копирования или оператора присваивания
QObject не имеет ни конструктора копирования ни оператора присваивания. Таков замысел. В действительности, они объявлены, но в секции private с помощью макроса Q_DISABLE_COPY(). Фактически, все классы Qt произошедшие от QObject (прямо или косвенно), используют этот макрос, чтобы объявить их конструктор копирования и оператор присваивания закрытыми. Причины вы найдёте в обсуждении Ссылочный тип (Identity) или тип значений (Value) на странице Объектная модель Qt.
Основное последствие - то, что вы должны использовать указатели на QObject (или на ваш подкласс QObject) там, где вы бы могли, в других случаях, соблазниться использовать ваш наследник QObject, как значение. Например, без конструктора копирования, вы не можете использовать подкласс QObject как значение, чтобы сохранить его в одном из классов-контейнеров. Вы должны сохранять указатели.
Автосединение
Мета-объектная система Qt предоставляет механизм для автоматического соединения сигналов и слотов между подклассами QObject и их дочерними объектами. До тех пор, пока объекты определены с надлежащими именами, а слоты соответствуют простому соглашению об именовании, это соединение может быть выполнено во время выполнения, функцией QMetaObject::connectSlotsByName().
uic генерирует код, который вызывает эту функцию, позволить выполнятся автосоединению между виджетами на форме, созданной с помощью Qt Designer. Дополнительная информация об использовании автосоединения с помощью Qt Designer дана в главе Использование компонентов в вашем приложении руководства Qt Designer.
Динамические свойства
Начиная с Qt 4.2, динамические свойства могут быть добавлены и удалены из экземпляра QObject во время выполнения. Динамические свойства не нужно объявлять во время компиляции, тем не менее они предоставляют такие же приемущества как и статические свойства и управляются используя тот же API - используя функцию property(), чтобы читать их и setProperty(), чтобы писать их.
Начиная с Qt 4.3, динамические свойства поддерживаются Qt Designer'ом, и формам на основе стандартных виджетов Qt и на основе пользовательских, могут быть заданны динамические свойства.
(Деревья объектов и владение объектами)
Смотрите также QMetaObject, QPointer, QObjectCleanupHandler, и Q_DISABLE_COPY().
Описание свойств
Это свойство содержит имя объекта.
Вы можете найти объект по имени (и типу) используя findChild(). Вы можете получить множество объектов с помощью findChildren().
qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
qPrintable(objectName()), newPrecision);
По умолчанию, это свойство содержит пустую строку.
Функции доступа:
- QString objectName () const
- void setObjectName ( const QString & name )
Смотрите также metaObject() и QMetaObject::className().
Описание функций-членов
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 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(), 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, the destroyed() 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 event 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.
Смотрите также 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().
bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection ) [static]
Создает соединение заданного типа type между сигналом signal объекта-отправителя sender и методом method в объекте-приёмнике receiver. Возвращает true, если соединение удалось; в противном случае возвращает false.
Вы должны использовать макросы SIGNAL() и SLOT(), когда указываете signal и method, например:
QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
label, SLOT(setNum(int)));
Этот пример гарантирует, что метка всегда отображает текущее значение линейки прокрутки. Заметьте, что параметры сигналов и слотов не должны содержать имен переменных, а только их тип. Следующий пример не будет работать и вернёт false:
QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
label, SLOT(setNum(int value)));
Сигнал, также может быть соединён с другим сигналом:
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 an arbitrary order 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, if QObject is unable to verify the existence of either signal or method, or if their signatures aren't compatible.
A signal is emitted for every connection you make, so if you duplicate a connection, two signals will be emitted. You can always break a connection using disconnect().
The optional type parameter describes the type of connection to establish. В частности определяет доставляется ли сигнал слоту немедленно или ставится в очередь. 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. Если вы пытаетесь использовать соединение с очередями и получаете сообщение об ошибке
QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)
вызовите qRegisterMetaType(), чтобы зарегистрировать тип данных перед установлением соединения.
Замечание: Эта функция потокобезопасна.
See also disconnect(), sender(), and qRegisterMetaType().
bool QObject::connect ( const QObject * sender, const char * signal, const char * method, Qt::ConnectionType type = Qt::AutoConnection ) const
Это перегруженная функция, предоставленная для удобства.
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 using disconnect().
Замечание: Эта функция потокобезопасна.
See also disconnect().
void QObject::connectNotify ( const char * 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, use QLatin1String and the SIGNAL() macro as follows:
if (QLatin1String(signal) == SIGNAL(valueChanged(int))) {
}
If the signal contains multiple parameters or parameters that contain spaces, call QMetaObject::normalizedSignature() on the result of the SIGNAL() 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 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 QEvent subclass. The event is passed in the event parameter.
See also event() and QEvent.
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.
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.
Замечание: Эта функция потокобезопасна.
See also connect().
bool QObject::disconnect ( const char * signal = 0, const QObject * receiver = 0, const char * method = 0 )
Это перегруженная функция, предоставленная для удобства.
Disconnects signal from method of receiver.
A signal-slot connection is removed when either of the objects involved are destroyed.
Замечание: Эта функция потокобезопасна.
bool QObject::disconnect ( const QObject * receiver, const char * method = 0 )
Это перегруженная функция, предоставленная для удобства.
Disconnects all signals in this object from receiver's method.
A signal-slot connection is removed when either of the objects involved are destroyed.
void QObject::disconnectNotify ( const char * 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.
Warning: This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.
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().
Эта функция была введена в Qt 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(), QApplication::sendEvent(), QApplication::postEvent(), and QWidget::event().
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.
Пример:
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 {
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() ) 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.
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":
QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
This example returns a QListWidget child of parentWidget:
QListWidget *list = parentWidget->findChild<QListWidget *>();
Warning: This function is not available with MSVC 6. Use qFindChild() instead if you need to support that version of the compiler.
See also findChildren() and qFindChild().
QList<T> QObject::findChildren ( const QString & name = QString() ) 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.
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 *>();
Warning: This function is not available with MSVC 6. Use qFindChildren() instead if you need to support that version of the compiler.
See also findChild() and qFindChildren().
QList<T> QObject::findChildren ( const QRegExp & regExp ) const
Это перегруженная функция, предоставленная для удобства.
Returns the children of this object that can be cast to type T and that have names matching the regular expression regExp, or an empty list if there are no such objects. The search is performed recursively.
Warning: This function is not available with MSVC 6. Use qFindChildren() instead if you need to support that version of the compiler.
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 inherits className; otherwise returns false.
A class is considered to inherit itself.
Пример:
QTimer *timer = new QTimer;
timer->inherits("QTimer");
timer->inherits("QObject");
timer->inherits("QAbstractButton");
QLayout *layout = new QLayout;
layout->inherits("QObject");
layout->inherits("QLayoutItem");
(QLayoutItem is not a QObject.)
Consider using qobject_cast<Type *>(object) instead. The method is both faster and safer.
See also metaObject() and qobject_cast().
void QObject::installEventFilter ( QObject * filterObj )
Installs an event filter filterObj on this object. Например:
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 {
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::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.
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. The inherits() 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 use staticMetaObject.
Пример:
QObject *obj = new QPushButton;
obj->metaObject()->className();
QPushButton::staticMetaObject.className();
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. Например:
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 the targetThread.
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);
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.
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.
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.
See also QSignalMapper.
void QObject::setParent ( QObject * parent )
Makes the object a child of parent.
See also parent() and QWidget::setParent().
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 )
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.
Пример:
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject(QObject *parent = 0);
protected:
void timerEvent(QTimerEvent *event);
};
MyObject::MyObject(QObject *parent)
: QObject(parent)
{
startTimer(50);
startTimer(1000);
startTimer(60000);
}
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(), 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 * comment = 0, int n = -1 ) [static]
Returns a translated version of sourceText, or sourceText itself if there is no appropriate translated version. The translation context is Object with comment (0 by default). All QObject subclasses using the Q_OBJECT macro automatically have a reimplementation of this function with the subclass name as context.
You can set the encoding for sourceText by calling QTextCodec::setCodecForTr(). By default sourceText is assumed to be in Latin-1 encoding.
Пример:
MyWindow::MyWindow()
{
QLabel *nameLabel = new QLabel(tr("Name:"));
QLabel *addressLabel = new QLabel(tr("Address:", "i.e. a postal address"));
...
}
If n >= 0, all occurrences of %n in the resulting string are replaced with a decimal representation of n. In addition, depending on n's value, the translation text may vary.
Пример:
int n = messages.count();
showMessage(tr("%n message(s) saved", "", n));
The table below shows what string is returned depending on the active translation:
| Active Translation |
n | No Translation | French | English |
0 | "0 message(s) saved" | "0 message sauvegard?" | "0 messages saved" |
1 | "1 message(s) saved" | "1 message sauvegard?" | "1 message saved" |
2 | "2 message(s) saved" | "2 messages sauvegard?s" | "2 messages saved" |
37 | "37 message(s) saved" | "37 messages sauvegard?s" | "37 messages saved" |
This idiom is more flexible than the traditional approach, i.e.,
n == 1 ? tr("%n message saved") : tr("%n messages saved")
because it also works with target languages that have several plural forms (e.g., Irish has a special "dual" form that should be used when n is 2), and it handles the n == 0 case correctly for languages such as French that require the singular. See the Qt Linguist Manual for details.
Instead of %n, you can use %Ln to produce a localized representation of n. The conversion uses the default local, set using QLocal::setDefault(). (If no default locale was specified, the "C" locale is used.)
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(), QApplication::translate(), QTextCodec::setCodecForTr(), and Internationalization with Qt.
QString QObject::trUtf8 ( const char * sourceText, const char * comment = 0, int n = -1 ) [static]
Returns a translated version of sourceText, or QString::fromUtf8(sourceText) if there is no appropriate version. It is otherwise identical to tr(sourceText, comment, n).
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.
Warning: For portability reasons, we recommend that you use escape sequences for specifying non-ASCII characters in string literals to trUtf8(). Например:
label->setText(tr("F\374r \310lise"));
See also tr(), QApplication::translate(), and Internationalization with Qt.
Описание типов
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. The inherits() 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.
Пример:
QPushButton::staticMetaObject.className();
QObject *obj = new QPushButton;
obj->metaObject()->className();
See also metaObject().
Связанные нечлены класса
typedef QObjectList
Synonym for QList<QObject *>.
T qFindChild ( const QObject * obj, const QString & name )
This function is equivalent to obj->findChild<T>(name). It is provided as a work-around for MSVC 6, which doesn't support member template functions.
See also QObject::findChild().
QList<T> qFindChildren ( const QObject * obj, const QString & name )
This function is equivalent to obj->findChildren<T>(name). It is provided as a work-around for MSVC 6, which doesn't support member template functions.
See also QObject::findChildren().
QList<T> qFindChildren ( const QObject * obj, const QRegExp & regExp )
Это перегруженная функция, предоставленная для удобства.
This function is equivalent to obj->findChildren<T>(regExp). It is provided as a work-around for MSVC 6, which doesn't support member template functions.
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.
The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.
A class is considered to inherit itself.
Пример:
QObject *obj = new QTimer;
QTimer *timer = qobject_cast<QTimer *>(obj);
QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
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().
Описание макросов
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.
Пример:
class MyClass : public QObject
{
Q_OBJECT
Q_CLASSINFO("Author", "Pierre Gendron")
Q_CLASSINFO("URL", "http:
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.
Например:
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.
Пример:
Q_FLAGS(Options Alignment)
See also Qt's Property System.
Q_INTERFACES ( ... )
This macro tells Qt which interfaces the class implements. This is used when implementing plugins.
Пример:
class BasicToolsPlugin : public QObject,
public BrushInterface,
public ShapeInterface,
public FilterInterface
{
Q_OBJECT
Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)
public:
...
};
See the Plug & Paint Basic Tools example for details.
See also Q_DECLARE_INTERFACE(), Q_EXPORT_PLUGIN2(), and How to Create Qt Plugins.
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.
Например:
#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;
};
Смотрите также Мета-объектная система, Сигналы и слоты и Система свойств Qt.
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]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool])
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.
Например:
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_SIGNALS
Use this macro to replace the signals 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.
|