對象模型

標準 C++ 對象模型為對象範式,提供瞭非常有效的運行時支持。但其靜態性質在某些問題領域是不靈活的。GUI (圖形用戶界麵) 編程要求運行時高效,且高級靈活性的兩者領域。Qt 通過組閤 C++ 的速度與 Qt 對象模型的靈活性,提供這。

Qt 把這些特徵添加到 C++:

  • 用於無縫對象通信,非常強大的機製稱為 信號/槽
  • 可查詢且可設計的 對象特性
  • 強大的 事件和事件過濾
  • 上下文 字符串翻譯為國際化
  • sophisticated interval driven timers that make it possible to elegantly integrate many tasks in an event-driven GUI
  • hierarchical and queryable 對象樹 that organize object ownership in a natural way
  • 守衛指針 ( QPointer ) that are automatically set to 0 when the referenced object is destroyed, unlike normal C++ pointers which become dangling pointers when their objects are destroyed
  • a 動態鑄造 that works across library boundaries.

Many of these Qt features are implemented with standard C++ techniques, based on inheritance from QObject . Others, like the object communication mechanism and the dynamic property system, require the 元對象係統 provided by Qt's own MOC (元對象編譯器) .

The meta-object system is a C++ extension that makes the language better suited to true component GUI programming. Although templates can be used to extend C++, the meta-object system provides benefits using standard C++ that cannot be achieved with templates; see Why Doesn't Qt Use Templates for Signals and Slots?

重要類

這些類形成 Qt 對象模型的基礎。

QMetaClassInfo 有關類的額外信息
QMetaEnum 有關枚舉器的元數據
QMetaMethod 關於成員函數的元數據
QMetaObject 包含有關 Qt 對象的元信息
QMetaProperty 關於特性的元數據
QMetaType 在元對象係統中管理命名類型
QObject 所有 Qt 對象的基類
QObjectCleanupHandler 看守多個 QObject 的壽命
QPointer 提供指嚮 QObject 守衛指針的模闆類
QSignalMapper 捆綁來自可識彆發送器的信號
QVariant 舉動像最常見 Qt 數據類型的並集

Qt 對象:標識 vs 值

Some of the added features listed above for the Qt Object Model, require that we think of Qt Objects as identities, not values. Values are copied or assigned; identities are cloned. Cloning means to create a new identity, not an exact copy of the old one. For example, twins have different identities. They may look identical, but they have different names, different locations, and may have completely different social networks.

Then cloning an identity is a more complex operation than copying or assigning a value. We can see what this means in the Qt Object Model.

Qt 對象 ...

  • 可以擁有唯一 QObject::objectName ()。若拷貝 Qt Object,應該給副本什麼名稱?
  • has a location in an object hierarchy . If we copy a Qt Object, where should the copy be located?
  • can be connected to other Qt Objects to emit signals to them or to receive signals emitted by them. If we copy a Qt Object, how should we transfer these connections to the copy?
  • 可以擁有 新特性 added to it at runtime that are not declared in the C++ class. If we copy a Qt Object, should the copy include the properties that were added to the original?

For these reasons, Qt Objects should be treated as identities, not as values. Identities are cloned, not copied or assigned, and cloning an identity is a more complex operation than copying or assigning a value. Therefore, QObject and all subclasses of QObject (direct or indirect) have their 拷貝構造函數和賦值運算符 disabled.