QObject Class

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

Note: All functions in this class are reentrant.

Note: These functions are also 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)
  • 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)
  • disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)

属性

公有函数

QObject(QObject *parent = Q_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 = Q_NULLPTR, const QObject *receiver = Q_NULLPTR, const char *method = Q_NULLPTR) const
bool disconnect(const QObject *receiver, const char *method = Q_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 = Q_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_NULLPTR, int n = -1)

受保护的函数

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)
typedef QObjectList
QList<T> qFindChildren(const QObject *obj, const QRegExp &regExp)
T qobject_cast(QObject *object)

Macros

详细描述

The QObject 是所有Qt对象类的基类.

QObject 是 Qt 对象模型的核心. Qt对象模型的核心特性是一个非常强大的对象间无缝通信机制-- 信号和槽. 你可以调用 connect() 函数将信号和槽函数连接, 并调用 disconnect()断开连接. 为了避免信号循环, 你可以调用 blockSignals()临时阻塞信号. 受保护的函数 connectNotify() 和 disconnectNotify() 可以追踪连接.

QObjects 使用 对象树管理所有子对象. 你创建一个具有父对象的 QObject 时, 这个对象自动加入父对象的 children() 链表中. 父对象拥有对象的所有权; 即., 父对象析构时, 自动删除子对象. 你可以调用 findChild() 或 findChildren(), 按照名称及可选类型查找子对象.

每个对象有一个 objectName() , 调用 metaObject()返回对应元对象, 并调用QMetaObject::className()查找类名. 你可以调用 inherits() 函数判断对象类是否继承某个类.

当一个对象被删除时, 它会发出destroyed()信号. 你可以捕捉这个信号, 避免QObject指针悬垂.

QObject::event() 接收对象的所有事件, QObject也支持过滤其他对象的事件. 详见 installEventFilter() 和 eventFilter(). childEvent()可以捕获所有的子对象事件.

QObject 提供基本的定时器; 更高级的定时器参见 QTimer.

注意: Q_OBJECT宏对于需要实现信号, 槽或属性的对象是必需的. 你还需要运行元对象编译器(Meta Object Compiler)编译源文件. 无论继承自QObject的对象是否使用信号、槽和属性, 我们强烈建议使用Q_OBJECT宏, 因为如果不这样做, 可能导致某些函数表现出奇怪的行为.

Qt的所有widget继承自QObject. isWidgetType()判断一个QObject对象是否是widget. 它比qobject_cast<QWidget *>(obj)或obj->inherits("QWidget")更高效.

QObject的一些函数, 如. children()返回QObjectList. QObjectListQList<QObject *>.

线程亲和性(thread affinity)

QObject实例被称为具有线程亲和性, 或者它位于某个线程中. 当QObject接收到排队的信号(queued signal)或发布的事件(posted event)时, 槽或事件处理程序将在对象所在的线程中运行.

注意: 如果一个 QObject没有线程相关性(也就是说, 如果thread() 返回零), 或者它所在的线程没有正在运行的事件循环, 那么它就无法接收排队的信号或发布的事件.

默认情况下, QObject位于创建它的线程中. 对象的线程相关性可以使用thread()查询, 也可以使用moveToThread()更改.

所有的QObject与父对象必须位于同一线程. 因此:

注意: QObject的成员变量不会自动成为它的子对象. 父子关系必须通过向子构造函数传递父对象的指针或调用setParent()设置. 如果没有此步骤, 当调用moveToThread()时,对象的成员变量将保留在旧线程中.

无复制构造函数和赋值运算符

QObject既没有复制构造函数, 也没有赋值运算符. 这是经过设计的. 实际上, 它们是声明的, 但在一个带有宏Q_DISABLE_COPY()的私有部分. 事实上, 所有从QObject派生的Qt类(直接或间接)都使用这个宏来声明它们的复制构造函数和赋值运算符是私有的. 相关讨论参见Identity vs Value.

主要的结果是,您应该使用指向QObject(或指向你的QObject子类)的指针,否则你可能会将你的QObject子类用作值. 例如, 如果没有复制构造函数, 就不能使用QObject的子类作为一个容器类中的值, 必须存储指针.

自动连接

Qt的元对象系统提供一种机制, 自动连接QObject子类及子类之间的信号和槽函数. 只要用合适的对象名称定义对象, 并且槽函数遵循简单的命名约定, 就可以在运行时通过QMetaObject::connectSlotsByName()函数执行此连接.

uic生成调用此函数的代码, 以便在使用Qt Designer创建的表单上的widget之间执行自动连接. 有关使用Qt Designer自动连接的更多信息, 参见Qt Designer手册的Using a Designer UI File in Your Application章节.

动态属性

从Qt4.2开始, 动态属性可以在运行时添加到QObject实例, 也可以从中删除. 动态属性不需要在编译时声明, 但它们提供与静态属性相同的优势, 并且使用相同的API操作-调用property()读取, 调用setProperty()设置.

从Qt 4.3开始, Qt Designer支持动态属性, 并且标准Qt widget和用户创建的表单都可以被赋予动态属性.

国际化 (I18n)

所有QObject子类都支持Qt的翻译功能, 可以将应用程序的用户界面翻译成不同的语言.

为了使用户可见的文本可翻译, 必须将其封装在对tr()函数的调用中. 详见Writing Source Code for Translation.

参见 QMetaObject, QPointer, QObjectCleanupHandler, Q_DISABLE_COPY(), Object Trees & Ownership.

属性

objectName : QString

对象名称

调用findChild(), 根据objectName查找对象. 调用findChildren(), 查找对象集合.


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

默认情况下, objectName是空字符串.

访问函数:

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

Notifier signal:

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

注意: 私有信号. 用于信号连接, 但是不能被用户调用.

参见 metaObject(), QMetaObject::className().

成员函数

QObject::QObject(QObject *parent = Q_NULLPTR)

构造函数, parent 是父对象.

父对象是子对象的所有者. 例如, QDialog作为父对象, 包含OKCancel按钮.

父对象析构时, 会销毁所有子对象.

如果parent设置为nullptr, 则对象无父对象. 如果对象是widget, 它会变成顶级窗口.

注意: 这个函数可以通过元对象系统和QML调用. 参见Q_INVOKABLE.

参见 parent(), findChild(), findChildren().

[virtual] QObject::~QObject()

析构函数, 同时删除所有子对象.

这个对象关联的信号自动断开, 事件队列中的所有挂起事件被移除. 但是, 调用deleteLater()比直接删除QObject子类对象更安全.

警告: 所有子对象会被删除. 如果这些对象中有在堆栈或全局中, 程序可能崩溃. 我们不建议在父对象外部保留子对象的指针. 如果你仍然这么做, destroyed()信号让你有机会检测对象何时被破坏.

警告: 在等待传递挂起事件时, 删除QObject可能会导致崩溃. 如果QObject存在于与当前执行的线程不同的线程中, 则不能直接删除它. 改用deleteLater(), 这将导致事件循环在所有挂起的事件都传递到对象之后删除该对象.

参见 deleteLater().

bool QObject::blockSignals(bool block)

blocktrue, 对象阻塞所有信号(即., 发出的信号不会调用关联的信号或槽函数). blockfalse, 不会阻塞信号.

signalsBlocked()返回前面设置的值.

注意: 即便对象的信号被阻塞, destroyed()信号也会发出.

阻塞时, 发出的信号不会被缓存.

参见 signalsBlocked(), QSignalBlocker.

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

在派生类重载此函数, 处理子对象事件. 事件是在event参数传递.

添加或删除事件时, 对象会接收到QEvent::ChildAddedQEvent::ChildRemoved事件. 这两种情况下, 你可以调用isWidgetType()判断对象是不是QWidget(因为, ChildAdded时, 子对象并未完全构造; ChildRemoved时, 子对象可能已经销毁).

子对象polished时, widget会接收到QEvent::ChildPolished事件. 如果你收到QEvent::ChildPolished事件, 子对象已经构建完成. 然而, 这并不保证, 子对象构造函数期间可能发送多个QEvent::ChildPolished事件.

对于每个子widget, 你会接收到一个ChildAdded事件, 0个或多个ChildPolished事件, 一个ChildRemoved事件.

如果子对象添加后, 立即删除, 则会忽略ChildPolished事件. 如果构建和销毁过程中, 对一个子对象多次polished, 则你会收到这个子对象的多个ChildPolished事件, 每次使用不同的虚拟表.

参见 event().

const QObjectList &QObject::children() const

返回子对象链表, QObjectList采用如下方式定义在头文件<QObject>:


  typedef QList<QObject*> QObjectList;

链表中的子对象顺序是添加顺序, 新加的子对象被追加在链表末尾.

注意: QWidget子对象调用raised()或lowered()后, 链表顺序发生变化.widget调用raised()后, 变成链表中的最后一个对象. widget调用lowered()后, 变成链表中的第一个对象.

参见 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)

创建连接, 参数sender是发送对象, signal是信号, receiver是接收对象, method是槽函数, type是连接类型.

传递signalmethod方法时, 你必须使用SIGNAL()SLOT(), 如下所示:


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

上述示例目的是label始终显示滚动条的值. 如下所示是错误的: signal和slot不能包含变量名, 只能包含类型:


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

上述示例中, 在构造函数中, code>MyWidget把QPushButton的信号连接到自定义信号.

一个信号可以连接多个信号和槽函数. 多个信号可以连接到一个槽函数.

如果一个信号连接多个槽函数, 则信号发出时, 这些槽函数按照连接顺序执行.

函数将信号和槽函数连接成功时, 返回QMetaObject::Connection, 表示连接句柄. 如果无法创建连接, 连接句柄无效. 如, QObject无法验证信号或槽函数是否存在, 或参数不兼容. 你可以将连接句柄强转为bool, 检测连接是否有效.

默认情况下, 每次连接都会发出一个信号; 若两个连接重复, 你可以调用disconnect()断开连接. 若typeQt::UniqueConnection, 则仅会创建不重复连接. 如果已经有重复连接, 则连接失败, 并返回无效的QMetaObject::Connection.

注意: Qt::UniqueConnection不适用于lambda表达式, 非成员函数和函数对象; 仅适用于成员函数.

type描述连接类型. 尤其是, 它可以指定信号是立即响应, 还是队列方式. 如果信号是队列方式, 参数必须是Qt元对象系统已知类型, 因为Qt需要复制参数, 并存储. 若type是Qt::QueuedConnection, 且Qt元对象系统不知道参数类型, 你可以得到如下错误信息:


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

你可以在连接之前, 调用qRegisterMetaType()注册类型.

注意: 这个函数是 线程安全的

参见 disconnect(), sender(), qRegisterMetaType(), Q_DECLARE_METATYPE(), Differences between String-Based and Functor-Based Connections.

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

创建连接. 参数sender是发送对象, signal是信号, receiver是接收对象, method是槽函数, type是类型.

返回连接的句柄, 句柄用于以后断开连接. 如果无法创建连接, 则连接句柄将无效. 例如, 参数无效. 你可以将连接句柄强转为bool, 检测连接是否有效.

这个函数的工作方式与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() 重载函数.

参数sender是发送对象, signal是信号, method是槽函数, type是类型.

等价于(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().

Note: This function is thread-safe

参见 disconnect().

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

connect()重载函数.

参数sender是发送对象, signal是信号, receiver是接收对象, method是槽函数, type是类型. 返回连接的句柄, 句柄用于以后断开连接.

信号必须在头文件中声明为信号函数. 槽函数可以是连接信号的任意成员函数. 信号的参数数量不少于槽函数的参数数量, 并且信号与槽函数的参数类型存在隐式转换, 则可以连接.

Example:


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

上述示例是label始终显示单行编辑器的文本.

一个信号可以连接多个信号和槽函数. 多个信号可以连接到一个槽函数.

如果一个信号连接多个槽函数, 则信号发出时, 这些槽函数按照连接顺序执行

函数将信号和槽函数连接成功时, 返回QMetaObject::Connection, 表示连接句柄. 如果无法创建连接, 连接句柄无效. 如, QObject无法验证信号或槽函数是否存在, 或参数不兼容. 你可以将连接句柄强转为bool, 检测连接是否有效.

默认情况下, 每次连接都会发出一个信号; 若两个连接重复, 你可以调用disconnect()断开连接. 若typeQt::UniqueConnection, 则仅会创建不重复连接. 如果已经有重复连接, 则连接失败, 并返回无效的QMetaObject::Connection.

type描述连接类型. 尤其是, 它可以指定信号是立即响应, 还是队列方式. 如果信号是队列方式, 参数必须是Qt元对象系统已知类型, 因为Qt需要复制参数, 并存储. 若type是Qt::QueuedConnection, 且Qt元对象系统不知道参数类型, 你可以得到如下错误信息:


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

使用Q_DECLARE_METATYPE声明参数类型

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe

参见 Differences between String-Based and Functor-Based Connections.

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

connect() 重载函数.

创建连接. 参数sender是发送对象, signal是信号, functor是函数对象, 返回连接句柄.

信号必须在头文件中声明为信号函数. 槽函数可以是任何可以连接到信号的函数或函数对象. 如果给定信号的自变量至少与槽的自变量一样多, 则函数可以连接到该信号. 信号的参数数量不少于槽函数的参数数量, 并且信号与槽函数的参数类型存在隐式转换.

例如:


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

sender销毁时, 连接自动断开. 但是, 你必须小心, 信号发出时, 函数对象中的任何对象未被销毁.

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe

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

connect()重载函数.

创建连接. 参数sender是发送对象, signal是信号, context是事件循环对象, functor是函数对象, type是连接类型, 返回连接句柄.

注意: Qt::UniqueConnection不能用于lambda表达式, 非成员函数和函数对象; 这个类型仅可以用于成员函数. 信号必须在头文件中声明为信号函数. 槽函数可以是任何可以连接到信号的函数或函数对象. 如果给定信号的自变量至少与槽的自变量一样多, 则函数可以连接到该信号. 信号的参数数量不少于槽函数的参数数量, 并且信号与槽函数的参数类型存在隐式转换.

例如:


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

sender销毁时, 连接自动断开. 但是, 你必须小心, 信号发出时, 函数对象中的任何对象未被销毁.

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe

This function was introduced in Qt 5.2.

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

连接到对象中的信号时, 调用这个函数.

如下所示, 如果你想过滤某个特定信号, 你可以使用QMetaMethod::fromSignal():


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

警告: 这个函数违反了模块化的面向对象原则. 然而, 你需要发送的某个信号, 可能执行昂贵的初始化时, 这个函数很有用.

警告: 这个函数从执行连接的线程调用, 可能和这个对象所在的线程不同.

This function was introduced in Qt 5.0.

参见 connect() and disconnectNotify().

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

重载这个函数可以接收自定义事件. 自定义事件是用户定义的事件, 这个类型值至少与QEvent::User项一样大, 通常是一个QEvent子类. 事件在参数event中传递.

参见 event(), QEvent.

[slot] void QObject::deleteLater()

延迟删除对象.

控件返回事件循环时, 对象将被删除. 如果在事件循环开始前调用这个函数(如. 在QCoreApplication::exec()之前调用deleteLater()), 事件循环启动时删除删除对象. 如果在主事件循环停止后调用deleteLater(), 则不会删除对象. 从Qt4.8开始, 如果deleteLater()在没有事件循环的线程中调用, 那么线程结束时, 这个对象才会销毁.

注意: 进入和离开一个新的事件循环(如. 打开模态对话框)不会延迟删除; 对于删除的对象, 控件必须在返回事件循环前调用deleteLater(). 这不适用在上一个事件循环仍在运行的对象删除: 新的事件循环一开始, Qt就会删除这个对象.

注意: 多次调用这个函数是安全的; 新的延迟删除事件, 会从事件队列中删除对象的任何挂起事件.

注意: 这个函数是线程安全的.

参见 destroyed(), QPointer.

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

这个信号在obj销毁前, QPointer实例被通知后, 并且不能阻塞.

这个信号发出后, 所有对象的子对象立即销毁.

参见 deleteLater(), QPointer.

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

断开连接. 参数sender是发送对象, signal是信号, receiver是接收对象, method是槽函数. 返回true表示断开连接成功, false表示断开连接失败.

发送对象或接收对象销毁时, 信号和槽函数会被移除.

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

  1. 如下所示, disconnect()有三种调用方式:
    
      disconnect(myObject, 0, 0, 0);
    
    

    equivalent to the non-static overloaded function

    
      myObject->disconnect();
    
    
  2. 1. 断开对象的所有信号连接:
    
      disconnect(myObject, SIGNAL(mySignal()), 0, 0);
    
    

    equivalent to the non-static overloaded function

    
      myObject->disconnect(SIGNAL(mySignal()));
    
    
  3. 2. 断开对象的特定信号:
    
      disconnect(myObject, 0, myReceiver, 0);
    
    

    equivalent to the non-static overloaded function

    
      myObject->disconnect(myReceiver);
    
    
  4. 3. 断开特定的接收者

nullptr作为一个通配符, 表示"任何信号", "任何接收对象", 或"接收对象的任何槽函数".

sender不能是nullptr.(不能在一次调用中断开多个对象的信号)

signal是nullptr, 则断开所有信号的receivermethod连接. 否则, 仅断开特定信号.

receiver是nullptr, 则断开signal的所有连接. 否则, 除receiver的其他对象的槽函数不会断开连接.

method是nullptr, 则断开receiver的所有连接. 否则, 仅断开method的槽函数连接. 如果省略receiver, 则method必须为nullptr, 因为无法断开所有对象上特定命名的slot连接.

Note: This function is thread-safe

参见 connect().

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

断开连接. 参数sender是发送对象, signal是信号, receiver是接收对象, method是方法. 返回true表示断开成功, false表示断开失败.

这个函数与disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)类似, 使用QMetaMethod表示信号和槽函数.

此外, 若出现下列情况, 函数不会断开信号和槽函数, 返回false:

  1. signal不是sender或父类的成员.
  2. method不是receiver或父类的成员.
  3. signal不是信号.

QMetaMethod()可以作为通配符, 表示"任何信号"或"接收对象中的任何槽函数". 同样, receiver也可是nullptr, 表示"任何接收对象". 这种情况下, 方法也应该是QMetaMethod(). sender不能是nullptr.

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 = Q_NULLPTR, const QObject *receiver = Q_NULLPTR, const char *method = Q_NULLPTR) const

disconnect()重载函数.

Disconnects signal from method of receiver.

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

Note: This function is thread-safe

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

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.

If the 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. Returns true if the connection is successfully broken; otherwise returns false.

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

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

  1. 如下所示, disconnect()通常有4种方式:
    
      disconnect(myObject, 0, 0, 0);
    
    
  2. 断开sender对象的任意连接:
    
      disconnect(myObject, &MyObject::mySignal(), 0, 0);
    
    
  3. 断开sender对象的特定信号连接:
    
      disconnect(myObject, 0, myReceiver, 0);
    
    
  4. 断开sender对象与receiver对象的连接:
    
      QObject::disconnect(lineEdit, &QLineEdit::textChanged,
                       label,  &QLabel::setText);
    
    
  5. 断开sender对象的特定信号与receiver对象的特定槽函数连接

nullptr作为一个通配符, 表示"任何信号", "任何接收对象", 或"接收对象的任何槽函数".

sender不能是nullptr.(不能在一次调用中断开多个对象的信号)

signal是nullptr, 则断开所有信号的receivermethod连接. 否则, 仅断开特定信号.

receiver是nullptr, 则断开signal的所有连接. 否则, 除receiver的其他对象的槽函数不会断开连接.

method是nullptr, 则断开receiver的所有连接. 否则, 仅断开method的槽函数连接. 如果省略receiver, 则method必须为nullptr, 因为无法断开所有对象上特定命名的slot连接.

注意: 不能使用这个函数断开信号和函数对象或lambda表达式的连接. 这是因为无法对它们进行比较. 相反, 请使用接受QMetaObject::Connection的重载

Note: This function is thread-safe

参见 connect().

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

断开与signal信号的连接时, 调用这个函数.

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

如果断开对象的所有信号(如, disconnect()的参数signal是nullptr), 则disconnectNotify()仅调用一次, 并且参数signal是无效的(QMetaMethod::isValid()返回false).

警告: 这个函数违反了模块化的面向对象原则. 然而, 它有助于优化昂贵的资源访问.

警告: 这个函数是从执行断开连接的线程调用的, 该线程可能与此对象所在的线程不同. 也可以在锁定QObject内部互斥的情况下调用此函数. 因此, 不允许你的重载实现中重新输入任何QObject函数, 如果你在重载实现中锁定了一个互斥体, 请确保你不会用其他地方持有的互斥体调用QObject功能, 否则将导致死锁.

This function was introduced in Qt 5.0.

参见 disconnect(), connectNotify().

void QObject::dumpObjectInfo() const

输出对象的连接信息(信号, 槽函数等).

Note: before Qt 5.9, this function was not const.

参见 dumpObjectTree().

void QObject::dumpObjectTree() const

输出对象树.

Note: before Qt 5.9, this function was not const.

参见 dumpObjectInfo().

QList<QByteArray> QObject::dynamicPropertyNames() const

调用setProperty()添加的动态属性名称列表.

This function was introduced in Qt 4.2.

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

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

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

Make sure you call the parent event class implementation for all the events you did not handle.

Example:


  class MyClass : public QWidget
  {
      Q_OBJECT

  public:
      MyClass(QWidget *parent = 0);
      ~MyClass();

      bool event(QEvent* ev)
      {
          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(), and QCoreApplication::postEvent().

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

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

In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.

Example:


  class MainWindow : public QMainWindow
  {
  public:
      MainWindow();

  protected:
      bool eventFilter(QObject *obj, QEvent *ev);

  private:
      QTextEdit *textEdit;
  };

  MainWindow::MainWindow()
  {
      textEdit = new QTextEdit;
      setCentralWidget(textEdit);

      textEdit->installEventFilter(this);
  }

  bool MainWindow::eventFilter(QObject *obj, QEvent *event)
  {
      if (obj == textEdit) {
          if (event->type() == QEvent::KeyPress) {
              QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
              qDebug() << "Ate key press" << keyEvent->key();
              return true;
          } else {
              return false;
          }
      } else {
          // pass the event on to the parent class
          return QMainWindow::eventFilter(obj, event);
      }
  }

Notice in the example above that unhandled events are passed to the base class's eventFilter() function, since the base class might have reimplemented eventFilter() for its own internal purposes.

Warning: If you delete the receiver object in this function, be sure to return true. Otherwise, Qt will forward the event to the deleted object and the program might crash.

参见 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", even if the button isn't a direct child of the parent:


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

This example returns a 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);

This example returns a 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 QWidgets of the specified parentWidget named widgetname:


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

This example returns all QPushButtons that are children of parentWidget:


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

This example returns all QPushButtons 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

Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.

A class is considered to inherit itself.

Example:


  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)

If you need to determine whether an object is an instance of a particular class for the purpose of casting it, consider using qobject_cast<Type *>(object) instead.

参见 metaObject() and qobject_cast().

void QObject::installEventFilter(QObject *filterObj)

Installs an event filter filterObj on this object. For example:


  monitoredObj->installEventFilter(filterObj);

An event filter is an object that receives all events that are sent to this object. The filter can either stop the event or forward it to this object. The event filter filterObj receives events via its eventFilter() function. The eventFilter() function must return true if the event should be filtered, (i.e. stopped); otherwise it must return false.

If multiple event filters are installed on a single object, the filter that was installed last is activated first.

Here's a KeyPressEater class that eats the key presses of its monitored objects:


  class KeyPressEater : public QObject
  {
      Q_OBJECT
      ...

  protected:
      bool eventFilter(QObject *obj, QEvent *event);
  };

  bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
  {
      if (event->type() == QEvent::KeyPress) {
          QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
          qDebug("Ate key press %d", keyEvent->key());
          return true;
      } else {
          // standard event processing
          return QObject::eventFilter(obj, event);
      }
  }

And here's how to install it on two widgets:


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

  pushButton->installEventFilter(keyPressEater);
  listView->installEventFilter(keyPressEater);

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

Warning: If you delete the receiver object in your eventFilter() function, be sure to return true. If you return false, Qt sends the event to the deleted object and the program will crash.

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(), and event().

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

如果信号被连接, 返回true. 否则, 返回false.

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


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

如上所示, 你可以使用这个函数避免发出无人监听的信号.

警告: 这个函数违反了模块化的面向对象原则. 然而, 你需要发送的某个信号, 可能执行昂贵的初始化时, 这个函数很有用.

This function was introduced in Qt 5.0.

bool QObject::isWidgetType() const

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

Calling this function is equivalent to calling inherits("QWidget"), except that it is much faster.

bool QObject::isWindowType() const

Returns true if the object is a window; otherwise returns false.

Calling this function is equivalent to calling inherits("QWindow"), except that it is much faster.

void QObject::killTimer(int id)

Kills the timer with timer identifier, id.

The timer identifier is returned by startTimer() when a timer event is started.

参见 timerEvent() and startTimer().

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

Returns a pointer to the meta-object of this object.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have no pointer to an actual object instance but still want to access the meta-object of a class, you can use staticMetaObject.

Example:


  QObject *obj = new QPushButton;
  obj->metaObject()->className();             // returns "QPushButton"

  QPushButton::staticMetaObject.className();  // returns "QPushButton"

参见 staticMetaObject.

void QObject::moveToThread(QThread *targetThread)

Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

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


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

If targetThread is zero, all event processing for this object and its children stops.

Note that all active timers for the object will be reset. The timers are first stopped in the current thread and restarted (with the same interval) in the targetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in the targetThread.

Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.

参见 thread().

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

对象的名称被修改时, 发出这个信号. objectName是新的对象名.

注意: 这是私有信号. 信号连接使用, 不能被用户调用.

注意: 这个函数是属性 objectName的信号.

参见 QObject::objectName.

QObject *QObject::parent() const

Returns a pointer to the parent object.

参见 setParent() and children().

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

Returns the value of the object's name property.

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

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

参见 setProperty(), QVariant::isValid(), metaObject(), and 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);
  }

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

参见 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(), and 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 0. The pointer is valid only during the execution of the slot that calls this function from this object's thread context.

The pointer returned by this function becomes invalid if the sender is destroyed, or if the slot is disconnected from the sender's signal.

Warning: This function violates the object-oriented principle of modularity. However, getting access to the sender might be useful when many signals are connected to a single slot.

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

参见 senderSignalIndex() and QSignalMapper.

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

Warning: This function violates the object-oriented principle of modularity. However, getting access to the signal index might be useful when many signals are connected to a single slot.

Warning: The return value of this function is not valid when the slot is called via 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(), and QMetaObject::method().

void QObject::setParent(QObject *parent)

Makes the object a child of parent.

参见 parent() and 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.

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

Dynamic properties can be queried again using property() and can be removed by setting the property value to an invalid QVariant. Changing the value of a dynamic property causes a QDynamicPropertyChangeEvent to be sent to the object.

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

参见 property(), metaObject(), dynamicPropertyNames(), and QMetaProperty::write().

bool QObject::signalsBlocked() const

Returns true if signals are blocked; otherwise returns false.

Signals are not blocked by default.

参见 blockSignals() and 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.

Example:


  class MyObject : public QObject
  {
      Q_OBJECT

  public:
      MyObject(QObject *parent = 0);

  protected:
      void timerEvent(QTimerEvent *event);
  };

  MyObject::MyObject(QObject *parent)
      : QObject(parent)
  {
      startTimer(50);     // 50-millisecond timer
      startTimer(1000);   // 1-second timer
      startTimer(60000);  // 1-minute timer

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

Note that 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.

The QTimer class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also a QBasicTimer class that is more lightweight than QTimer and less clumsy than using timer IDs directly.

参见 timerEvent(), killTimer(), and QTimer::singleShot().

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

This is an overloaded function.

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.

Example:


  class MyObject : public QObject
  {
      Q_OBJECT

  public:
      MyObject(QObject *parent = 0);

  protected:
      void timerEvent(QTimerEvent *event);
  };

  MyObject::MyObject(QObject *parent)
      : QObject(parent)
  {
      startTimer(50);     // 50-millisecond timer
      startTimer(1000);   // 1-second timer
      startTimer(60000);  // 1-minute timer

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

Note that 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.

The QTimer class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also a QBasicTimer class that is more lightweight than QTimer and less clumsy than using timer IDs directly.

This function was introduced in Qt 5.9.

参见 timerEvent(), killTimer(), and QTimer::singleShot().

QThread *QObject::thread() const

Returns the thread in which the object lives.

参见 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 parameter.

参见 startTimer(), killTimer(), and event().

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

Returns a translated version of 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.

Example:


  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.

Example:


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

See Writing Source Code for Translation for a detailed description of Qt's translation mechanisms in general, and the Disambiguation section for information on disambiguation.

Warning: This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.

参见 QCoreApplication::translate() and Internationalization with Qt.

成员变量

const QMetaObject QObject::staticMetaObject

This variable stores the meta-object for the class.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every class that contains the Q_OBJECT macro will also have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have a pointer to an object, you can use metaObject() to retrieve the meta-object associated with that object.

Example:


  QPushButton::staticMetaObject.className();  // returns "QPushButton"

  QObject *obj = new QPushButton;
  obj->metaObject()->className();             // returns "QPushButton"

参见 metaObject().

相关非成员

typedef QObjectList

Synonym for QList<QObject *>.

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

This function overloads qFindChildren().

This function is equivalent to obj->findChildren<T>(regExp).

Note: This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.

参见 QObject::findChildren().

T qobject_cast(QObject *object)

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

The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.

A class is considered to inherit itself.

Example:


  QObject *obj = new QTimer;          // QTimer inherits QObject

  QTimer *timer = qobject_cast<QTimer *>(obj);
  // timer == (QObject *)obj

  QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
  // button == 0

The qobject_cast() function behaves similarly to the standard C++ dynamic_cast(), with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.

qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details.

Warning: If T isn't declared with the Q_OBJECT macro, this function's return value is undefined.

参见 QObject::inherits().

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, Value)

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 Value literal string.

Example:


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

  public:
      ...
  };

参见 QMetaObject::classInfo(), QAxFactory, Using Qt D-Bus Adaptors, and 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 &);
       MyClass &operator=(const MyClass &);
  };

But even this might not catch absolutely every case. You might be tempted to do something like this:


    QWidget w = QWidget();

First of all, don't do that. Most compilers will generate code that uses the copy constructor, so the privacy violation error will be reported, but your C++ compiler is not required to generate code for this statement in a specific way. It could generate code using neither the copy constructor nor the assignment operator we made private. In that case, no error would be reported, but your application would probably crash when you called a member function of w.

Q_EMIT

Use this macro to replace the emit keyword for emitting signals, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.

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

Q_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 or the Q_GADGET macro. For namespaces use Q_ENUM_NS() instead.

For example:


  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.

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.

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

The macro must be placed after the enum declaration.

For example, in QLibrary, the 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.

Note: 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.

Note: 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 is of type 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.

Example:


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

See the Plug & Paint Basic Tools example for details.

参见 Q_DECLARE_INTERFACE(), Q_PLUGIN_METADATA(), and How to Create Qt Plugins.

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

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

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.

For example:


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

Note: This macro requires the class to be a subclass of QObject. Use 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.

参见 Meta-Object System, Signals and Slots, and 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 Meta-Object System.


  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.

For example:


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

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

参见 QMetaMethod::revision().

Q_SET_OBJECT_NAME(Object)

This macro assigns Object the objectName "Object".

It doesn't matter whether Object 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.