QObject 类

QObject 类是所有 Qt 对象的基类。 更多...

头: #include <QObject>
qmake: QT += core
继承者:

QAbstractAnimation , QAbstractEventDispatcher , QAbstractItemModel , QAbstractState , QAbstractTransition , QCoreApplication , QEventLoop , QFileSelector , QFileSystemWatcher , QIODevice , QItemSelectionModel , QLibrary , QMimeData , QObjectCleanupHandler , QPluginLoader , QSettings , QSharedMemory , QSignalMapper , QSocketNotifier , QThread , QThreadPool , QTimeLine , QTimer , QTranslator ,和 QWinEventNotifier

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

注意: 这些函数也是 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 deleteLater ()

信号

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 )

保护变量

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 )

QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
Q_CLASSINFO ( Name , Value )
Q_DISABLE_COPY ( Class )
Q_EMIT
Q_ENUM ( ... )
Q_ENUM_NS ( ... )
Q_FLAG ( ... )
Q_FLAG_NS ( ... )
Q_GADGET
Q_INTERFACES ( ... )
Q_INVOKABLE
Q_NAMESPACE
Q_OBJECT
Q_PROPERTY ( ... )
Q_REVISION
Q_SET_OBJECT_NAME ( Object )
Q_SIGNAL
Q_SIGNALS
Q_SLOT
Q_SLOTS

详细描述

QObject 类是所有 Qt 对象的基类。

QObject 是心脏在 Qt 对象模型 。该模型的中心特征是非常强大的无缝对象通信机制,称为 信号和槽 。可以连接信号到槽采用 connect () 和销毁连接采用 disconnect ()。为避免从不结束通知循环,可以临时阻塞信号采用 blockSignals ()。保护函数 connectNotify () 和 disconnectNotify () 使之可能跟踪连接。

QObject 组织自身在 对象树 . When you create a QObject with another object as parent, the object will automatically add itself to the parent's children () 列表。父级拥有对象的所有权;即:它将在其析构函数中自动删除其子级。可以查找对象通过名称和可选类型,使用 findChild () 或 findChildren ().

每个对象都有 objectName () 且可以找到其类名凭借相应 metaObject () (见 QMetaObject::className ()). You can determine whether the object's class inherits another class in the QObject inheritance hierarchy by using the inherits () 函数。

当对象被删除时,它发射 destroyed () 信号。可以捕获此信号以避免 QObjects 的悬空引用。

QObjects 可以接收事件透过 event () 和过滤其它对象的事件。见 installEventFilter () 和 eventFilter () 了解细节。方便处理程序 childEvent (),可以重实现以捕获子级事件。

Last but not least, QObject provides the basic timer support in Qt; see QTimer 了解计时器的高级支持。

预告 Q_OBJECT 宏是强制性的,对于实现信号、槽或特性的任何对象而言。还需要运行 元对象编译器 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.

所有 Qt 小部件继承 QObject . The convenience function isWidgetType () 返回对象是否是实际 Widget。它快得多相比 qobject_cast < QWidget *>( obj ) 或 obj -> inherits (" QWidget ").

某些 QObject 函数,如 children (),返回 QObjectList . QObjectList 是 typedef 对于 QList < QObject *>.

线程倾向性

A QObject instance is said to have a 线程倾向性 ,或者它 lives in a certain thread. When a QObject 接收 队列信号 张贴事件 ,槽或事件处理程序将运行在对象存活的线程中。

注意: QObject has no thread affinity (that is, if thread () 返回 0),或者若它存活在没有正运行事件循环的线程中,那么它无法接收队列信号或张贴事件。

默认情况下, QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread () 和改变使用 moveToThread ().

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

注意: A QObject 的成员变量 do not 自动变为其子级。父/子关系的设置必须通过将指针传递给子级的 constructor ,或者通过调用 setParent ()。没有这一步,对象的成员变量会留在旧线程中当 moveToThread () 被调用。

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

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private 区间采用宏 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 标识 vs 值 在 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 生成援引此函数的代码,以使表单小部件之间能够履行自动连接,创建采用 Qt Designer 。更多信息关于使用自动连接采用 Qt Designer 的给出在 在应用程序中使用 Designer UI 文件 章节的 Qt Designer 手册。

动态特性

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 () 读取它们和 setProperty () 写入它们。

从 Qt 4.3 起,动态特性的支持通过 Qt Designer ,且标准 Qt Widget 和用户创建的表单两者都可以赋予动态特性。

国际化 (I18n)

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

为使对用户可见的文本可翻译,必须将它包裹在调用 tr () 函数。这的详细解释在 编写翻译源代码 文档。

另请参阅 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 为 0 构造没有父级的对象。若对象是 Widget,它将变为顶层窗口。

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

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

[virtual] QObject:: ~QObject ()

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

自动断开到/自对象的所有信号连接,并从事件队列移除对象的任何待决张贴事件。不管怎样,经常更安全使用 deleteLater () 而不是删除 QObject 子类直接。

警告: 删除所有子级对象。若这些对象中的任一在堆栈 (或全局) 中,程序迟早会崩溃。不推荐从父级外部保持子级对象的指针。若仍然这样做, destroyed () 信号给予机会以检测对象何时被销毁。

警告: 删除 QObject 当等待交付的待决事件会导致崩溃时。不得删除 QObject 直接若它存在于与目前执行线程不同的线程中。使用 deleteLater () 代替,将导致事件循环删除对象在所有待决事件被交付给对象之后。

另请参阅 deleteLater ().

bool QObject:: blockSignals ( bool block )

block 为 true,阻塞由此对象发射的信号 (即:发射信号不会援引与其连接的任何东西)。若 block 为 false,不会发生这种阻塞。

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

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

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

另请参阅 signalsBlocked () 和 QSignalBlocker .

[virtual protected] void QObject:: childEvent ( QChildEvent * event )

可以在子类中重实现此事件处理程序以接收子级事件。事件被传入 event 参数。

QEvent::ChildAdded and QEvent::ChildRemoved 事件被发送给对象,当添加或移除子级时。在这 2 种情况下,只能依赖的子级是 QObject ,或者若 isWidgetType () 返回 true QWidget 。(这是因为,在 ChildAdded 情况下,子级尚未被完全构造,而在 ChildRemoved 情况下,它可能已经被销毁)。

QEvent::ChildPolished 事件被发送给 Widget 当子级被抛光时,或者当添加抛光子级时。若收到子级抛光事件,子级的构造通常已完成。不管怎样,这不保证,且在 Widget 构造函数执行期间可能交付多个抛光事件。

对于每个子级 Widget,接收一个 ChildAdded 事件,零个或多个 ChildPolished 事件,和一个 ChildRemoved 事件。

ChildPolished 事件被省略若子级立即被移除在被添加之后。若子级在构建和销毁期间中被多次抛光,则可能收到同一子级的几个子级抛光事件,每次采用不同虚拟表格。

另请参阅 event ().

const QObjectList &QObject:: children () const

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

typedef QList<QObject*> QObjectList;
					

第一添加子级是 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)

创建连接为给定 type signal sender 对象到 method receiver 对象。返回可用于稍后断开连接的连接句柄。

必须使用 SIGNAL() and SLOT() 宏当指定 signal method ,例如:

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

此范例确保标签始终显示当前滚动条值。注意,信号和槽参数不得包含任何变量名,只能包含类型。如,以下将不工作且返回 false:

// WRONG
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()));
}
					

在此范例中, MyWidget 构造函数中继来自私有成员变量的信号,并使它可用当名称相关 MyWidget .

信号可以连接到多个槽和信号。多个信号可以连接到一个槽。

若信号连接到几个槽,当发射信号时,这些槽按制作连接的相同次序被激活。

函数返回 QMetaObject::Connection 表示要连接的句柄,若成功将信号连接到槽。连接句柄将是无效的若它无法创建连接,例如,若 QObject 无法验证存在 signal or method ,或若它们的签名不兼容。可以校验句柄是否有效,通过将它铸造成布尔。

默认情况下,制作的每个连接都会发出信号;重复连接发射 2 个信号。可以断开所有这些连接采用一个 disconnect () 调用。若传递 Qt::UniqueConnection type ,只在不重复时才制作连接。若已经重复 (准确相同的信号到同一对象中准确相同的槽),连接将失败且连接会返回无效 QMetaObject::Connection .

注意: Qt::UniqueConnections 不工作于 Lambda、非成员函数及函子;它们仅适用于连接到成员函数。

可选 type 参数描述要建立的连接类型。尤其,它确定特定信号是立即交付给槽,还是稍后排队交付。若信号排队,参数必须是 Qt 元对象系统已知类型,因为 Qt 需要拷贝自变量以将它们存储在幕后事件中。若试着使用排队连接且获得错误消息

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)

创建连接为给定 type signal sender 对象到 method receiver 对象。返回可用于稍后断开连接的连接句柄。

连接句柄将是无效的 (例如:参数无效),若它不能创建连接。可以校验若 QMetaObject::Connection 有效,通过将它铸造成布尔。

此函数的工作方式相同如 connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type) 但它使用 QMetaMethod 来指定信号和方法。

该函数在 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

此函数重载 connect ().

连接 signal sender 对象到此对象的 method .

相当于 connect( sender , signal , this , method , type ).

每个建立连接都会发射信号,因此重复连接会发射 2 个信号。可以断开连接使用 disconnect ().

注意: 此函数是 thread-safe .

另请参阅 disconnect ().

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

此函数重载 connect ().

创建连接为给定 type signal sender 对象到 method receiver 对象。返回可用于稍后断开连接的连接句柄。

信号必须是在 Header 头中声明作为信号的函数。槽函数可以是能连接到信号的任何成员函数。槽可以连接到给定信号,若信号拥有至少如槽一样多的自变量,且信号和槽中的相应自变量类型之间存在隐式转换。

范例:

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

此范例确保标签始终显示当前行编辑文本。

信号可以连接到多个槽和信号。多个信号可以连接到一个槽。

若信号被连接到几个槽,这些槽将按制作连接的相同次序被激活,当发射信号时

函数返回连接句柄,若它将信号成功连接到槽。连接句柄将是无效的,若它不能创建连接,例如,若 QObject 无法验证是否存在 signal (若它未被声明成信号) 可以校验若 QMetaObject::Connection 有效,通过将它铸造成布尔。

默认情况下,制作的每个连接都会发出信号;重复连接发射 2 个信号。可以断开所有这些连接采用一个 disconnect () 调用。若传递 Qt::UniqueConnection type ,只在不重复时才制作连接。若已经重复 (准确相同的信号到同一对象中准确相同的槽),连接将失败且连接会返回无效 QMetaObject::Connection .

可选 type 参数描述要建立的连接类型。尤其,它确定特定信号是立即交付给槽,还是稍后排队交付。若信号排队,参数必须是 Qt 元对象系统已知类型,因为 Qt 需要拷贝自变量以将它们存储在幕后事件中。若试着使用排队连接且获得错误消息

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

确保声明自变量类型采用 Q_DECLARE_METATYPE

重载函数可以解析借助 qOverload .

注意: 此函数是 thread-safe .

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

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

此函数重载 connect ().

创建连接从 signal in sender 对象到 functor ,并返回要连接的句柄

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 表达式:

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

连接将自动断开,若发送者被销毁。不管怎样,应小心在函子中使用的任何对象仍存活,当发射信号时。

重载函数可以解析借助 qOverload .

注意: 此函数是 thread-safe .

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

此函数重载 connect ().

创建连接按给定 type from signal in sender 对象到 functor 以放置在特定事件循环 context ,并返回要连接的句柄。

注意: Qt::UniqueConnections 不工作于 Lambda、非成员函数及函子;它们仅适用于连接到成员函数。

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 表达式:

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

连接将自动断开,若发送者 (或上下文) 被销毁。不管怎样,应小心在函子中使用的任何对象仍存活,当发射信号时。

重载函数可以解析借助 qOverload .

注意: 此函数是 thread-safe .

该函数在 Qt 5.2 引入。

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

此虚函数被调用当某些东西已连接到 signal 在此对象。

若想要比较 signal 采用特定信号,可以使用 QMetaMethod::fromSignal () 如下:

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

警告: 此函数违反了面向对象的模块化原则。不管怎样,它可能很有用仅当某些东西连接到信号时,才需要履行昂贵的初始化。

警告: 此函数被履行连接的线程所调用,该线程可能不同于此对象存活的线程。

该函数在 Qt 5.0 引入。

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

[virtual protected] void QObject:: customEvent ( QEvent * event )

可以在子类中重实现此事件处理程序,以接收自定义事件。自定义事件是用户定义事件,具有类型值至少一样大如 QEvent::User 项的 QEvent::Type 枚举, 且通常是 QEvent 子类。事件被传入 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 被销毁,且不阻塞。

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

另请参阅 deleteLater () 和 QPointer .

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

断开连接 signal 在对象 sender from method 在对象 receiver 。返回 true 若连接被成功中断;否则返回 false .

信号/槽连接被移除,当涉及的任何对象被销毁时。

disconnect() 通常按以下范例演示的 3 种方式使用。

  1. 断开连接到对象信号的一切:
    disconnect(myObject, 0, 0, 0);
    							

    相当于非静态重载函数

    myObject->disconnect();
    							
  2. 断开连接到特定信号的一切:
    disconnect(myObject, SIGNAL(mySignal()), 0, 0);
    							

    相当于非静态重载函数

    myObject->disconnect(SIGNAL(mySignal()));
    							
  3. 断开特定接收者的连接:
    disconnect(myObject, 0, myReceiver, 0);
    							

    相当于非静态重载函数

    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 )

断开连接 signal 在对象 sender from method 在对象 receiver 。返回 true 若连接被成功中断;否则返回 false .

此函数提供相同可能性,像 disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) 但使用 QMetaMethod 来表示要断开的信号和方法。

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 实例表示不是信号。

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.

该函数在 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

此函数重载 disconnect ().

断开连接 signal from method of receiver .

信号/槽连接被移除,当涉及的任何对象被销毁时。

注意: 此函数是 thread-safe .

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

此函数重载 disconnect ().

断开连接此对象的所有信号从 receiver 's method .

信号/槽连接被移除,当涉及的任何对象被销毁时。

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

断开连接的连接。

connection 无效或已断开连接,什么都不做并返回 false。

另请参阅 connect ().

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

This function overloads diconnect().

断开连接 signal 在对象 sender from method 在对象 receiver 。返回 true 若连接被成功中断;否则返回 false .

信号/槽连接被移除,当涉及的任何对象被销毁时。

disconnect () is typically used in three ways, as the following examples demonstrate.

  1. 断开连接到对象信号的一切:
    disconnect(myObject, 0, 0, 0);
    							
  2. 断开连接到特定信号的一切:
    disconnect(myObject, &MyObject::mySignal(), 0, 0);
    							
  3. 断开特定接收者的连接:
    disconnect(myObject, 0, myReceiver, 0);
    							
  4. 断开从特定信号到特定槽的连接:
    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 )

此虚函数被调用当某些东西已断开连接从 signal 在此对象。

connectNotify () 例如如何比较 signal 采用特定信号。

若所有信号与此对象断开连接 (如,信号自变量在 disconnect () was 0), disconnectNotify() is only called once, and the signal 将是无效 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.

该函数在 Qt 5.0 引入。

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

void QObject:: dumpObjectInfo () const

将有关此对象的信号连接等信息转储到调试输出。

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

另请参阅 dumpObjectTree ().

void QObject:: dumpObjectTree () const

将子级树转储到调试输出。

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

另请参阅 dumpObjectInfo ().

QList < QByteArray > QObject:: dynamicPropertyNames () const

返回被动态添加到对象的所有特性的名称,使用 setProperty ().

该函数在 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

返回此对象的子级可以被铸造成 T 类型且称为 name , or 0 if there is no such object. Omitting the name 自变量导致匹配所有对象名称。搜索是递归履行的,除非 options 指定 FindDirectChildrenOnly 选项。

若有多个子级匹配搜索,返回最直接祖先。若有多个直接祖先,返回哪个未定义。在此情况下, findChildren () 应该被使用。

此范例返回子级 QPushButton of parentWidget 命名 "button1" ,即使按钮不是父级的直接子级:

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

此范例返回 QListWidget 子级对于 parentWidget :

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

此范例返回子级 QPushButton of parentWidget (其直接父级) 命名 "button1" :

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

此范例返回 QListWidget 子级对于 parentWidget ,其直接父级:

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

另请参阅 findChildren ().

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

返回此对象的所有子级具有给定 name that can be cast to type T, or an empty list if there are no such objects. Omitting the name 自变量导致匹配所有对象名称。搜索是递归履行的,除非 options 指定 FindDirectChildrenOnly 选项。

以下范例展示如何查找列表化的子级 QWidget 为指定 parentWidget 命名 widgetname :

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

此范例返回所有 QPushButton 其是子级对于 parentWidget :

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

此范例返回所有 QPushButton 其是直系子级对于 parentWidget :

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

另请参阅 findChild ().

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

此函数重载 findChildren ().

返回此对象的子级,可以被转换成 T 类型且拥有的名称匹配正则表达式 regExp ,或空列表若没有这样的对象。搜索是递归履行的,除非 options 指定 FindDirectChildrenOnly 选项。

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

此函数重载 findChildren ().

返回此对象的子级,可以被转换成 T 类型且拥有的名称匹配正则表达式 re ,或空列表若没有这样的对象。搜索是递归履行的,除非 options 指定 FindDirectChildrenOnly 选项。

该函数在 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) 代替。

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

void QObject:: installEventFilter ( QObject * filterObj )

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

monitoredObj->installEventFilter(filterObj);
					

事件过滤器是接收发送给此对象的所有事件的对象。过滤器可以停止事件 (或将其转发给此对象)。事件过滤器 filterObj 接收事件凭借其 eventFilter () 函数。 eventFilter () 函数必须返回 true,若事件应该被过滤 (即:停止);否则,它必须返回 false。

若在单个对象安装多个事件过滤器,将首先激活最后安装的过滤器。

这里是 KeyPressEater 类,会吃掉其监控对象的键按下:

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

和这里是如何将其安装在 2 小部件中:

KeyPressEater *keyPressEater = new KeyPressEater(this);
QPushButton *pushButton = new QPushButton(this);
QListView *listView = new QListView(this);
pushButton->installEventFilter(keyPressEater);
listView->installEventFilter(keyPressEater);
					

QShortcut 类,例如,使用此技术来拦截快捷键按下。

警告: 若删除接收者对象在 eventFilter () 函数,确保返回 true。若返回 false,Qt 把事件发送给已删除对象,且程序会崩溃。

注意,过滤对象必须与此对象在同一线程中。若 filterObj 在不同线程中, 此函数什么都不做。若 filterObj 或此对象被移入不同线程在调用此函数后,事件过滤器不会被调用直到 2 对象再次拥有相同线程倾向性 (它 not 被移除)。

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

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

返回 true signal 连接至少一接收者,否则返回 false .

signal 必须是此对象的信号成员,否则行为未定义。

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

如以上代码片段阐明,可以使用此函数以避免发射无人监听的信号。

警告: 此函数违反了面向对象的模块化原则。不管怎样,它可能很有用仅当某些东西连接到信号时,才需要履行昂贵的初始化。

该函数在 Qt 5.0 引入。

bool QObject:: isWidgetType () const

返回 true 若对象是 Widget;否则返回 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

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

元对象包含的信息有关类继承 QObject ,如类名、超类名称、特性、信号和槽。每个 QObject 子类包含 Q_OBJECT 宏将拥有元对象。

元对象信息是信号/槽连接机制和特性系统要求的。 inherits () 函数还利用了元对象。

若没有指向实际对象实例的指针但仍想访问类的元对象,可以使用 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.

注意,对象的所有活动计时器都将被重置。计时器先在当前线程中停止并重启 (采用相同间隔) 在 targetThread 。因此,在线程之间不断移动对象可以无限期推迟计时器事件。

QEvent::ThreadChange 事件被发送给此对象,恰好在线程亲和度改变之前。可以处理此事件以履行任何特殊处理。注意,张贴给此对象的任何新事件都将被处理在 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

返回接收者数为连接到 signal .

由于槽和信号两者可以用作信号的接收者,且可以多次建立相同连接,接收者数与从此信号建立的连接数相同。

当调用此函数时,可以使用 SIGNAL() 宏来传递特定信号:

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

警告: 此函数违反了面向对象的模块化原则。不管怎样,它可能很有用仅当某些东西连接到信号时,才需要履行昂贵的初始化。

另请参阅 isSignalConnected ().

void QObject:: removeEventFilter ( QObject * obj )

移除事件过滤器对象 obj 从此对象。忽略请求,若尚未安装这种事件过滤器。

将自动移除此对象的所有事件过滤器,当此对象被销毁时。

它始终安全地移除事件过滤器,即使在事件过滤器激活期间 (即:从 eventFilter () 函数)。

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

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

返回发送信号的对象指针,若在由信号激活的槽中调用;否则它返回 nullptr 。指针才有效,在从此对象线程上下文调用此函数的槽执行期间。

由此函数返回的指针变为无效若发送器被销毁,或者,若槽断开发送器信号连接。

警告: 此函数违反了面向对象的模块化原则。不管怎样,访问发送器可能很有用,当多个信号连接到单个槽时。

警告: 如上所述,此函数的返回值无效,当槽被调用凭借 Qt::DirectConnection 来自不同于此对象线程的线程。不要在这种情景类型下使用此函数。

另请参阅 senderSignalIndex ().

[protected] int QObject:: senderSignalIndex () const

返回目前调用执行槽的信号的元方法索引,它是类成员返回通过 sender ()。若在由信号激活的槽外调用,返回 -1。

对于具有默认参数的信号,此函数总是返回带有所有参数的索引,不管如何使用采用 connect ()。例如,信号 destroyed(QObject *obj = 0) 将有 2 个不同索引 (带和不带参数),但此函数总是返回带参数的索引。这不适用,当以不同参数重载信号时。

警告: 此函数违反了面向对象的模块化原则。不管怎样,访问信号索引可能很有用,当多个信号连接到单个槽时。

警告: 此函数的返回值无效,当槽被调用凭借 Qt::DirectConnection 来自不同于此对象线程的线程。不要在这种情景类型下使用此函数。

该函数在 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 )

设置值为对象的 name 特性到 value .

若有定义类特性使用 Q_PROPERTY 则成功返回 true,否则返回 false。若特性未定义使用 Q_PROPERTY ,因此未在元对象中列出,它被添加作为动态属性并返回 false。

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

动态特性可以被再次查询使用 property () 且可以被移除通过将特性值设为无效 QVariant 。更改动态特性值将导致 QDynamicPropertyChangeEvent 被发送给对象。

注意: 以 _q_ 开头的动态特性预留用于内部目的。

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

bool QObject:: signalsBlocked () const

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

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

另请参阅 blockSignals () 和 QSignalBlocker .

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

启动计时器并返回计时器标识符,或返回 0 若无法启动计时器。

计时器事件将出现每隔 interval 毫秒直到 killTimer () 被调用。若 interval 为 0,那么计时器事件出现一次,每次没有更多窗口系统事件要处理时。

虚拟 timerEvent () 函数被调用采用 QTimerEvent 事件参数类当计时器事件出现时。重实现此函数能获取计时器事件。

若有多个计时器在运行, QTimerEvent::timerId () 可以用于找出激活了哪个计时器。

范例:

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 的精度从属底层操作系统和硬件。 timerType 自变量允许定制计时器的精度。见 Qt::TimerType 了解不同计时器类型的有关信息。大多数平台支持 20 毫秒的精度;某些提供更多。若 Qt 无法交付请求的计时器事件数,会默默地丢弃一些。

QTimer 类提供高级编程接口,采用单发计时器和计时器信号而不是事件。还有 QBasicTimer 类更轻量相比 QTimer 且不像直接使用计时器 ID 那样笨重。

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

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

这是重载函数。

启动计时器并返回计时器标识符,或返回 0 若无法启动计时器。

计时器事件将出现每隔 time 间隔直到 killTimer () 被调用。若 time 等于 std::chrono::duration::zero() ,那么计时器事件就会出现,一旦每次没有更多窗口系统事件要处理。

虚拟 timerEvent () 函数被调用采用 QTimerEvent 事件参数类当计时器事件出现时。重实现此函数能获取计时器事件。

若有多个计时器在运行, QTimerEvent::timerId () 可以用于找出激活了哪个计时器。

范例:

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 的精度从属底层操作系统和硬件。 timerType 自变量允许定制计时器的精度。见 Qt::TimerType 了解不同计时器类型的有关信息。大多数平台支持 20 毫秒的精度;某些提供更多。若 Qt 无法交付请求的计时器事件数,会默默地丢弃一些。

QTimer 类提供高级编程接口,采用单发计时器和计时器信号而不是事件。还有 QBasicTimer 类更轻量相比 QTimer 且不像直接使用计时器 ID 那样笨重。

该函数在 Qt 5.9 引入。

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

QThread *QObject:: thread () const

返回对象所在的线程。

另请参阅 moveToThread ().

[virtual protected] void QObject:: timerEvent ( QTimerEvent * event )

此事件处理程序可以在子类中重实现,以接收对象的计时器事件。

QTimer 为计时器功能提供更高级接口,及有关定时器的更一般信息。计时器事件被传入 event 参数。

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

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

返回翻译版本的 sourceText ,可选基于 disambiguation 字符串和值 n 对于包含复数的字符串;否则返回 QString::fromUtf8 ( sourceText ) 若没有合适的翻译字符串可用。

范例:

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

若相同 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 消除歧义 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

此变量存储类的元对象。

元对象包含的信息有关类继承 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.

元对象信息是信号/槽连接机制和特性系统要求的。 inherits () 函数还利用了元对象。

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.

该函数在 Qt 5.8 引入。

另请参阅 QObject::connect .

Q_CLASSINFO ( Name , Value )

此宏将额外信息关联到类,是可用的使用 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 Value 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 适配器 ,和 扩展 QML .

Q_DISABLE_COPY ( Class )

禁用拷贝构造函数和赋值运算符的使用为给定 Class .

实例化的子类 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

使用此宏替换 emit 关键词对于发射信号,当想要使用 Qt 信号和槽采用 第 3 方信号/槽机制 .

通常使用宏当 no_keywords 的指定是采用 CONFIG 变量在 .pro 文件,但可以使用它即使当 no_keywords is not 指定。

Q_ENUM ( ... )

此宏采用元对象系统注册枚举类型。它必须放在类枚举声明之后,类有 Q_OBJECT Q_GADGET 宏。对于名称空间使用 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 。还可以使用 QMetaEnum::fromType () 以获取 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.

该函数在 Qt 5.5 引入。

另请参阅 Qt 的特性系统 .

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 但在名称空间中。

Enumerations that are declared with Q_ENUM_NS have their QMetaEnum registered in the enclosing QMetaObject 。还可以使用 QMetaEnum::fromType () 以获取 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.

该函数在 Qt 5.8 引入。

另请参阅 Qt 的特性系统 .

Q_FLAG ( ... )

此宏注册单 标志类型 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 () 代替。

宏必须放在枚举声明后。

例如,在 QLibrary LoadHints 标志的声明方式如下:

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

注意: The Q_FLAG macro takes care of registering individual flag values with the meta-object system, so it is unnecessary to use Q_ENUM () 除此宏外。

该函数在 Qt 5.5 引入。

另请参阅 Qt 的特性系统 .

Q_FLAG_NS ( ... )

此宏注册单 标志类型 采用元对象系统。它用于的名称空间拥有 Q_NAMESPACE 宏,以声明可以用作标志的给定枚举值,并组合使用按位 OR 运算符。它如同 Q_FLAG 但在名称空间中。

宏必须放在枚举声明后。

注意: Q_FLAG_NS 宏负责采用元对象系统注册单个标志值,因此不必使用 Q_ENUM_NS () 除此宏外。

该函数在 Qt 5.8 引入。

另请参阅 Qt 的特性系统 .

Q_GADGET

Q_GADGET 宏是更轻版本的 Q_OBJECT 宏,对于类不继承 QObject 但仍想使用某些反射能力提供通过 QMetaObject 。就像 Q_OBJECT 宏,它必须出现在类定义私有区间。

Q_GADGET 可以拥有 Q_ENUM , Q_PROPERTY and Q_INVOKABLE ,但它们不能拥有信号或槽。

Q_GADGET 使类成员, staticMetaObject ,可用。 staticMetaObject 是类型 QMetaObject 并提供对采用 Q_ENUMS 声明枚举的访问。

Q_INTERFACES ( ... )

此宏告诉 Qt 类实现哪些接口。使用这当实现插件时。

范例:

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

插件和描绘基本工具 范例了解细节。

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

Q_INVOKABLE

将此宏应用于成员函数声明,以允许凭借元对象系统援引它们。宏写在返回类型之前,如以下范例所示:

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

invokableMethod() 函数使用 Q_INVOKABLE 进行标记,导致它向元对象系统注册并使其能够被援引使用 QMetaObject::invokeMethod ()。由于 normalMethod() 函数未按此方式注册,不可以援引它使用 QMetaObject::invokeMethod ().

若可援引成员函数返回的指针指向 QObject 或子类化的 QObject 且是从 QML 援引它的,适用特殊的所有权规则。见 在 QML 和 C++ 之间的数据类型转换 了解更多信息。

Q_NAMESPACE

Q_NAMESPACE 宏可以用于添加 QMetaObject 能力到名称空间。

Q_NAMESPACE 可以拥有 Q_CLASSINFO , Q_ENUM_NS , Q_FLAG_NS ,但它们不可以拥有 Q_ENUM , Q_FLAG , Q_PROPERTY , Q_INVOKABLE , signals nor slots.

Q_NAMESPACE 制作外部变量, staticMetaObject ,可用。 staticMetaObject 是类型 QMetaObject and provides access to the enums declared with Q_ENUM_NS / Q_FLAG_NS .

该函数在 Qt 5.8 引入。

Q_OBJECT

Q_OBJECT 宏必须出现在类定义的私有区间,声明自身的信号和槽,或使用由 Qt 元对象系统提供的其它服务。

例如:

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

注意: 此宏要求类是子类化的 QObject 。使用 Q_GADGET 而不是 Q_OBJECT 来启用元对象系统类枚举支持,不要求是 QObject 子类。

另请参阅 元对象系统 , 信号和槽 ,和 Qt 的特性系统 .

Q_PROPERTY ( ... )

此宏用于声明类特性,当继承 QObject 。特性的行为像类数据成员,但它们拥有的额外特征可访问透过 元对象系统 .

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

特性名称和类型及 READ 函数是要求的。可以是任何类型的类型支持通过 QVariant ,或它可以是用户定义类型。其它项可选,但 WRITE 函数是公共的。属性默认为 true 除了 USER ,其默认为 false。

例如:

Q_PROPERTY(QString title READ title WRITE setTitle USER true)
					

有关如何使用此宏的更多细节,和其用法的更详细范例,见讨论在 Qt 的特性系统 .

另请参阅 Qt 的特性系统 .

Q_REVISION

将此宏应用到成员函数声明,以在元对象系统中采用修订号标记它们。宏写在返回类型之前,如以下范例所示:

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

这很有用当使用元对象系统将对象动态暴露给另一 API 时,因为可以匹配由其它 API 的多个版本所期望的版本。考虑以下简化范例:

    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.

元对象系统本身不使用此标记。目前这只用于 QtQml 模块。

对于更一般字符串标签,见 QMetaMethod::tag ()

另请参阅 QMetaMethod::revision ().

Q_SET_OBJECT_NAME ( Object )

此宏赋值 Object the objectName "Object".

它不管是否 Object 是指针或不是指针,宏自己会弄清楚。

该函数在 Qt 5.0 引入。

另请参阅 QObject::objectName ().

Q_SIGNAL

这是允许将单个函数,标记为信号的额外宏。它可能非常有用,尤其是当使用第 3 方源代码剖析器不理解 signals or Q_SIGNALS 组。

使用此宏替换 signals 关键词在类声明中,当想要使用 Qt 信号和槽采用 第 3 方信号/槽机制 .

通常使用宏当 no_keywords 的指定是采用 CONFIG 变量在 .pro 文件,但可以使用它即使当 no_keywords is not 指定。

Q_SIGNALS

使用此宏替换 signals 关键词在类声明中,当想要使用 Qt 信号和槽采用 第 3 方信号/槽机制 .

通常使用宏当 no_keywords 的指定是采用 CONFIG 变量在 .pro 文件,但可以使用它即使当 no_keywords is not 指定。

Q_SLOT

这是允许将单个函数,标记为槽的额外宏。它可能非常有用,尤其是当使用第 3 方源代码剖析器不理解 slots or Q_SLOTS 组。

使用此宏替换 slots 关键词在类声明中,当想要使用 Qt 信号和槽采用 第 3 方信号/槽机制 .

通常使用宏当 no_keywords 的指定是采用 CONFIG 变量在 .pro 文件,但可以使用它即使当 no_keywords is not 指定。

Q_SLOTS

使用此宏替换 slots 关键词在类声明中,当想要使用 Qt 信号和槽采用 第 3 方信号/槽机制 .

通常使用宏当 no_keywords 的指定是采用 CONFIG 变量在 .pro 文件,但可以使用它即使当 no_keywords is not 指定。