QObject Class Reference

[ QtCore module]

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

Inherited by AbstractAudioOutput , Notifier , Effect , MediaController , MediaObject , QAbstractAnimation , QAbstractEventDispatcher , QAbstractItemDelegate , QAbstractItemModel , QAbstractMessageHandler , QAbstractNetworkCache , QAbstractState , QAbstractTextDocumentLayout , QAbstractTransition , QAbstractUriResolver , QAbstractVideoSurface , QAction , QActionGroup , QAssistantClient , QAudioInput , QAudioOutput , QAxObject , QButtonGroup , QClipboard , QCompleter , QCoreApplication , QDataWidgetMapper , QDBusAbstractAdaptor , QDBusAbstractInterface , QDBusPendingCallWatcher , QDBusServiceWatcher , QDeclarativeComponent , QDeclarativeContext , QDeclarativeEngine , QDeclarativeExpression , QDeclarativeExtensionPlugin , QDeclarativePropertyMap , QDesignerFormEditorInterface , QDesignerFormWindowManagerInterface , QDrag , QEventLoop , QExtensionFactory , QExtensionManager , QFileSystemWatcher , QFtp , QGesture , QGLShader , QGLShaderProgram , QGraphicsAnchor , QGraphicsEffect , QGraphicsItemAnimation , QGraphicsObject , QGraphicsScene , QGraphicsTransform , QHelpEngineCore , QHelpSearchEngine , QHttp , QHttpMultiPart , QInputContext , QIODevice , QItemSelectionModel , QLayout , QLibrary , QLocalServer , QMimeData , QMovie , QNetworkAccessManager , QNetworkConfigurationManager , QNetworkCookieJar , QNetworkSession , QObjectCleanupHandler , QPluginLoader , QPyDeclarativePropertyValueSource , QPyDesignerContainerExtension , QPyDesignerCustomWidgetCollectionPlugin , QPyDesignerCustomWidgetPlugin , QPyDesignerMemberSheetExtension , QPyDesignerPropertySheetExtension , QPyDesignerTaskMenuExtension , QPyTextObject , QScriptEngine , QScriptEngineDebugger , QSessionManager , QSettings , QSharedMemory , QShortcut , QSignalMapper , QSocketNotifier , QSound , QSqlDriver , QStyle , QSvgRenderer , QSyntaxHighlighter , QSystemTrayIcon , QTcpServer , QTextDocument , QTextObject , QThread , QThreadPool , QTimeLine , QTimer , QTranslator , QUndoGroup , QUndoStack , QValidator , QWebFrame , QWebHistoryInterface , QWebPage , QWebPluginFactory and QWidget .

方法

Static Methods

Special Methods

Qt Signals

Static Members


详细描述

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

QObject 是心脏,对于 Qt 对象 Model . The central feature in this model is a very powerful mechanism for seamless object communication called 信号和槽 . You can connect a signal to a slot with connect () and destroy the connection with disconnect (). To avoid never ending notification loops you can temporarily block signals with blockSignals ()。 protected functions connectNotify () 和 disconnectNotify () make it possible to track connections.

QObjects organize themselves in 对象树 . When you create a QObject with another object as parent, the object will automatically add itself to the parent's children () list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild () 或 findChildren ().

Every object has an objectName () and its class name can be found via the corresponding metaObject () (see QMetaObject.className ()). You can determine whether the object's class inherits another class in the QObject inheritance hierarchy by using the 继承 () 函数。

When an object is deleted, it emits a destroyed () signal. You can catch this signal to avoid dangling references to QObjects .

QObjects can receive events through event () and filter the events of other objects. See installEventFilter () 和 eventFilter () for details. A convenience handler, childEvent (), can be reimplemented to catch child events.

Last but not least, QObject provides the basic timer support in Qt; see QTimer for high-level support for timers.

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

All Qt widgets inherit QObject. The convenience function isWidgetType () 返回 whether an object is actually a widget. It is much faster than qobject_cast < QWidget *>( obj ) or obj -> 继承 (" QWidget ").

Some QObject functions, e.g. children (), return a QObjectList . QObjectList is a typedef for QList <QObject *>.

线程倾向性

据说 QObject 实例拥有 线程倾向性 ,或 that it lives in a certain thread. When a QObject receives a queued signal posted event , the slot or event handler will run in the thread that the object lives in.

注意: If a QObject has no thread affinity (that is, if thread () returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.

By default, a QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread () and changed using moveToThread ().

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

\li setParent () will fail if the two QObjects involved live in different threads. \li When a QObject is moved to another thread, all its children will be automatically moved too. \li moveToThread () will fail if the QObject has a parent. \li If QObjects are created within QThread.run (), they cannot become children 的 QThread object because the QThread does not live in the thread that calls QThread.run ().

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

No copy constructor or assignment operator

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

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

自动连接

Qt's meta-object system provides a mechanism to automatically connect signals and slots between QObject subclasses and their children. As long as objects are defined with suitable object names, and slots follow a simple naming convention, this connection can be performed at run-time by the QMetaObject.connectSlotsByName () 函数。

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

动态特性

From Qt 4.2, dynamic properties can be added to and removed from QObject instances at run-time. Dynamic properties do not need to be declared at compile-time, yet they provide the same advantages as static properties and are manipulated using the same API - using property () to read them and setProperty () to write them.

From Qt 4.3, dynamic properties are supported by Qt Designer , and both standard Qt widgets and user-created forms can be given dynamic properties.

国际化 (i18n)

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

To make user-visible text translatable, it must be wrapped in calls to the tr () function. This is explained in detail in the Writing Source Code for Translation 文档。


方法文档编制

QObject.__init__ ( self , QObject   parent  = None)

parent argument, if not None, causes self to be owned by Qt instead of PyQt.

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

The parent of an object may be viewed as the object's owner. For 实例, 对话框 is the parent of the OK and Cancel 按钮 (它包含的)。

The destructor of a parent object destroys all child 对象。

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

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

bool QObject.blockSignals ( self , bool  b )

block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). If block 为 false,不会发生这种阻塞。

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

注意: destroyed () signal will be emitted even if the signals for this object have been blocked.

另请参阅 signalsBlocked ().

QObject.childEvent ( self , QChildEvent )

This event handler can be reimplemented in a subclass to receive child events. The event is passed in the event 参数。

QEvent.ChildAdded and QEvent.ChildRemoved events are sent to objects when children are added or removed. In both cases you can only rely on the child being a QObject ,或者若 isWidgetType () returns true, a QWidget . (This is because, in the ChildAdded case, the child is not yet fully constructed, and in the ChildRemoved case it might have been destructed already).

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

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

ChildPolished event is omitted if a child is removed immediately after it is added. If a child is polished several times during construction and destruction, you may receive several child polished events for the same child, each time with a different virtual table.

另请参阅 event ().

list-of-QObject QObject.children ( self )

返回子级对象的列表。 QObjectList class is defined 在 <QObject> 头文件,如下所示:

 typedef QList<QObject*> QObjectList;
			

第一添加子级是 first object in the list and the last child added is the last object in the list, i.e. new children are appended at the end.

注意:列表次序改变,当 QWidget 子级 raised or lowered . A widget that is raised becomes the last object in the list, and a widget that is lowered becomes the first object in the list.

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

bool QObject.connect ( QObject , SIGNAL(), QObject , SLOT(), Qt.ConnectionType  = Qt.AutoConnection)

Creates a connection of the given type signal sender object to the 方法 in the receiver object. Returns true if the connection succeeds; otherwise returns false.

必须使用 SIGNAL() and SLOT() macros when specifying the signal 方法 , for example:

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

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

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

A signal can also be connected to another signal:

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

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

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

If a signal is connected to several slots, the slots are activated in the same order 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 is unable to verify the existence of either signal or 方法 , or if their signatures aren't compatible.

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

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

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

call qRegisterMetaType () 到 register the data type before you establish the connection.

注意: 此函数是 thread-safe .

另请参阅 disconnect (), sender (), qRegisterMetaType (),和 Q_DECLARE_METATYPE ().

bool QObject.connect ( QObject , SIGNAL(), callable, Qt.ConnectionType  = Qt.AutoConnection)

Creates a connection of the given type signal sender object to the 方法 in the 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 to specify signal and method.

该函数在 Qt 4.8 引入。

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

bool QObject.connect ( self , QObject , SIGNAL(), SLOT(), Qt.ConnectionType  = Qt.AutoConnection)

此函数重载 connect ().

Connects signal sender object to this object's 方法 .

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

Every connection you make emits a signal, so duplicate connections emit two signals. You can break a connection using disconnect ().

注意: 此函数是 thread-safe .

另请参阅 disconnect ().

QObject.connectNotify ( self , SIGNAL()  signal )

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

If you want to compare signal with a specific signal, 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() 宏。

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

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

QObject.customEvent ( self , QEvent )

This event handler can be reimplemented in a subclass to receive custom events. Custom events are user-defined events with a type value at least as large as the QEvent.User item of the QEvent.Type enum, and is typically a QEvent subclass. The event is passed in the event 参数。

另请参阅 event () 和 QEvent .

QObject.deleteLater ( self )

This method is also a Qt slot with the C++ signature void deleteLater() .

安排删除此对象。

The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication.exec ()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.

Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.

注意: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.

另请参阅 destroyed () and QPointer .

bool QObject.disconnect ( QObject , SIGNAL(), QObject , SLOT())

Disconnects signal in object sender from 方法 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 everything connected to an object's signals:
     disconnect(myObject, 0, 0, 0);
    					

    equivalent to the non-static overloaded function

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

    equivalent to the non-static overloaded function

     myObject->disconnect(SIGNAL(mySignal()));
    					
  3. Disconnect a specific receiver:
     disconnect(myObject, 0, myReceiver, 0);
    					

    equivalent to the non-static overloaded function

     myObject->disconnect(myReceiver);
    					

0 may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", 分别。

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

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

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

方法 is 0, it disconnects anything that is connected to receiver . If not, only slots named 方法 将是 disconnected, and all other slots are left alone. The 方法 must be 0 if receiver is left out, so you cannot disconnect a specifically-named slot on all objects.

注意: 此函数是 thread-safe .

另请参阅 connect ().

bool QObject.disconnect ( QObject , SIGNAL(), callable)

Disconnects signal in object sender from 方法 in object 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 to represent the signal and the method to be disconnected.

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

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

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

该函数在 Qt 4.8 引入。

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

QObject.disconnectNotify ( self , SIGNAL()  signal )

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

connectNotify () for an example of how to compare signal with a specific 信号。

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

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

QObject.dumpObjectInfo ( self )

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

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

另请参阅 dumpObjectTree ().

QObject.dumpObjectTree ( self )

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

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

另请参阅 dumpObjectInfo ().

list-of-QByteArray QObject.dynamicPropertyNames ( self )

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

该函数在 Qt 4.2 引入。

QObject.emit ( self , SIGNAL(), ...)

bool QObject.event ( self , QEvent )

This virtual function receives events to an object and should return true if the event e 被识别并被处理。

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

另请参阅 installEventFilter (), timerEvent (), QApplication.sendEvent (), QApplication.postEvent (), and QWidget.event ().

bool QObject.eventFilter ( self , QObject , QEvent )

Filters events if this object has been installed as an event filter for the watched 对象。

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.

范例:

 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.

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

QObject QObject.findChild ( self , type  type , QString  name  = QString())

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. 省略 name argument causes all object names to be matched. The search is performed recursively.

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.

此范例返回子级 QPushButton of parentWidget named "button1" :

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

此范例返回 QListWidget child of parentWidget :

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

另请参阅 findChildren ().

QObject QObject.findChild ( self , tuple  types , QString  name  = QString())

list-of-QObject QObject.findChildren ( self , type  type , QString  name  = QString())

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.

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

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

此范例返回所有 QPushButton s that are children of parentWidget :

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

另请参阅 findChild ().

list-of-QObject QObject.findChildren ( self , tuple  types , QString  name  = QString())

此函数重载 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.

list-of-QObject QObject.findChildren ( self , type  type , QRegExp   regExp )

list-of-QObject QObject.findChildren ( self , tuple  types , QRegExp   regExp )

bool QObject.inherits ( self , str  classname )

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

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

QObject.installEventFilter ( self , QObject )

安装事件过滤器 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 接收事件凭借其 eventFilter () 函数。 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);
			

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

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

Note that the filtering object must be in the same thread as this object. If filterObj is in a different thread, this function does nothing. If either filterObj or this object are moved to a different thread after calling this function, the event filter will not be called until both objects have the same thread affinity again (it is not removed).

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

bool QObject.isWidgetType ( self )

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

调用此函数相当于调用 inherits(" QWidget "), except that it is much faster.

QObject.killTimer ( self , int  id )

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

计时器标识符被返回通过 startTimer () when a timer event is started.

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

QMetaObject QObject.metaObject ( self )

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

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 继承 () function also makes use of the meta-object.

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

范例:

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

另请参阅 staticMetaObject .

QObject.moveToThread ( self , QThread   thread )

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 () 到 retrieve a pointer to the current application, and then use QApplication.thread () 到 retrieve the thread in which the application lives. For example:

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

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 在 targetThread .

警告: 此函数是 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 ().

QString QObject.objectName ( self )

QObject QObject.parent ( self )

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

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

QVariant QObject.property ( self , str  name )

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

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

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

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

QObject.pyqtConfigure ( self , object)

int QObject.receivers ( self , SIGNAL()  signal )

返回接收者数为连接到 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);
 }
			

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

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

QObject.removeEventFilter ( self , QObject )

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

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

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

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

QObject QObject.sender ( self )

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.

警告: 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 槽。

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

int QObject.senderSignalIndex ( self )

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

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

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

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

该函数在 Qt 4.8 引入。

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

QObject.setObjectName ( self , QString  name )

QObject.setParent ( self , QObject )

QObject argument, if not None, causes self to be owned by Qt instead of PyQt.

使对象子级 parent .

另请参阅 parent () 和 QWidget.setParent ().

bool QObject.setProperty ( self , str  name , QVariant  value )

Sets the value of the object's name 特性到 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 () 和 dynamicPropertyNames ().

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

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

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

bool QObject.signalsBlocked ( self )

Returns true if signals are blocked; otherwise returns false.

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

另请参阅 blockSignals ().

int QObject.startTimer ( self , int  interval )

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 毫秒 until killTimer () 被调用。 若 interval is 0, then the timer event occurs once every time there are no more window system events to process.

虚拟 timerEvent () function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer 事件。

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

范例:

 class MyObject : public QObject
 {
     Q_OBJECT
 public:
     MyObject(QObject *parent = 0);
 protected:
     void timerEvent(QTimerEvent *event);
 };
 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.

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

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

QThread QObject.thread ( self )

返回对象所在的线程。

另请参阅 moveToThread ().

QObject.timerEvent ( self , QTimerEvent )

This event handler can be reimplemented in a subclass to receive timer events for the object.

QTimer provides a higher-level interface to the timer functionality, and also more general information about timers. The timer event is passed in the event 参数。

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

QString QObject.tr ( self , str  sourceText , str  disambiguation  = None, int  n  = -1)

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

范例:

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

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

范例:

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

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

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

另请参阅 trUtf8 (), QApplication.translate (), QTextCodec.setCodecForTr (), and Internationalization with Qt .

QString QObject.trUtf8 ( self , str  sourceText , str  disambiguation  = None, 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.

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

警告: 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 (), and Internationalization with Qt .

object QObject.__getattr__ ( self , str  name )


Qt Signal Documentation

void destroyed (QObject* = 0)

This is the default overload of this signal.

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

All the objects's children are destroyed immediately after this 信号被发射。

另请参阅 deleteLater () 和 QPointer .


Member Documentation

QMetaObject staticMetaObject

This member should be treated as a constant.

此变量存储类的元对象。

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 继承 () function also makes use of the meta-object.

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

范例:

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

另请参阅 metaObject ().