QObject 类

QObject class is the base class of all Qt objects. 更多...

注意: 此类的所有函数 可重入 .

注意: 这些函数也是 thread-safe :

  • connect (const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
  • connect (const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type) const
  • connect (const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
  • connect (const QObject *sender, PointerToMemberFunction signal, Functor functor)
  • connect (const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
  • disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *method)
  • disconnect (const char *signal, const QObject *receiver, const char *method) const
  • disconnect (const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)
  • deleteLater ()

特性

公共函数

QObject (QObject * parent = nullptr)
virtual ~QObject ()
bool blockSignals (bool block )
const QObjectList & children () const
QMetaObject::Connection connect (const QObject * sender , const char * signal , const char * method , Qt::ConnectionType type = Qt::AutoConnection) const
bool disconnect (const char * signal = nullptr, const QObject * receiver = nullptr, const char * method = nullptr) const
bool disconnect (const QObject * receiver , const char * method = nullptr) const
void dumpObjectInfo () const
void dumpObjectTree () const
QList<QByteArray> dynamicPropertyNames () const
virtual bool event (QEvent * e )
virtual bool eventFilter (QObject * watched , QEvent * event )
T findChild (const QString & name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
QList<T> findChildren (const QString & name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
QList<T> findChildren (const QRegExp & regExp , Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
QList<T> findChildren (const QRegularExpression & re , Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
bool inherits (const char * className ) const
void installEventFilter (QObject * filterObj )
bool isWidgetType () const
bool isWindowType () 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 , Qt::TimerType timerType = Qt::CoarseTimer)
int startTimer (std::chrono::milliseconds time , Qt::TimerType timerType = Qt::CoarseTimer)
QThread * thread () const

公共槽

信号

void destroyed (QObject * obj = nullptr)
void objectNameChanged (const QString & objectName )

静态公共成员

QMetaObject::Connection connect (const QObject * sender , const char * signal , const QObject * receiver , const char * method , Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connection connect (const QObject * sender , const QMetaMethod & signal , const QObject * receiver , const QMetaMethod & method , Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connection connect (const QObject * sender , PointerToMemberFunction signal , const QObject * receiver , PointerToMemberFunction method , Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connection connect (const QObject * sender , PointerToMemberFunction signal , Functor functor )
QMetaObject::Connection connect (const QObject * sender , PointerToMemberFunction signal , const QObject * context , Functor functor , 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 )
bool disconnect (const QMetaObject::Connection & connection )
bool disconnect (const QObject * sender , PointerToMemberFunction signal , const QObject * receiver , PointerToMemberFunction method )
const QMetaObject staticMetaObject
QString tr (const char * sourceText , const char * disambiguation = Q_OBJECT, int n = Q_OBJECT)

保护函数

virtual void childEvent (QChildEvent * event )
virtual void connectNotify (const QMetaMethod & signal )
virtual void customEvent (QEvent * event )
virtual void disconnectNotify (const QMetaMethod & signal )
bool isSignalConnected (const QMetaMethod & signal ) const
int receivers (const char * signal ) const
QObject * sender () const
int senderSignalIndex () const
virtual void timerEvent (QTimerEvent * event )

Protected Variables

QScopedPointer<QObjectData> d_ptr

静态保护成员

const QMetaObject staticQtMetaObject
typedef QObjectList
QList<T> qFindChildren (const QObject * obj , const QRegExp & regExp )
T qobject_cast (QObject * object )
T qobject_cast (const QObject * object )

详细描述

QObject class is the base class of all Qt objects.

QObject is the heart of the Qt 对象模型 . The central feature in this model is a very powerful mechanism for seamless object communication called 信号和槽 . 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 () 和 disconnectNotify () make it possible to track connections.

QObjects organize themselves in 对象树 . 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 () 或 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 () 函数。

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 () 和 eventFilter () 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; 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 *>.

线程倾向性

A QObject instance is said to have a 线程倾向性 , or that it lives in a certain thread. When a QObject receives a queued signal posted event , the slot or event handler will run in the thread that the object lives in.

注意: QObject has no thread affinity (that is, if thread () 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, a QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread () and changed using moveToThread ().

所有 QObject 必须活在如其父级的相同线程内。因此:

注意: A QObject 's member variables do not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child's constructor , or by calling setParent (). Without this step, the object's member variables will remain in the old thread when moveToThread () 被调用。

不拷贝构造函数或赋值运算符

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY (). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt 对象模型 页面。

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.

自动连接

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 () 函数。

uic generates code that invokes this function to enable auto-connection to be performed between widgets on forms created with Qt Designer . More information about using auto-connection with Qt Designer is given in the Using a Designer UI File in Your Application section of the Qt Designer manual.

动态特性

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.

国际化 (I18n)

所有 QObject subclasses support Qt's translation features, making it possible to translate an application's user interface into different languages.

To make user-visible text translatable, it must be wrapped in calls to the tr () function. This is explained in detail in the 编写翻译源代码 文档。

另请参阅 QMetaObject , QPointer , QObjectCleanupHandler , Q_DISABLE_COPY (),和 对象树 & 所有权 .

特性文档编制

objectName : QString

此特性保持该对象的名称

可按名称 (和类型) 查找对象,使用 findChild ()。可找到一组对象采用 findChildren ().

qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
       qPrintable(objectName()), newPrecision);
							

默认情况下,此特性包含空字符串。

访问函数:

QString objectName () const
void setObjectName (const QString & name )

通知信号:

void objectNameChanged (const QString & objectName ) [see note below]

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

另请参阅 metaObject () 和 QMetaObject::className ().

成员函数文档编制

QObject:: QObject ( QObject * parent = nullptr)

构造对象采用父级对象 parent .

对象的父级可以被视为对象的所有者。例如, 对话框 父级于 OK and Cancel 按钮 (它包含的)。

父级对象的析构函数会销毁所有子级对象。

设置 parent to 0 constructs an object with no parent. If the object is a widget, it will become a top-level window.

注意: 此函数可以被援引,通过元对象系统和从 QML。见 Q_INVOKABLE .

另请参阅 parent (), findChild (),和 findChildren ().

[virtual] QObject:: ~QObject ()

销毁对象,删除其所有子级对象。

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.

警告: 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.

警告: 删除 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.

另请参阅 deleteLater ().

bool QObject:: blockSignals ( bool block )

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.

返回值是先前值的 signalsBlocked ().

注意: destroyed () 信号会被发射,即使此对象的信号已被阻塞。

当被阻塞时发出的信号,不会被缓冲。

另请参阅 signalsBlocked () 和 QSignalBlocker .

[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 the event 参数。

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 () 返回 true , a QWidget . (This is because, in the ChildAdded case, the child is not yet fully constructed, and in the ChildRemoved case it might have been destructed already).

QEvent::ChildPolished events are sent to widgets when children are polished, or when polished children are added. If you receive a child polished event, the child's construction is usually completed. However, this is not guaranteed, and multiple polish events may be delivered during the execution of a widget's constructor.

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

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

返回子级对象的列表。 QObjectList 类被定义于 <QObject> 头文件,如下所示:

第一添加子级是 first 对象在列表中,且最后添加子级是 last 对象在列表中,即:新子级被追加在末尾。

注意:列表次序改变,当 QWidget 子级 raised or lowered 。被提升 Widget 变为最后列表对象,被降低 Widget 变为第一列表对象。

另请参阅 findChild (), findChildren (), parent (),和 setParent ().

[static] QMetaObject::Connection QObject:: connect (const QObject * sender , const char * signal , const QObject * receiver , const char * method , Qt::ConnectionType type = Qt::AutoConnection)

Creates a connection of the given type signal sender object to the method receiver object. Returns a handle to the connection that can be used to disconnect it later.

You must use the SIGNAL() and SLOT() macros when specifying the signal method ,例如:

QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
                 label,  SLOT(setNum(int)));
							

This example ensures that the label always displays the current scroll bar value. Note that the signal and slots parameters must not contain any variable names, only the type. E.g. the following would not work and return false:

// WRONG
QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
                 label, SLOT(setNum(int value)));
							

A signal can also be connected to another signal:

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    MyWidget();
signals:
    void buttonClicked();
private:
    QPushButton *myButton;
};
MyWidget::MyWidget()
{
    myButton = new QPushButton(this);
    connect(myButton, SIGNAL(clicked()),
            this, SIGNAL(buttonClicked()));
}
							

In this example, the MyWidget constructor relays a signal from a private member variable, and makes it available under a name that relates to MyWidget .

A signal can be connected to many slots and signals. Many signals can be connected to one slot.

If a signal is connected to several slots, the slots are activated in the same order in which the connections were made, when the signal is emitted.

The function returns a QMetaObject::Connection that represents a handle to a connection if it successfully connects the signal to the slot. The connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of either signal or method , or if their signatures aren't compatible. You can check if the handle is valid by casting it to a bool.

By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect () call. If you pass the Qt::UniqueConnection type , the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection .

注意: Qt::UniqueConnections do not work for lambdas, non-member functions and functors; they only apply to connecting to member functions.

可选 type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message

QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)
							

call qRegisterMetaType () 以注册数据类型在建立连接之前。

注意: 此函数是 thread-safe .

另请参阅 disconnect (), sender (), qRegisterMetaType (), Q_DECLARE_METATYPE (),和 基于字符串的连接和基于函子的连接之间的差异 .

[static] QMetaObject::Connection QObject:: connect (const QObject * sender , const QMetaMethod & signal , const QObject * receiver , const QMetaMethod & method , Qt::ConnectionType type = Qt::AutoConnection)

Creates a connection of the given type signal sender object to the method receiver object. Returns a handle to the connection that can be used to disconnect it later.

The Connection handle will be invalid if it cannot create the connection, for example, the parameters were invalid. You can check if the QMetaObject::Connection is valid by casting it to a bool.

This function works in the same way as connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type) but it uses QMetaMethod to specify signal and method.

This function was introduced in Qt 4.8.

另请参阅 connect (const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type).

QMetaObject::Connection QObject:: connect (const QObject * sender , const char * signal , const char * method , Qt::ConnectionType type = Qt::AutoConnection) const

This function overloads connect ().

Connects signal 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 ().

注意: 此函数是 thread-safe .

另请参阅 disconnect ().

[static] QMetaObject::Connection QObject:: connect (const QObject * sender , PointerToMemberFunction signal , const QObject * receiver , PointerToMemberFunction method , Qt::ConnectionType type = Qt::AutoConnection)

This function overloads connect ().

Creates a connection of the given type signal sender object to the method receiver object. Returns a handle to the connection that can be used to disconnect it later.

The signal must be a function declared as a signal in the header. The slot function can be any member function that can be connected to the signal. A slot can be connected to a given signal if the signal has at least as many arguments as the slot, and there is an implicit conversion between the types of the corresponding arguments in the signal and the slot.

范例:

QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
                 label,  &QLabel::setText);
							

This example ensures that the label always displays the current line edit text.

A signal can be connected to many slots and signals. Many signals can be connected to one slot.

If a signal is connected to several slots, the slots are activated in the same order as the order the connection was made, when the signal is emitted

The function returns an handle to a connection if it successfully connects the signal to the slot. The Connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of signal (if it was not declared as a signal) You can check if the QMetaObject::Connection is valid by casting it to a bool.

By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect () call. If you pass the Qt::UniqueConnection type , the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection .

可选 type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message

QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)
							

make sure to declare the argument type with Q_DECLARE_METATYPE

Overloaded functions can be resolved with help of qOverload .

注意: 此函数是 thread-safe .

另请参阅 基于字符串的连接和基于函子的连接之间的差异 .

[static] QMetaObject::Connection QObject:: connect (const QObject * sender , PointerToMemberFunction signal , Functor functor )

This function overloads connect ().

Creates a connection from signal in sender object to functor , and returns a handle to the connection

The signal must be a function declared as a signal in the header. The slot function can be any function or functor that can be connected to the signal. A function can be connected to a given signal if the signal has at least as many argument as the slot. A functor can be connected to a signal if they have exactly the same number of arguments. There must exist implicit conversion between the types of the corresponding arguments in the signal and the slot.

范例:

void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, someFunction);
							

Lambda expressions can also be used:

QByteArray page = ...;
QTcpSocket *socket = new QTcpSocket;
socket->connectToHost("qt-project.org", 80);
QObject::connect(socket, &QTcpSocket::connected, [=] () {
        socket->write("GET " + page + "\r\n");
    });
							

The connection will automatically disconnect if the sender is destroyed. However, you should take care that any objects used within the functor are still alive when the signal is emitted.

Overloaded functions can be resolved with help of qOverload .

注意: 此函数是 thread-safe .

[static] QMetaObject::Connection QObject:: connect (const QObject * sender , PointerToMemberFunction signal , const QObject * context , Functor functor , Qt::ConnectionType type = Qt::AutoConnection)

This function overloads connect ().

Creates a connection of a given type from signal in sender object to functor 以放置在特定事件循环 context ,并返回连接的句柄。

注意: Qt::UniqueConnections do not work for lambdas, non-member functions and functors; they only apply to connecting to member functions.

The signal must be a function declared as a signal in the header. The slot function can be any function or functor that can be connected to the signal. A function can be connected to a given signal if the signal has at least as many argument as the slot. A functor can be connected to a signal if they have exactly the same number of arguments. There must exist implicit conversion between the types of the corresponding arguments in the signal and the slot.

范例:

void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, this, someFunction, Qt::QueuedConnection);
							

Lambda expressions can also be used:

QByteArray page = ...;
QTcpSocket *socket = new QTcpSocket;
socket->connectToHost("qt-project.org", 80);
QObject::connect(socket, &QTcpSocket::connected, this, [=] () {
        socket->write("GET " + page + "\r\n");
    }, Qt::AutoConnection);
							

The connection will automatically disconnect if the sender or the context is destroyed. However, you should take care that any objects used within the functor are still alive when the signal is emitted.

Overloaded functions can be resolved with help of qOverload .

注意: 此函数是 thread-safe .

This function was introduced in Qt 5.2.

[virtual protected] void QObject:: connectNotify (const QMetaMethod & signal )

This virtual function is called when something has been connected to signal in this object.

If you want to compare signal with a specific signal, you can use QMetaMethod::fromSignal () as follows:

if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
    // signal is valueChanged
}
							

警告: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.

警告: This function is called from the thread which performs the connection, which may be a different thread from the thread in which this object lives.

This function was introduced in Qt 5.0.

另请参阅 connect () 和 disconnectNotify ().

[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 the QEvent::User item of the QEvent::Type enum, and is typically a QEvent subclass. The event is passed in the event 参数。

另请参阅 event () 和 QEvent .

[slot] void QObject:: deleteLater ()

安排删除此对象。

对象将被删除,当控制返回给事件循环时。若事件循环未运行,当此函数被调用时 (如,对象调用 deleteLater() 先于 QCoreApplication::exec ()),对象会被删除,一旦事件循环被启动。若在 main 事件循环已停止之后调用 deleteLater(),对象不会被删除。从 Qt 4.8 起,若 deleteLater() 被活在未运行事件循环线程中的对象所调用,对象不会被销毁当线程完成时。

注意:进入和离开新事件循环 (如,通过打开模态对话框) 会 not 履行延迟删除;对于要被删除的对象而言,控件必须返回给调用 deleteLater() 的事件循环。这不适用于先前嵌套事件循环仍在运行时被删除的对象:Qt 事件循环就会删除这些对象,当新嵌套事件循环一开始。

注意: 多次调用此函数是安全的;当交付首个延迟删除事件时,对象的任何待决事件均将从事件队列中被移除。

注意: 此函数是 thread-safe .

另请参阅 destroyed () 和 QPointer .

[signal] void QObject:: destroyed ( QObject * obj = nullptr)

此信号被立即发射先于对象 obj is destroyed, and can not be blocked.

立即销毁所有对象的子级,在此信号被发射之后。

另请参阅 deleteLater () 和 QPointer .

[static] bool QObject:: disconnect (const QObject * sender , const char * signal , const QObject * receiver , const char * method )

Disconnects signal in object sender from method in object receiver 。返回 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.

  1. Disconnect everything connected to an object's signals:
    disconnect(myObject, 0, 0, 0);
    									

    equivalent to the non-static overloaded function

    myObject->disconnect();
    									
  2. Disconnect everything connected to a specific signal:
    disconnect(myObject, SIGNAL(mySignal()), 0, 0);
    									

    equivalent to the non-static overloaded function

    myObject->disconnect(SIGNAL(mySignal()));
    									
  3. 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.

sender may never be 0. (You cannot disconnect signals from more than one object in a single call.)

signal is 0, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.

receiver is 0, it disconnects anything connected to signal . If not, slots in objects other than receiver are not disconnected.

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.

注意: 此函数是 thread-safe .

另请参阅 connect ().

[static] bool QObject:: disconnect (const QObject * sender , const QMetaMethod & signal , const QObject * receiver , const QMetaMethod & method )

Disconnects signal in object sender from method in object receiver 。返回 true if the connection is successfully broken; otherwise returns false .

This function provides the same possibilities like disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) but uses QMetaMethod to represent the signal and the method to be disconnected.

Additionally this function returnsfalse and no signals and slots disconnected if:

  1. signal is not a member of sender class or one of its parent classes.
  2. method is not a member of receiver class or one of its parent classes.
  3. signal instance represents not a signal.

QMetaMethod() may be used as wildcard in the meaning "any signal" or "any slot in receiving object". In the same way 0 can be used for receiver in the meaning "any receiving object". In this case method should also be QMetaMethod(). sender parameter should be never 0.

This function was introduced in Qt 4.8.

另请参阅 disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *method).

bool QObject:: disconnect (const char * signal = nullptr, const QObject * receiver = nullptr, const char * method = nullptr) const

This function overloads disconnect ().

Disconnects signal from method of receiver .

A signal-slot connection is removed when either of the objects involved are destroyed.

注意: 此函数是 thread-safe .

bool QObject:: disconnect (const QObject * receiver , const char * method = nullptr) const

This function overloads disconnect ().

Disconnects all signals in this object from receiver 's method .

A signal-slot connection is removed when either of the objects involved are destroyed.

[static] bool QObject:: disconnect (const QMetaObject::Connection & connection )

Disconnect a connection.

connection is invalid or has already been disconnected, do nothing and return false.

另请参阅 connect ().

[static] bool QObject:: disconnect (const QObject * sender , PointerToMemberFunction signal , const QObject * receiver , PointerToMemberFunction method )

This function overloads diconnect().

Disconnects signal in object sender from method in object receiver 。返回 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.

  1. Disconnect everything connected to an object's signals:
    disconnect(myObject, 0, 0, 0);
    									
  2. Disconnect everything connected to a specific signal:
    disconnect(myObject, &MyObject::mySignal(), 0, 0);
    									
  3. Disconnect a specific receiver:
    disconnect(myObject, 0, myReceiver, 0);
    									
  4. Disconnect a connection from one specific signal to a specific slot:
    QObject::disconnect(lineEdit, &QLineEdit::textChanged,
                     label,  &QLabel::setText);
    									

0 may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", respectively.

sender may never be 0. (You cannot disconnect signals from more than one object in a single call.)

signal is 0, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.

receiver is 0, it disconnects anything connected to signal . If not, slots in objects other than receiver are not disconnected.

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.

注意: It is not possible to use this overload to diconnect signals connected to functors or lambda expressions. That is because it is not possible to compare them. Instead, use the overload that takes a QMetaObject::Connection

注意: 此函数是 thread-safe .

另请参阅 connect ().

[virtual protected] void QObject:: disconnectNotify (const QMetaMethod & signal )

This virtual function is called when something has been disconnected from signal in this object.

connectNotify () for an example of how to compare signal with a specific signal.

If all signals were disconnected from this object (e.g., the signal argument to disconnect () was 0), disconnectNotify() is only called once, and the signal will be an invalid QMetaMethod ( QMetaMethod::isValid () 返回 false ).

警告: This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.

警告: This function is called from the thread which performs the disconnection, which may be a different thread from the thread in which this object lives. This function may also be called with a QObject internal mutex locked. It is therefore not allowed to re-enter any of any QObject functions from your reimplementation and if you lock a mutex in your reimplementation, make sure that you don't call QObject functions with that mutex held in other places or it will result in a deadlock.

This function was introduced in Qt 5.0.

另请参阅 disconnect () 和 connectNotify ().

void QObject:: dumpObjectInfo () const

Dumps information about signal connections, etc. for this object to the debug output.

注意: 在 Qt 5.9 之前,此函数不是 const。

另请参阅 dumpObjectTree ().

void QObject:: dumpObjectTree () const

Dumps a tree of children to the debug output.

注意: 在 Qt 5.9 之前,此函数不是 const。

另请参阅 dumpObjectInfo ().

QList < QByteArray > QObject:: dynamicPropertyNames () const

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

This function was introduced in Qt 4.2.

[virtual] bool QObject:: event ( QEvent * e )

此虚函数接收对象事件并返回 true,若事件 e 被识别并被处理。

event() 函数可以被重实现,以定制对象行为。

确保调用父级事件类实现,为所有未处理事件。

范例:

class MyClass : public QWidget
{
    Q_OBJECT
public:
    MyClass(QWidget *parent = 0);
    ~MyClass();
    bool event(QEvent* ev) override
    {
        if (ev->type() == QEvent::PolishRequest) {
            // overwrite handling of PolishRequest if any
            doThings();
            return true;
        } else  if (ev->type() == QEvent::Show) {
            // complement handling of Show if any
            doThings2();
            QWidget::event(ev);
            return true;
        }
        // Make sure the rest of events are handled
        return QWidget::event(ev);
    }
};
							

另请参阅 installEventFilter (), timerEvent (), QCoreApplication::sendEvent (),和 QCoreApplication::postEvent ().

[virtual] bool QObject:: eventFilter ( QObject * watched , QEvent * event )

过滤事件,若此对象已被安装成事件过滤器为 watched 对象。

在此函数的重实现中,若希望过滤 event 即:停止进一步处理,返回 true;否则返回 false。

范例:

class MainWindow : public QMainWindow
{
public:
    MainWindow();
protected:
    bool eventFilter(QObject *obj, QEvent *ev) override;
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);
    }
}
							

注意:在以上范例中,未处理事件被传递给基类的 eventFilter() 函数,因为基类可能出于其内部目重实现了 eventFilter()。

某些事件,如 QEvent::ShortcutOverride 必须被明确接受 (通过调用 accept() ) 为阻止传播。

警告: 若在此函数中删除接收者对象,确保返回 true。否则,Qt 将把事件转发给被删除对象,且程序可能崩溃。

另请参阅 installEventFilter ().

T QObject:: findChild (const QString & name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

Returns the child of this object that can be cast into type T and that is called name , or 0 if there is no such object. Omitting the name argument causes all object names to be matched. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

If there is more than one child matching the search, the most direct ancestor is returned. If there are several direct ancestors, it is undefined which one will be returned. In that case, findChildren () should be used.

This example returns a child QPushButton of parentWidget named "button1" ,即使按钮不是父级的直接子级:

QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
							

此范例返回 QListWidget child of parentWidget :

QListWidget *list = parentWidget->findChild<QListWidget *>();
							

This example returns a child QPushButton of parentWidget (its direct parent) named "button1" :

QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildrenOnly);
							

此范例返回 QListWidget child of parentWidget , its direct parent:

QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildrenOnly);
							

另请参阅 findChildren ().

QList < T > QObject:: findChildren (const QString & name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. Omitting the name argument causes all object names to be matched. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

The following example shows how to find a list of child QWidget s of the specified parentWidget named widgetname :

QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");
							

This example returns all QPushButton s that are children of parentWidget :

QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();
							

This example returns all QPushButton s that are immediate children of parentWidget :

QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildrenOnly);
							

另请参阅 findChild ().

QList < T > QObject:: findChildren (const QRegExp & regExp , Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

This function overloads findChildren ().

Returns the children of this object that can be cast to type T and that have names matching the regular expression regExp , or an empty list if there are no such objects. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

QList < T > QObject:: findChildren (const QRegularExpression & re , Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

This function overloads findChildren ().

Returns the children of this object that can be cast to type T and that have names matching the regular expression re , or an empty list if there are no such objects. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

This function was introduced in Qt 5.0.

bool QObject:: inherits (const char * className ) const

返回 true 若此对象是类实例,继承 className QObject 子类,继承 className ;否则返回 false .

类被认为继承本身。

范例:

QTimer *timer = new QTimer;         // QTimer inherits QObject
timer->inherits("QTimer");          // returns true
timer->inherits("QObject");         // returns true
timer->inherits("QAbstractButton"); // returns false
// QVBoxLayout inherits QObject and QLayoutItem
QVBoxLayout *layout = new QVBoxLayout;
layout->inherits("QObject");        // returns true
layout->inherits("QLayoutItem");    // returns true (even though QLayoutItem is not a QObject)
							

若为铸造目的需要确定对象是否为特定类的实例,考虑使用 qobject_cast <Type *>(object) instead.

另请参阅 metaObject () 和 qobject_cast ().

void QObject:: installEventFilter ( QObject * filterObj )

安装事件过滤器 filterObj 在此对象。例如:

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 接收事件凭借其 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) override;
};
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);
							

QShortcut class, for example, uses this technique to intercept shortcut key presses.

警告: 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).

另请参阅 removeEventFilter (), eventFilter (),和 event ().

[protected] bool QObject:: isSignalConnected (const QMetaMethod & signal ) const

返回 true signal is connected to at least one receiver, otherwise returns false .

signal must be a signal member of this object, otherwise the behaviour is undefined.

static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
if (isSignalConnected(valueChangedSignal)) {
    QByteArray data;
    data = get_the_value();       // expensive operation
    emit valueChanged(data);
}
							

As the code snippet above illustrates, you can use this function to avoid emitting a signal that nobody listens to.

警告: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.

This function was introduced in Qt 5.0.

bool QObject:: isWidgetType () const

返回 true if the object is a widget; otherwise returns false .

调用此函数相当于调用 inherits("QWidget") ,除了它更快。

bool QObject:: isWindowType () const

返回 true 若对象是窗口;否则返回 false .

调用此函数相当于调用 inherits("QWindow") ,除了它更快。

void QObject:: killTimer ( int id )

杀除计时器,采用计时器标识符 id .

计时器标识符被返回通过 startTimer () 当计时器事件被启动时。

另请参阅 timerEvent () 和 startTimer ().

[virtual] const QMetaObject *QObject:: metaObject () const

返回指向此对象的元对象的指针。

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();             // returns "QPushButton"
QPushButton::staticMetaObject.className();  // returns "QPushButton"
							

另请参阅 staticMetaObject .

void QObject:: moveToThread ( QThread * targetThread )

更改此对象及其子级的线程亲缘关系。对象无法被移动,若它有父级。事件处理将继续在 targetThread .

To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives. For example:

myObject->moveToThread(QApplication::instance()->thread());
							

targetThread is nullptr , all event processing for this object and its children stops, as they are no longer associated with any thread.

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 , provided it is non-null: when it is nullptr , no event processing for this object or its children can happen, as they are no longer associated with any thread.

警告: 此函数是 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. There is one exception to this rule however: objects with no thread affinity can be "pulled" to the current thread.

另请参阅 thread ().

[signal] void QObject:: objectNameChanged (const QString & objectName )

此信号被发射在对象名称改变之后。新对象名称被传递作为 objectName .

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

注意: 通知信号为特性 objectName .

另请参阅 QObject::objectName .

QObject *QObject:: parent () const

返回指向父级对象的指针。

另请参阅 setParent () 和 children ().

QVariant QObject:: property (const char * name ) const

返回值,为对象的 name 特性。

返回的变体是无效的,若没有这样的特性存在。

所有可用特性的有关信息,提供透过 metaObject () 和 dynamicPropertyNames ().

另请参阅 setProperty (), QVariant::isValid (), metaObject (),和 dynamicPropertyNames ().

[protected] int QObject:: receivers (const char * signal ) const

Returns the number of receivers connected to the signal .

Since both slots and signals can be used as receivers for signals, and the same connections can be made many times, the number of receivers is the same as the number of connections made from this signal.

When calling this function, you can use the SIGNAL() macro to pass a specific signal:

if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
    QByteArray data;
    get_the_value(&data);       // expensive operation
    emit valueChanged(data);
}
							

警告: 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.

另请参阅 isSignalConnected ().

void QObject:: removeEventFilter ( QObject * obj )

Removes an event filter object obj from this object. The request is ignored if such an event filter has not been installed.

All event filters for this object are automatically removed when this object is destroyed.

It is always safe to remove an event filter, even during event filter activation (i.e. from the eventFilter () function).

另请参阅 installEventFilter (), eventFilter (),和 event ().

[protected] QObject *QObject:: sender () const

Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns nullptr . 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.

警告: 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.

警告: As mentioned above, the return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.

另请参阅 senderSignalIndex ().

[protected] int QObject:: senderSignalIndex () const

Returns the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender (). If called outside of a slot activated by a signal, -1 is returned.

For signals with default parameters, this function will always return the index with all parameters, regardless of which was used with connect (). For example, the signal destroyed(QObject *obj = 0) will have two different indexes (with and without the parameter), but this function will always return the index with a parameter. This does not apply when overloading signals with different parameters.

警告: 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.

警告: The return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.

This function was introduced in Qt 4.8.

另请参阅 sender (), QMetaObject::indexOfSignal (),和 QMetaObject::method ().

void QObject:: setParent ( QObject * parent )

使对象子级 parent .

另请参阅 parent () 和 children ().

bool QObject:: setProperty (const char * name , const QVariant & value )

Sets the value of the object's name property to value .

If the property is defined in the class using Q_PROPERTY then true is returned on success and false otherwise. If the property is not defined using Q_PROPERTY , and therefore not listed in the meta-object, it is added as a dynamic property and false is returned.

所有可用特性的有关信息,提供透过 metaObject () 和 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.

注意: Dynamic properties starting with "_q_" are reserved for internal purposes.

另请参阅 property (), metaObject (), dynamicPropertyNames (),和 QMetaProperty::write ().

bool QObject:: signalsBlocked () const

返回 true 若信号被阻塞;否则返回 false .

信号不被阻塞,默认情况下。

另请参阅 blockSignals () 和 QSignalBlocker .

int QObject:: startTimer ( int interval , Qt::TimerType timerType = Qt::CoarseTimer)

Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.

A timer event will occur every interval milliseconds until killTimer () is called. If interval is 0, then the timer event occurs once every time there are no more window system events to process.

The virtual timerEvent () function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events.

If multiple timers are running, the QTimerEvent::timerId () can be used to find out which timer was activated.

范例:

class MyObject : public QObject
{
    Q_OBJECT
public:
    MyObject(QObject *parent = 0);
protected:
    void timerEvent(QTimerEvent *event) override;
};
MyObject::MyObject(QObject *parent)
    : QObject(parent)
{
    startTimer(50);     // 50-millisecond timer
    startTimer(1000);   // 1-second timer
    startTimer(60000);  // 1-minute timer
    using namespace std::chrono;
    startTimer(milliseconds(50));
    startTimer(seconds(1));
    startTimer(minutes(1));
    // since C++14 we can use std::chrono::duration literals, e.g.:
    startTimer(100ms);
    startTimer(5s);
    startTimer(2min);
    startTimer(1h);
}
void MyObject::timerEvent(QTimerEvent *event)
{
    qDebug() << "Timer ID:" << event->timerId();
}
							

注意: QTimer 's accuracy depends on the underlying operating system and hardware. The timerType argument allows you to customize the accuracy of the timer. See Qt::TimerType for information on the different timer types. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.

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.

另请参阅 timerEvent (), killTimer (),和 QTimer::singleShot ().

int QObject:: startTimer ( std::chrono::milliseconds time , Qt::TimerType timerType = Qt::CoarseTimer)

这是重载函数。

Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.

A timer event will occur every time interval until killTimer () is called. If time is equal to std::chrono::duration::zero() , 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) override;
};
MyObject::MyObject(QObject *parent)
    : QObject(parent)
{
    startTimer(50);     // 50-millisecond timer
    startTimer(1000);   // 1-second timer
    startTimer(60000);  // 1-minute timer
    using namespace std::chrono;
    startTimer(milliseconds(50));
    startTimer(seconds(1));
    startTimer(minutes(1));
    // since C++14 we can use std::chrono::duration literals, e.g.:
    startTimer(100ms);
    startTimer(5s);
    startTimer(2min);
    startTimer(1h);
}
void MyObject::timerEvent(QTimerEvent *event)
{
    qDebug() << "Timer ID:" << event->timerId();
}
							

注意: QTimer 's accuracy depends on the underlying operating system and hardware. The timerType argument allows you to customize the accuracy of the timer. See Qt::TimerType for information on the different timer types. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.

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.

This function was introduced in Qt 5.9.

另请参阅 timerEvent (), killTimer (),和 QTimer::singleShot ().

QThread *QObject:: thread () const

返回对象所在的线程。

另请参阅 moveToThread ().

[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 the event 参数。

另请参阅 startTimer (), killTimer (),和 event ().

[static] QString QObject:: tr (const char * sourceText , const char * disambiguation = Q_OBJECT, int n = Q_OBJECT)

返回翻译版本的 sourceText , optionally based on a disambiguation string and value of n for strings containing plurals; otherwise returns QString::fromUtf8 ( sourceText ) if no appropriate translated string is available.

范例:

void MainWindow::createActions()
{
    QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
    ...
							

If the same sourceText is used in different roles within the same context, an additional identifying string may be passed in disambiguation (0 by default). In Qt 4.4 and earlier, this was the preferred way to pass comments to translators.

范例:

MyWindow::MyWindow()
{
    QLabel *senderLabel = new QLabel(tr("Name:"));
    QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
    ...
							

编写翻译源代码 for a detailed description of Qt's translation mechanisms in general, and the Disambiguation section for information on disambiguation.

警告: 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.

另请参阅 QCoreApplication::translate () 和 Qt 国际化 .

成员变量文档编制

const QMetaObject QObject:: staticMetaObject

此变量存储类的元对象。

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();  // returns "QPushButton"
QObject *obj = new QPushButton;
obj->metaObject()->className();             // returns "QPushButton"
							

另请参阅 metaObject ().

相关非成员

T qobject_cast ( QObject * object )

T qobject_cast (const QObject * object )

返回给定 object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.

类 T 必须继承 (直接或间接) QObject 并被声明采用 Q_OBJECT 宏。

类被认为继承本身。

范例:

QObject *obj = new QTimer;          // QTimer inherits QObject
QTimer *timer = qobject_cast<QTimer *>(obj);
// timer == (QObject *)obj
QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
// button == 0
							

qobject_cast () 函数行为类似于标准 C++ dynamic_cast() ,它的优点是不要求 RTTI 支持,且跨动态库边界工作。

qobject_cast () 也可以与接口结合使用;见 插件和描绘 范例了解细节。

警告: 若 T 未被声明采用 Q_OBJECT 宏,此函数的返回值是不确定的。

另请参阅 QObject::inherits ().

typedef QObjectList

同义词为 QList < QObject *>.

QList < T > qFindChildren (const QObject * obj , const QRegExp & regExp )

此函数重载 qFindChildren()。

此函数相当于 obj -> findChildren <T>( regExp ).

注意: 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.

另请参阅 QObject::findChildren ().

T qobject_cast ( QObject * object )

T qobject_cast (const QObject * object )

宏文档编制

QT_NO_NARROWING_CONVERSIONS_IN_CONNECT

Defining this macro will disable narrowing and floating-point-to-integral conversions between the arguments carried by a signal and the arguments accepted by a slot, when the signal and the slot are connected using the PMF-based syntax.

This function was introduced in Qt 5.8.

另请参阅 QObject::connect .

Q_CLASSINFO ( Name , )

This macro associates extra information to the class, which is available using QObject::metaObject (). Qt makes only limited use of this feature, in the Active Qt , Qt D-Bus and Qt QML .

The extra information takes the form of a Name string and a literal string.

范例:

class MyClass : public QObject
{
    Q_OBJECT
    Q_CLASSINFO("Author", "Pierre Gendron")
    Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")
public:
    ...
};
							

另请参阅 QMetaObject::classInfo (), QAxFactory , 使用 Qt D-Bus 适配器 ,和 Extending QML .

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 &) = delete;
    MyClass &operator=(const MyClass &) = delete;
};
							

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

This macro registers an enum type with the meta-object system. It must be placed after the enum declaration in a class that has the Q_OBJECT Q_GADGET macro. For namespaces use Q_ENUM_NS () 代替。

例如:

class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject *parent = 0);
    ~MyClass();
    enum Priority { High, Low, VeryHigh, VeryLow };
    Q_ENUM(Priority)
    void setPriority(Priority priority);
    Priority priority() const;
};
							

Enumerations that are declared with Q_ENUM have their QMetaEnum registered in the enclosing QMetaObject . You can also use QMetaEnum::fromType () to get the QMetaEnum .

Registered enumerations are automatically registered also to the Qt meta type system, making them known to QMetaType without the need to use Q_DECLARE_METATYPE (). This will enable useful features; for example, if used in a QVariant , you can convert them to strings. Likewise, passing them to QDebug will print out their names.

Mind that the enum values are stored as signed int in the meta object system. Registering enumerations with values outside the range of values valid for int will lead to overflows and potentially undefined behavior when accessing them through the meta object system. QML, for example, does access registered enumerations through the meta object system.

This function was introduced in Qt 5.5.

另请参阅 Qt's Property System .

Q_ENUM_NS ( ... )

This macro registers an enum type with the meta-object system. It must be placed after the enum declaration in a namespace that has the Q_NAMESPACE macro. It is the same as Q_ENUM but in a namespace.

Enumerations that are declared with Q_ENUM_NS have their QMetaEnum registered in the enclosing QMetaObject . You can also use QMetaEnum::fromType () to get the QMetaEnum .

Registered enumerations are automatically registered also to the Qt meta type system, making them known to QMetaType without the need to use Q_DECLARE_METATYPE (). This will enable useful features; for example, if used in a QVariant , you can convert them to strings. Likewise, passing them to QDebug will print out their names.

Mind that the enum values are stored as signed int in the meta object system. Registering enumerations with values outside the range of values valid for int will lead to overflows and potentially undefined behavior when accessing them through the meta object system. QML, for example, does access registered enumerations through the meta object system.

This function was introduced in Qt 5.8.

另请参阅 Qt's Property System .

Q_FLAG ( ... )

This macro registers a single flags type with 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 namespaces use Q_FLAG_NS () 代替。

The macro must be placed after the enum declaration.

For example, in QLibrary LoadHints flag is declared in the following way:

class QLibrary : public QObject
{
    Q_OBJECT
public:
    ...
    enum LoadHint {
        ResolveAllSymbolsHint = 0x01,
        ExportExternalSymbolsHint = 0x02,
        LoadArchiveMemberHint = 0x04
    };
    Q_DECLARE_FLAGS(LoadHints, LoadHint)
    Q_FLAG(LoadHints)
    ...
}
							

The declaration of the flags themselves is performed in the public section of the QLibrary class itself, using the Q_DECLARE_FLAGS () macro.

注意: The Q_FLAG macro takes care of registering individual flag values with the meta-object system, so it is unnecessary to use Q_ENUM () in addition to this macro.

This function was introduced in Qt 5.5.

另请参阅 Qt's Property System .

Q_FLAG_NS ( ... )

This macro registers a single flags type with the meta-object system. It is used in a namespace that has the Q_NAMESPACE macro, to declare that values of a given enum can be used as flags and combined using the bitwise OR operator. It is the same as Q_FLAG but in a namespace.

The macro must be placed after the enum declaration.

注意: The Q_FLAG_NS macro takes care of registering individual flag values with the meta-object system, so it is unnecessary to use Q_ENUM_NS () in addition to this macro.

This function was introduced in Qt 5.8.

另请参阅 Qt's Property System .

Q_GADGET

The Q_GADGET macro is a lighter version of the Q_OBJECT macro for classes that do not inherit from QObject but still want to use some of the reflection capabilities offered by QMetaObject . Just like the Q_OBJECT macro, it must appear in the private section of a class definition.

Q_GADGETs can have Q_ENUM , Q_PROPERTY and Q_INVOKABLE , but they cannot have signals or slots.

Q_GADGET makes a class member, staticMetaObject , available. staticMetaObject 是类型 QMetaObject and provides access to the enums declared with Q_ENUMS.

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_PLUGIN_METADATA(IID "org.qt-project.Qt.Examples.PlugAndPaint.BrushInterface" FILE "basictools.json")
    Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)
public:
    ...
};
							

Plug & Paint Basic Tools 范例了解细节。

另请参阅 Q_DECLARE_INTERFACE (), Q_PLUGIN_METADATA (),和 如何创建 Qt 插件 .

Q_INVOKABLE

Apply this macro to declarations of member functions to allow them to be invoked via the meta-object system. The macro is written before the return type, as shown in the following example:

class Window : public QWidget
{
    Q_OBJECT
public:
    Window();
    void normalMethod();
    Q_INVOKABLE void invokableMethod();
};
							

invokableMethod() function is marked up using Q_INVOKABLE, causing it to be registered with the meta-object system and enabling it to be invoked using QMetaObject::invokeMethod (). Since normalMethod() function is not registered in this way, it cannot be invoked using QMetaObject::invokeMethod ().

If an invokable member function returns a pointer to a QObject or a subclass of QObject and it is invoked from QML, special ownership rules apply. See Data Type Conversion Between QML and C++ 了解更多信息。

Q_NAMESPACE

The Q_NAMESPACE macro can be used to add QMetaObject capabilities to a namespace.

Q_NAMESPACEs can have Q_CLASSINFO , Q_ENUM_NS , Q_FLAG_NS , but they cannot have Q_ENUM , Q_FLAG , Q_PROPERTY , Q_INVOKABLE , signals nor slots.

Q_NAMESPACE makes an external variable, staticMetaObject , available. staticMetaObject 是类型 QMetaObject and provides access to the enums declared with Q_ENUM_NS / Q_FLAG_NS .

This function was introduced in Qt 5.8.

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

注意: This macro requires the class to be a subclass of QObject 。使用 Q_GADGET instead of Q_OBJECT to enable the meta object system's support for enums in a class that is not a QObject subclass.

另请参阅 元对象系统 , 信号和槽 ,和 Qt's Property System .

Q_PROPERTY ( ... )

This macro is used for declaring properties in classes that inherit QObject . Properties behave like class data members, but they have additional features accessible through the 元对象系统 .

Q_PROPERTY(type name
           (READ getFunction [WRITE setFunction] |
            MEMBER memberName [(READ getFunction | WRITE setFunction)])
           [RESET resetFunction]
           [NOTIFY notifySignal]
           [REVISION int]
           [DESIGNABLE bool]
           [SCRIPTABLE bool]
           [STORED bool]
           [USER bool]
           [CONSTANT]
           [FINAL])
							

The property name and type and the READ function are required. The type can be any type supported by QVariant , or it can be a user-defined type. The other items are optional, but a WRITE function is common. The attributes default to true except USER , which defaults to false.

例如:

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 .

另请参阅 Qt's Property System .

Q_REVISION

Apply this macro to declarations of member functions to tag them with a revision number in the meta-object system. The macro is written before the return type, as shown in the following example:

class Window : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(int normalProperty READ normalProperty)
    Q_PROPERTY(int newProperty READ newProperty REVISION 1)
public:
    Window();
    int normalProperty();
    int newProperty();
public slots:
    void normalMethod();
    Q_REVISION(1) void newMethod();
};
							

This is useful when using the meta-object system to dynamically expose objects to another API, as you can match the version expected by multiple versions of the other API. Consider the following simplified example:

    Window window;
    int expectedRevision = 0;
    const QMetaObject *windowMetaObject = window.metaObject();
    for (int i=0; i < windowMetaObject->methodCount(); i++)
        if (windowMetaObject->method(i).revision() <= expectedRevision)
            exposeMethod(windowMetaObject->method(i));
    for (int i=0; i < windowMetaObject->propertyCount(); i++)
        if (windowMetaObject->property(i).revision() <= expectedRevision)
            exposeProperty(windowMetaObject->property(i));
							

Using the same Window class as the previous example, the newProperty and newMethod would only be exposed in this code when the expected version is 1 or greater.

Since all methods are considered to be in revision 0 if untagged, a tag of Q_REVISION(0) is invalid and ignored.

This tag is not used by the meta-object system itself. Currently this is only used by the QtQml 模块。

For a more generic string tag, see QMetaMethod::tag ()

另请参阅 QMetaMethod::revision ().

Q_SET_OBJECT_NAME ( 对象 )

This macro assigns 对象 the objectName "Object".

It doesn't matter whether 对象 is a pointer or not, the macro figures that out by itself.

This function was introduced in Qt 5.0.

另请参阅 QObject::objectName ().

Q_SIGNAL

This is an additional macro that allows you to mark a single function as a signal. It can be quite useful, especially when you use a 3rd-party source code parser which doesn't understand a signals or Q_SIGNALS groups.

Use this macro to replace the signals keyword in class declarations, when you want to use Qt Signals and Slots with 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_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_SLOT

This is an additional macro that allows you to mark a single function as a slot. It can be quite useful, especially when you use a 3rd-party source code parser which doesn't understand a slots or Q_SLOTS groups.

Use this macro to replace the slots keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism .

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.

Q_SLOTS

Use this macro to replace the slots keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism .

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.