QObject 類

The QObject 類是所有 Qt 對象的基類。 更多...

頭: #include <QObject>
實例化: QtObject
繼承者: Maemo::DBusDispatcher , Phonon::AudioDataOutput , Phonon::AudioOutput , Phonon::BackendCapabilities::Notifier , Phonon::Effect , Phonon::MediaController , Phonon::MediaObject , Q3Accel , Q3Action , Q3Canvas , Q3Dns , Q3DragObject , Q3EditorFactory , Q3FileIconProvider , Q3NetworkOperation , Q3NetworkProtocol , Q3Process , Q3ServerSocket , Q3Signal , Q3SqlForm , Q3StyleSheet , Q3WhatsThis , QAbstractAnimation , QAbstractEventDispatcher , QAbstractFontEngine , QAbstractItemDelegate , QAbstractItemModel , QAbstractMessageHandler , QAbstractNetworkCache , QAbstractState , QAbstractTextDocumentLayout , QAbstractTransition , QAbstractUriResolver , QAbstractVideoSurface , QAccessibleBridgePlugin , QAccessiblePlugin , QAction , QActionGroup , QAudioInput , QAudioOutput , QAxFactory , QAxObject , QAxScript , QAxScriptManager , QButtonGroup , QClipboard , QCompleter , QCopChannel , QCoreApplication , QDataWidgetMapper , QDBusAbstractAdaptor , QDBusAbstractInterface , QDBusPendingCallWatcher , QDBusServiceWatcher , QDeclarativeComponent , QDeclarativeContext , QDeclarativeEngine , QDeclarativeExpression , QDeclarativeExtensionPlugin , QDeclarativePropertyMap , QDecorationPlugin , QDesignerFormEditorInterface , QDesignerFormWindowManagerInterface , QDirectPainter , QDrag , QEventLoop , QExtensionFactory , QExtensionManager , QFileSystemWatcher , QFontEnginePlugin , QFtp , QFutureWatcher , QGenericPlugin , QGesture , QGLShader , QGLShaderProgram , QGraphicsAnchor , QGraphicsEffect , QGraphicsItemAnimation , QGraphicsObject , QGraphicsScene , QGraphicsTransform , QHelpEngineCore , QHelpSearchEngine , QHttp , QHttpMultiPart , QIconEnginePlugin , QIconEnginePluginV2 , QImageIOPlugin , QInputContext , QInputContextPlugin , QIODevice , QItemSelectionModel , QKbdDriverPlugin , QLayout , QLibrary , QLocalServer , QMimeData , QMouseDriverPlugin , QMovie , QNetworkAccessManager , QNetworkConfigurationManager , QNetworkCookieJar , QNetworkSession , QObjectCleanupHandler , QPictureFormatPlugin , QPlatformCursor , QPluginLoader , QScreenDriverPlugin , QScriptEngine , QScriptEngineDebugger , QScriptExtensionPlugin , QSessionManager , QSettings , QSharedMemory , QShortcut , QSignalMapper , QSignalSpy , QSocketNotifier , QSound , QSqlDriver , QSqlDriverPlugin , QStyle , QStylePlugin , QSvgRenderer , QSyntaxHighlighter , QSystemTrayIcon , QTcpServer , QTextCodecPlugin , QTextDocument , QTextObject , QThread , QThreadPool , QTimeLine , QTimer , QTranslator , QUiLoader , QUndoGroup , QUndoStack , QValidator , QWebFrame , QWebHistoryInterface , QWebPage , QWebPluginFactory , QWidget , QWSClient , QWSInputMethod ,和 QWSServer

注意: 此類的所有函數 可重入 ,但 connect (), connect (), disconnect (),和 disconnect () are also 綫程安全 .

特性

公共函數

QObject (QObject * parent = 0)
virtual ~QObject ()
bool blockSignals (bool block )
const QObjectList & children () const
bool connect (const QObject * sender , const char * signal , const char * method , Qt::ConnectionType type = Qt::AutoConnection) const
bool disconnect (const char * signal = 0, const QObject * receiver = 0, const char * method = 0)
bool disconnect (const QObject * receiver , const char * method = 0)
void dumpObjectInfo ()
void dumpObjectTree ()
QList<QByteArray> dynamicPropertyNames () const
virtual bool event (QEvent * e )
virtual bool eventFilter (QObject * watched , QEvent * event )
T findChild (const QString & name = QString()) const
QList<T> findChildren (const QString & name = QString()) const
QList<T> findChildren (const QRegExp & regExp ) const
bool inherits (const char * className ) const
void installEventFilter (QObject * filterObj )
bool isWidgetType () 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 )
QThread * thread () const

公共槽

void deleteLater ()

信號

void destroyed (QObject * obj = 0)

靜態公共成員

bool connect (const QObject * sender , const char * signal , const QObject * receiver , const char * method , Qt::ConnectionType type = Qt::AutoConnection)
bool connect (const QObject * sender , const QMetaMethod & signal , const QObject * receiver , const QMetaMethod & method , 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 )
const QMetaObject staticMetaObject
QString tr (const char * sourceText , const char * disambiguation = 0, int n = -1)
QString trUtf8 (const char * sourceText , const char * disambiguation = 0, int n = -1)

保護函數

virtual void childEvent (QChildEvent * event )
virtual void connectNotify (const char * signal )
virtual void customEvent (QEvent * event )
virtual void disconnectNotify (const char * signal )
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 )

Q_CLASSINFO ( Name , Value )
Q_DISABLE_COPY ( Class )
Q_EMIT
Q_ENUMS (...)
Q_FLAGS (...)
Q_INTERFACES (...)
Q_INVOKABLE
Q_OBJECT
Q_PROPERTY (...)
Q_SIGNAL
Q_SIGNALS
Q_SLOT
Q_SLOTS

詳細描述

The QObject 類是所有 Qt 對象的基類。

QObject 是心髒在 Qt 對象模型 。該模型的中心特徵是非常強大的無縫對象通信機製,稱為 信號/槽 。可以連接信號到槽采用 connect () 和銷毀連接采用 disconnect ()。為避免從不結束通知循環,可以臨時阻塞信號采用 blockSignals ()。保護函數 connectNotify () 和 disconnectNotify () 使之可能跟蹤連接。

QObjects organize themselves in 對象樹 。當創建 QObject 采用另一對象作為父級,對象將自動把自身添加到父級的 children () 列錶。父級擁有對象的所有權;即:它將在其析構函數中自動刪除其子級。可以查找對象通過名稱和可選類型,使用 findChild () 或 findChildren ().

每個對象都有 objectName () 且可以找到其類名憑藉相應 metaObject () (見 QMetaObject::className ())。可以確定對象的類是否繼承另一個類在 QObject 繼承層次結構通過使用 inherits () 函數。

當對象被刪除時,它發射 destroyed () signal. You can catch this signal to avoid dangling references to QObjects .

QObjects can receive events through event () 和過濾其它對象的事件。見 installEventFilter () 和 eventFilter () 瞭解細節。方便處理程序 childEvent (),可以重實現以捕獲子級事件。

最後但最重要, QObject 提供 Qt 支持的基本計時器;見 QTimer 瞭解計時器的高級支持。

預告 Q_OBJECT 宏是強製性的對於實現信號、槽或特性的任何對象而言。還需要運行 元對象編譯器 在源文件。強烈推薦使用此宏在所有子類化的 QObject 不管它們是否實際使用信號、槽及特性,由於不這樣做可能導緻某些函數顯露奇怪行為。

所有 Qt 小部件繼承 QObject 。方便函數 isWidgetType () 返迴對象是否是實際 Widget。它快得多相比 qobject_cast < QWidget *>( obj ) 或 obj -> inherits (" QWidget ").

某些 QObject 函數,如 children (),返迴 QObjectList . QObjectList 是 typedef 對於 QList < QObject *>.

綫程親緣關係

A QObject 實例稱擁有 綫程親緣關係 ,或者它 lives 在某個綫程中。當 QObject 接收 隊列信號 張貼事件 ,槽或事件處理程序將運行在對象存活的綫程中。

注意: QObject 沒有綫程傾嚮性 (也就是說,若 thread () 返迴 0),或者若它存活在沒有正運行事件循環的綫程中,那麼它無法接收隊列信號或張貼事件。

默認情況下, QObject 活在創建它的綫程中。可以查詢對象的綫程傾嚮性使用 thread () 和改變是使用 moveToThread ().

所有 QObjects must live in the same thread as their parent. Consequently:

注意: A QObject 的成員變量 do not 自動變為其子級。父/子關係的設置必須通過將指針傳遞給子級的 constructor ,或者通過調用 setParent ()。沒有這一步,對象的成員變量會留在舊綫程中當 moveToThread () 被調用。

No copy constructor or assignment operator

QObject 既沒有拷貝構造函數,也沒有賦值運算符。這是設計的。而實際上,它們的聲明是在 private 區間采用宏 Q_DISABLE_COPY ()。事實上,所有 Qt 類派生自 QObject (直接或間接) 使用此宏來聲明它們的拷貝構造函數和賦值運算符是私有的。找到原因在討論有關 標識 vs 值 在 Qt 對象模型 頁麵。

主要後果是應使用指針指嚮 QObject (或 QObject 子類),否則可能引誘您使用 QObject 子類作為值。例如,若沒有拷貝構造函數,就不可以使用子類化的 QObject 作為值以存儲在某種容器類中。必須存儲指針。

自動連接

Qt 元對象係統提供信號/槽自動連接機製介於 QObject 子類及其子級。隻要采用閤適對象名稱定義對象,且槽遵循簡單命名約定,就可以在運行時履行此連接通過 QMetaObject::connectSlotsByName () 函數。

uic 生成援引此函數的代碼,以使錶單小部件之間能夠履行自動連接,創建采用 Qt Designer 。更多信息關於使用自動連接采用 Qt Designer 的給齣在 在應用程序中使用 Designer UI 文件 章節的 Qt Designer 手冊。

動態特性

從 Qt 4.2 起,可以添加動態特性和移除從 QObject 實例在運行時。編譯時不需要聲明動態特性,它們仍提供如靜態特性的相同優點且操縱是使用相同 API - 使用 property () 讀取它們和 setProperty () 以寫入它們。

從 Qt 4.3 起,動態特性的支持通過 Qt Designer ,且標準 Qt Widget 和用戶創建的錶單兩者都可以賦予動態特性。

國際化 (i18n)

所有 QObject 子類都支持 Qt 翻譯特徵,使之可能將應用程序用戶界麵翻譯成不同語言。

為使對用戶可見的文本可翻譯,必須將它包裹在調用 tr () 函數。這的詳細解釋在 編寫翻譯源代碼 文檔。

另請參閱 QMetaObject , QPointer , QObjectCleanupHandler , Q_DISABLE_COPY (),和 對象樹 & 所有權 .

特性文檔編製

objectName : QString

This property holds the name of this object.

可按名稱 (和類型) 查找對象,使用 findChild ()。可找到一組對象采用 findChildren ().

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

默認情況下,此特性包含空字符串。

訪問函數:

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

另請參閱 metaObject () 和 QMetaObject::className ().

成員函數文檔編製

QObject:: QObject ( QObject * parent = 0)

構造對象采用父級對象 parent .

對象的父級可以被視為對象的所有者。例如, 對話框 是父級對於 OK and Cancel 按鈕 (它包含的)。

父級對象的析構函數會銷毀所有子級對象。

設置 parent 為 0 構造沒有父級的對象。若對象是 Widget,它將變為頂層窗口。

另請參閱 parent (), findChild (),和 findChildren ().

[虛擬] QObject:: ~QObject ()

銷毀對象,刪除其所有子級對象。

自動斷開到/自對象的所有信號連接,並從事件隊列移除對象的任何待決張貼事件。不管怎樣,經常更安全使用 deleteLater () 而不是刪除 QObject 子類直接。

警告: 刪除所有子級對象。若這些對象中的任一在堆棧 (或全局) 中,程序遲早會崩潰。不推薦從父級外部保持子級對象的指針。若仍然這樣做, destroyed () 信號給予機會以檢測對象何時被銷毀。

警告: 刪除 QObject 當等待交付的待決事件會導緻崩潰時。不得刪除 QObject 直接,若它存在於目前執行綫程的不同綫程中。使用 deleteLater () 代替,將導緻事件循環刪除對象在所有待決事件被交付給對象之後。

另請參閱 deleteLater ().

bool QObject:: blockSignals ( bool block )

block 為 true,阻塞由此對象發射的信號 (即:發射信號不會援引與其連接的任何東西)。若 block 為 false,不會發生這種阻塞。

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

注意, destroyed () 信號會被發射,即使此對象的信號已被阻塞。

另請參閱 signalsBlocked ().

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

此事件處理程序可以在子類中重實現,以接收子級事件。事件被傳入 event 參數。

QEvent::ChildAdded and QEvent::ChildRemoved 事件被發送給對象,當添加 (或移除) 子級時。在這 2 種情況下,隻能依賴的子級是 QObject ,或者若 isWidgetType () returns true, a QWidget 。(這是因為,在 ChildAdded 情況下,子級尚未被完全構造,而在 ChildRemoved 情況下,它可能已經被銷毀)。

QEvent::ChildPolished 事件被發送給 Widget 當子級被拋光時,或者當添加拋光子級時。若收到子級拋光事件,子級的構造通常已完成。不管怎樣,這不保證,且在 Widget 構造函數執行期間可能交付多個拋光事件。

對於每個子級 Widget,接收一個 ChildAdded 事件,零個或多個 ChildPolished 事件,和一個 ChildRemoved 事件。

The ChildPolished 事件被省略若子級立即被移除在被添加之後。若子級在構建和銷毀期間中被多次拋光,則可能收到同一子級的幾個子級拋光事件,每次采用不同虛擬錶格。

另請參閱 event ().

const QObjectList & QObject:: children () const

返迴子級對象的列錶。 QObjectList 類的定義在 <QObject> 頭文件,如下所示:

typedef QList<QObject*> QObjectList;
					

第 1 添加子級是 first 對象在列錶中,且最後添加子級是 last 對象在列錶中,即:新子級被追加在末尾。

注意:列錶次序改變,當 QWidget 子級 raised or lowered 。被提升 Widget 變為最後列錶對象,被降低 Widget 變為第一列錶對象。

另請參閱 findChild (), findChildren (), parent (),和 setParent ().

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

創建連接為給定 type signal sender 對象到 method receiver object. Returns true if the connection succeeds; otherwise returns false.

必須使用 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 .

信號可以連接到多個槽和信號。多個信號可以連接到一個槽。

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

The function returns true if it successfully connects the signal to the slot. It will return false if it cannot create the connection, for example, if QObject 無法驗證存在 signal or method , or if their signatures aren't compatible.

默認情況下,製作的每個連接都會發齣信號;重復連接發射 2 個信號。可以斷開所有這些連接采用一個 disconnect () 調用。若傳遞 Qt::UniqueConnection type , the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return false.

可選 type 參數描述要建立的連接類型。尤其,它確定特定信號是立即交付給槽,還是稍後排隊交付。若信號排隊,參數必須是 Qt 元對象係統已知類型,因為 Qt 需要拷貝自變量以將它們存儲在幕後事件中。若試著使用排隊連接且獲得錯誤消息

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

call qRegisterMetaType () 以注冊數據類型在建立連接之前。

注意: 此函數是 綫程安全 .

另請參閱 disconnect (), sender (), qRegisterMetaType (),和 Q_DECLARE_METATYPE ().

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

創建連接為給定 type signal sender 對象到 method receiver object. Returns true if the connection succeeds; otherwise returns false.

This function works in the same way as connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type) but it uses QMetaMethod 來指定信號和方法。

該函數在 Qt 4.8 引入。

另請參閱 connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type).

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

注意: 此函數是 綫程安全 .

另請參閱 disconnect ().

[virtual protected] void QObject:: connectNotify (const char * signal )

此虛函數被調用,當有東西已連接到 signal 在此對象。

若想要比較 signal with a specific signal, use QLatin1String SIGNAL() macro as follows:

if (QLatin1String(signal) == SIGNAL(valueChanged(int))) {
    // signal is valueChanged(int)
}
					

If the signal contains multiple parameters or parameters that contain spaces, call QMetaObject::normalizedSignature () on the result of the SIGNAL() 宏。

警告: 此函數違反瞭麵嚮對象的模塊化原則。不管怎樣,它可能很有用僅當某些東西連接到信號時,纔需要履行昂貴的初始化。

另請參閱 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() 的事件循環。

注意: 多次調用此函數是安全的;當交付首個延遲刪除事件時,會從事件隊列移除對象的任何待決事件。

另請參閱 destroyed () 和 QPointer .

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

此信號立即發射先於對象 obj 被銷毀,且不阻塞。

立即銷毀對象的所有子級,在此信號發射後。

另請參閱 deleteLater () 和 QPointer .

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

斷開連接 signal 在對象 sender from method 在對象 receiver . Returns true if the connection is successfully broken; otherwise returns 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 可以用作通配符,分彆意味著任何信號、任何接收對象、或在接收對象中的任何槽。

The sender 可以從不為 0 (無法在信號調用中斷開來自多個對象的信號)。

signal 為 0,它斷開連接 receiver and method 從任何信號。若沒有,僅斷開連接指定信號。

receiver 為 0,它斷開連接任何東西連接到 signal 。若不,對象中的槽除瞭 receiver 不被斷開連接。

method 為 0,它斷開連接任何東西連接到 receiver 。若不,僅槽稱為 method 會被斷開連接,且單獨剩下所有其它槽。 method 必須為 0 若 receiver 被省略,所以無法斷開連接所有對象中的具體命名槽。

注意: 此函數是 綫程安全 .

另請參閱 connect ().

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

斷開連接 signal 在對象 sender from method 在對象 receiver . Returns true if the connection is successfully broken; otherwise returns false.

This function provides the same possibilities like disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) but uses QMetaMethod 來錶示要斷開的信號和方法。

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

  1. signal 不是發送者類成員 (或其父級類成員)。
  2. method 不是接收者類成員 (或其父級類成員)。
  3. signal 實例錶示不是信號。

QMetaMethod() 可以用作通配符,意味著任何信號、或在接收對象中的任何槽。以相同方式,0 可以用於 receiver 意味著任何接收對象。在此情況下,方法也應該是 QMetaMethod()。 sender 參數從不應該為 0。

該函數在 Qt 4.8 引入。

另請參閱 disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method).

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

此函數重載 disconnect ().

斷開連接 signal from method of receiver .

信號/槽連接被移除,當涉及的對象被銷毀時。

注意: 此函數是 綫程安全 .

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

此函數重載 disconnect ().

斷開連接此對象的所有信號從 receiver 's method .

信號/槽連接被移除,當涉及的對象被銷毀時。

[virtual protected] void QObject:: disconnectNotify (const char * signal )

此虛函數被調用,當有東西已斷開連接從 signal 在此對象。

connectNotify () 例如如何比較 signal 采用特定信號。

警告: 此函數違反瞭麵嚮對象的模塊化原則。不管怎樣,它可能很有用為優化昂貴資源的訪問。

另請參閱 disconnect () 和 connectNotify ().

void QObject:: dumpObjectInfo ()

將有關此對象的信號連接等信息轉儲到調試輸齣。

This function is useful for debugging, but does nothing if the library has been compiled in release mode (i.e. without debugging information).

另請參閱 dumpObjectTree ().

void QObject:: dumpObjectTree ()

將子級樹轉儲到調試輸齣。

This function is useful for debugging, but does nothing if the library has been compiled in release mode (i.e. without debugging information).

另請參閱 dumpObjectInfo ().

QList < QByteArray > QObject:: dynamicPropertyNames () const

返迴被動態添加到對象的所有特性的名稱,使用 setProperty ().

該函數在 Qt 4.2 引入。

[虛擬] bool QObject:: event ( QEvent * e )

此虛函數接收對象事件並返迴 true,若事件 e 被識彆並處理。

event() 函數可以重實現,以定製對象行為。

另請參閱 installEventFilter (), timerEvent (), QApplication::sendEvent (), QApplication::postEvent (),和 QWidget::event ().

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

過濾事件,若已將此對象安裝成事件過濾器對於 watched 對象。

在此函數的重實現中,若希望過濾 event 即:停止進一步處理,返迴 true;否則返迴 false。

範例:

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

注意:在以上範例中,未處理事件被傳遞給基類的 eventFilter() 函數,由於基類可能齣於自已的內部目的有重實現 eventFilter()。

警告: 若在此函數中刪除接收者對象,確保返迴 true。否則,Qt 將把事件轉發給被刪除對象,且程序可能崩潰。

另請參閱 installEventFilter ().

T QObject:: findChild (const QString & name = QString()) const

返迴此對象的子級可以被鑄造成 T 類型且被稱為 name ,或 0 若沒有這種對象。省略 name argument causes all object names to be matched. The search is performed recursively.

若有多個子級匹配搜索,返迴最直接祖先。若有多個直接祖先,返迴哪個未定義。在此情況下, findChildren () 應該被使用。

此範例返迴子級 QPushButton of parentWidget 命名 "button1" :

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

此範例返迴 QListWidget 子級對於 parentWidget :

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

另請參閱 findChildren ().

QList < T > QObject:: findChildren (const QString & name = QString()) const

返迴此對象的所有子級具有給定 name 可以被鑄造成 T 類型,或空列錶若沒有這種對象。省略 name argument causes all object names to be matched. The search is performed recursively.

以下範例展示如何查找列錶化的子級 QWidget 為指定 parentWidget 命名 widgetname :

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

此範例返迴所有 QPushButton 其是子級對於 parentWidget :

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

另請參閱 findChild ().

QList < T > QObject:: findChildren (const QRegExp & regExp ) const

此函數重載 findChildren ().

返迴此對象的子級,可以被鑄造成 T 類型且擁有的名稱匹配正則錶達式 regExp , or an empty list if there are no such objects. The search is performed recursively.

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

Returns true if this object is an instance of a class that inherits 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);
};
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);
					

The QShortcut 類,例如,使用此技術來攔截快捷鍵按下。

警告: 若刪除接收者對象在 eventFilter () 函數,確保返迴 true。若返迴 false,Qt 把事件發送給已刪除對象,且程序會崩潰。

注意,過濾對象必須與此對象在同一綫程中。若 filterObj 在不同綫程中, 此函數什麼都不做。若 filterObj 或在調用此函數後此對象被移入不同綫程,不會調用事件過濾器直到 2 對象再次擁有相同綫程親緣關係 (它 not 被移除)。

另請參閱 removeEventFilter (), eventFilter (),和 event ().

bool QObject:: isWidgetType () const

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

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

void QObject:: killTimer ( int id )

殺除計時器采用計時器標識符 id .

計時器標識符被返迴通過 startTimer () 當計時器事件被啓動時。

另請參閱 timerEvent () 和 startTimer ().

[虛擬] 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 .

要將對象移至主綫程,使用 QApplication::instance () 檢索指嚮當前應用程序的指針,然後使用 QApplication::thread () 來檢索應用程序在其中存活的綫程。例如:

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

targetThread 為 0, 停止此對象及其子級的所有事件處理。

注意,對象的所有活動計時器都將被重置。計時器先在當前綫程中停止並重啓 (采用相同間隔) 在 targetThread 。因此,在綫程之間不斷移動對象可以無限期推遲計時器事件。

A QEvent::ThreadChange 事件被發送給此對象,恰好在改變綫程親緣關係之前。可以處理此事件以履行任何特殊處理。注意,張貼給此對象的任何新事件都將被處理在 targetThread .

警告: 此函數是 not 綫程安全的;當前綫程必須與當前綫程親緣關係相同。換句話說,此函數隻可以把對象從當前綫程 "壓入" 到另一綫程,它不可以從任意綫程 "拉齣" 對象到當前綫程。

另請參閱 thread ().

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

如以上代碼片段闡明,可以使用此函數以避免發射無人監聽的信號。

警告: 此函數違反瞭麵嚮對象的模塊化原則。不管怎樣,它可能很有用僅當某些東西連接到信號時,纔需要履行昂貴的初始化。

void QObject:: removeEventFilter ( QObject * obj )

移除事件過濾器對象 obj 從此對象。忽略請求,若尚未安裝這種事件過濾器。

將自動移除此對象的所有事件過濾器,當此對象被銷毀時。

它始終安全地移除事件過濾器,即使在事件過濾器激活期間 (即:從 eventFilter () 函數)。

另請參閱 installEventFilter (), eventFilter (),和 event ().

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

返迴指嚮發送信號的對象的指針,若在由信號激活的槽中被調用;否則它返迴 0。指針在從此對象的綫程上下文調用此函數的槽執行期間纔有效。

由此函數返迴的指針變為無效若發送者被銷毀,或者,若槽斷開連接發送者信號。

警告: 此函數違反瞭麵嚮對象的模塊化原則。不管怎樣,訪問發送者可能很有用,當多個信號連接到單個槽時。

警告: 如上所述,此函數的返迴值無效,當槽被調用憑藉 Qt::DirectConnection 來自不同於此對象綫程的綫程。不要在這種情景類型下使用此函數。

另請參閱 senderSignalIndex () 和 QSignalMapper .

[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 () 和 QWidget::setParent ().

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

bool QObject:: signalsBlocked () const

Returns true if signals are blocked; otherwise returns false.

信號不被阻塞,默認情況下。

另請參閱 blockSignals ().

int QObject:: startTimer ( int interval )

啓動計時器並返迴計時器標識符,或返迴 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);
};
MyObject::MyObject(QObject *parent)
    : QObject(parent)
{
    startTimer(50);     // 50-millisecond timer
    startTimer(1000);   // 1-second timer
    startTimer(60000);  // 1-minute timer
}
void MyObject::timerEvent(QTimerEvent *event)
{
    qDebug() << "Timer ID:" << event->timerId();
}
					

注意, QTimer 's accuracy depends on the underlying operating system and hardware. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.

The QTimer 類提供高級編程接口,采用單發計時器和計時器信號而不是事件。還有 QBasicTimer 類更輕量相比 QTimer 且不比直接使用計時器 ID 笨拙。

另請參閱 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 = 0, int n = -1)

返迴翻譯版本的 sourceText ,可選基於 disambiguation 字符串和值 n 對於包含多個的字符串;否則返迴 sourceText itself if no appropriate translated string is available.

範例:

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

若相同 sourceText 用於同一上下文中的不同角色,可將額外標識字符串傳入 disambiguation (0 默認情況下)。在 Qt 4.4 及更早版本,這是嚮翻譯者傳遞注釋的首選方式。

範例:

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

編寫翻譯源代碼 瞭解 Qt 一般翻譯機製的詳細描述,和 消除歧義 章節瞭解消除歧義的有關信息。

警告: 此方法纔可重入若有安裝所有翻譯器 before 調用此方法。不支持在履行翻譯時,安裝或移除翻譯器。這樣做可能會導緻崩潰或其它不期望行為。

另請參閱 trUtf8 (), QApplication::translate (), QTextCodec::setCodecForTr (),和 Qt 國際化 .

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

返迴翻譯版本的 sourceText ,或 QString::fromUtf8 ( sourceText ) if there is no appropriate version. It is otherwise identical to tr( sourceText , disambiguation , n ).

Note that using the Utf8 variants of the translation functions is not required if CODECFORTR is already set to UTF-8 in the qmake project file and QTextCodec::setCodecForTr ("UTF-8") is used.

警告: 此方法纔可重入若有安裝所有翻譯器 before 調用此方法。不支持在履行翻譯時,安裝或移除翻譯器。這樣做可能會導緻崩潰或其它不期望行為。

警告: For portability reasons, we recommend that you use escape sequences for specifying non-ASCII characters in string literals to trUtf8(). For example:

label->setText(tr("F\374r \310lise"));
					

另請參閱 tr (), QApplication::translate (),和 Qt 國際化 .

成員變量文檔編製

const QMetaObject QObject:: staticMetaObject

此變量存儲類的元對象。

元對象包含的信息有關類繼承 QObject ,如類名、超類名、特性、信號及槽。每個類包含 Q_OBJECT 宏也將擁有元對象。

元對象信息是信號/槽連接機製和特性係統要求的。 inherits () 函數還利用瞭元對象。

若擁有指嚮對象的指針,可以使用 metaObject () 以檢索該對象關聯的元對象。

範例:

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

另請參閱 metaObject ().

相關非成員

typedef QObjectList

同義詞 QList < QObject *>.

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

此函數重載 qFindChildren()。

此函數相當於 obj -> findChildren <T>( regExp ).

注意: 此函數是為不支持成員模闆函數的 MSVC 6 提供的解決方案。建議在新代碼中使用其它形式。

另請參閱 QObject::findChildren ().

T qobject_cast ( QObject * object )

返迴給定 object 被鑄造成 T 類型,若對象為 T 類型 (或子類);否則返迴 0。若 object 為 0 那麼它也將返迴 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 ().

宏文檔編製

Q_CLASSINFO ( Name , Value )

此宏將額外信息關聯到類,是可用的使用 QObject::metaObject (). Except for the ActiveQt extension, Qt doesn't use this information.

額外信息接受形式化的 Name 字符串和 Value 文字字符串。

範例:

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

另請參閱 QMetaObject::classInfo ().

Q_DISABLE_COPY ( Class )

禁用拷貝構造函數和賦值運算符的使用為給定 Class .

實例化的子類 QObject 不應被認為是可以拷貝 (或賦值) 的值,而是作為唯一標識。這意味著當創建自己的子類化 QObject (直接或間接),應 not 賦予它拷貝構造函數 (或賦值運算符)。不管怎樣,從類中簡單省略它們可能不夠,因為,若過失編寫瞭一些要求拷貝構造函數 (或賦值運算符) 的代碼 (這很容易做到),編譯器會體貼地為您創建它。您必須做更多。

好奇用戶將看到 Qt 類派生自 QObject 通常包括此宏在私有區間:

class MyClass : public QObject
{
  private:
    Q_DISABLE_COPY(MyClass)
};
					

在私有區間聲明拷貝構造函數和賦值運算符,所以,若過失使用瞭它們,編譯器會報錯。

class MyClass : public QObject
{
  private:
     MyClass(const MyClass &);
     MyClass &operator=(const MyClass &);
};
					

即使這樣,也絕對不可能捕獲每種情況。可能被誘惑做像這樣的一些事:

  QWidget w = QWidget();
					

首先,不要這樣做。大多數編譯器將生成使用拷貝構造函數的代碼,所以會報告違反隱私錯誤,但不要求 C++ 編譯器以特定方式為該語句生成代碼。可以生成代碼使用 neither 拷貝構造函數 nor 私有賦值運算符。這種情況不會報錯,但應用程序可能崩潰當調用成員函數從 w .

Q_EMIT

使用此宏替換 發射 關鍵詞對於發射信號,當想要使用 Qt 信號和槽采用 第 3 方信號/槽機製 .

通常使用宏當 no_keywords 的指定是采用 CONFIG 變量在 .pro 文件,但可以使用它甚至在 no_keywords is not 指定。

Q_ENUMS (...)

This macro registers one or several enum types to the meta-object system.

例如:

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

If you want to register an enum that is declared in another class, the enum must be fully qualified with the name of the class defining it. In addition, the class defining the enum has to inherit QObject as well as declare the enum using Q_ENUMS().

另請參閱 Qt 的特性係統 .

Q_FLAGS (...)

This macro registers one or several flags types to 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.

例如,在 QLibrary LoadHints 標誌的聲明方式如下:

class QLibrary : public QObject
{
    ...
    Q_FLAGS(LoadHint LoadHints)
    ...
					

標誌自身聲明的履行是在公共部分 QLibrary 類本身,使用 Q_DECLARE_FLAGS () 宏:

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

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

另請參閱 Qt 的特性係統 .

Q_INTERFACES (...)

此宏告訴 Qt 類實現哪些接口。使用這當實現插件時。

範例:

class BasicToolsPlugin : public QObject,
                         public BrushInterface,
                         public ShapeInterface,
                         public FilterInterface
{
    Q_OBJECT
    Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)
public:
    ...
};
					

插件和描繪基本工具 範例瞭解細節。

另請參閱 Q_DECLARE_INTERFACE (), Q_EXPORT_PLUGIN2 (),和 如何創建 Qt 插件 .

Q_INVOKABLE

Apply this macro to definitions 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() 函數使用 Q_INVOKABLE 進行標記,導緻它嚮元對象係統注冊並使其能夠被援引使用 QMetaObject::invokeMethod ()。由於 normalMethod() 函數未按此方式注冊,不可以援引它使用 QMetaObject::invokeMethod ().

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 . 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. Q_GADGET makes a class member, staticMetaObject ,可用。 staticMetaObject 是類型 QMetaObject 並提供對枚舉的訪問聲明采用 Q_ENUMS . Q_GADGET is provided only for C++.

另請參閱 元對象係統 , 信號和槽 ,和 Qt 的特性係統 .

Q_PROPERTY (...)

此宏用於聲明類特性,當繼承 QObject 。特性的行為像類數據成員,但它們擁有的額外特徵可訪問透過 元對象係統 .

Q_PROPERTY(type name
           READ getFunction
           [WRITE setFunction]
           [RESET resetFunction]
           [NOTIFY notifySignal]
           [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_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 指定。